public void UpdateCarsPositions(NetIncomingMessage msg) { int carCount = msg.ReadInt32(); for (int i = 0; i < carCount; i++) { int carID = msg.ReadInt32(); int prefabIndex = msg.ReadInt32(); Vector3 pos = new Vector3(); pos.x = msg.ReadFloat(); pos.y = msg.ReadFloat(); pos.z = msg.ReadFloat(); Quaternion rot2 = new Quaternion(); rot2.x = msg.ReadFloat(); rot2.y = msg.ReadFloat(); rot2.z = msg.ReadFloat(); rot2.w = msg.ReadFloat(); if (!m_fakeCarsCurrentPool.ContainsKey(carID) && m_fakeCarsPoolAvailable.Count > 0) { var obj = m_fakeCarsPoolAvailable[0]; m_fakeCarsPoolAvailable.RemoveAt(0); m_fakeCarsPoolInUse.Add(obj); m_fakeCarsCurrentPool.Add(carID, obj); obj.GameObject.GetComponent <VehicleNetworkView>().ResertState(); obj.GameObject.GetComponent <VehicleNetworkView>().m_id = carID; var prefab = PrefabCollection <VehicleInfo> .GetPrefab((uint)prefabIndex); obj.GameObject.GetComponent <MeshFilter>().sharedMesh = prefab.m_mesh; obj.GameObject.GetComponent <MeshRenderer>().sharedMaterial = prefab.m_material; obj.GameObject.SetActive(true); } if (m_fakeCarsCurrentPool.ContainsKey(carID)) { m_fakeCarsCurrentPool[carID].GameObject.GetComponent <VehicleNetworkView>().OnNetworkData(msg.ReceiveTime, pos, rot2); } } }
public override void Awake() { concretePrefab = PrefabCollection <NetInfo> .FindLoaded("Metro Track Ground"); concretePrefabNoBar = PrefabCollection <NetInfo> .FindLoaded("Metro Track Ground NoBar"); concreteTwoLaneOneWayPrefab = PrefabCollection <NetInfo> .FindLoaded("Metro Track Ground Two-Lane One-Way"); concreteTwoLaneOneWayPrefabNoBar = PrefabCollection <NetInfo> .FindLoaded("Metro Track Ground Two-Lane One-Way NoBar"); concreteLargePrefab = PrefabCollection <NetInfo> .FindLoaded("Metro Track Ground Large"); concreteLargePrefabNoBar = PrefabCollection <NetInfo> .FindLoaded("Metro Track Ground Large NoBar"); concreteSmallPrefab = PrefabCollection <NetInfo> .FindLoaded("Metro Track Ground Small"); concreteSmallPrefabNoBar = PrefabCollection <NetInfo> .FindLoaded("Metro Track Ground Small NoBar"); concreteSmallTwoWayPrefab = PrefabCollection <NetInfo> .FindLoaded("Metro Track Ground Small Two-Way"); concreteSmallTwoWayPrefabNoBar = PrefabCollection <NetInfo> .FindLoaded("Metro Track Ground Small Two-Way NoBar"); steelPrefab = PrefabCollection <NetInfo> .FindLoaded("Steel Metro Track Ground"); steelPrefabNoBar = PrefabCollection <NetInfo> .FindLoaded("Steel Metro Track Ground NoBar"); steelTwoLaneOneWayPrefab = PrefabCollection <NetInfo> .FindLoaded("Steel Metro Track Ground Two-Lane One-Way"); steelTwoLaneOneWayPrefabNoBar = PrefabCollection <NetInfo> .FindLoaded("Steel Metro Track Ground Two-Lane One-Way NoBar"); steelSmallPrefab = PrefabCollection <NetInfo> .FindLoaded("Steel Metro Track Ground Small"); steelSmallPrefabNoBar = PrefabCollection <NetInfo> .FindLoaded("Steel Metro Track Ground Small NoBar"); steelSmallTwoWayPrefab = PrefabCollection <NetInfo> .FindLoaded("Steel Metro Track Ground Small Two-Way"); steelSmallTwoWayPrefabNoBar = PrefabCollection <NetInfo> .FindLoaded("Steel Metro Track Ground Small Two-Way NoBar"); steelLargePrefab = PrefabCollection <NetInfo> .FindLoaded("Steel Metro Track Ground Large"); steelLargePrefabNoBar = PrefabCollection <NetInfo> .FindLoaded("Steel Metro Track Ground Large NoBar"); }
private void HandleCreateNode(NodeCreateCommand command) { NetInfo info = PrefabCollection <NetInfo> .GetPrefab(command.InfoIndex); ushort node = command.NodeId; // Don't allow this node id to be taken (=CreateItem at the creator) Singleton <NetManager> .instance.m_nodes.RemoveUnused(node); Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_position = command.Position; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_flags = NetNode.Flags.Created; Singleton <NetManager> .instance.m_nodes.m_buffer[node].Info = info; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_buildIndex = Singleton <SimulationManager> .instance.m_currentBuildIndex; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_building = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_lane = 0u; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_nextLaneNode = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_nextBuildingNode = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_nextGridNode = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_laneOffset = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_elevation = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_heightOffset = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_problems = Notification.Problem.None; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_transportLine = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_connectCount = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_maxWaitTime = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_coverage = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_tempCounter = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_finalCounter = 0; Singleton <NetManager> .instance.m_nodes.m_buffer[node].m_targetCitizens = 0; info.m_netAI.CreateNode(node, ref Singleton <NetManager> .instance.m_nodes.m_buffer[node]); _initializeNode.Invoke(Singleton <NetManager> .instance, new object[] { node, Singleton <NetManager> .instance.m_nodes.m_buffer[node] }); Singleton <NetManager> .instance.UpdateNode(node); Singleton <NetManager> .instance.UpdateNodeColors(node); Singleton <NetManager> .instance.m_nodes.m_buffer[node].UpdateBounds(node); Singleton <NetManager> .instance.m_nodeCount = ((int)Singleton <NetManager> .instance.m_nodes.ItemCount()) - 1; Singleton <SimulationManager> .instance.m_currentBuildIndex++; }
/* * In here I'm changing the prefabs to have my classes. This way, every time the game instantiates * a prefab that I've changed, that object will run my code. * The prefabs aren't available at the moment of creation of this class, that's why I keep trying to * run it on update. I want to make sure I make the switch as soon as they exist to prevent the game * from instantianting objects without my code. */ private bool TryReplacePrefabs() { Logger.LogInfo("Queueing prefabs for loading..."); Singleton <LoadingManager> .instance.QueueLoadingAction(ActionWrapper(() => { try { Logger.LogInfo("Options: " + TrafficMod.Options); if ((TrafficMod.Options & OptionsManager.ModOptions.RoadCustomizerTool) == OptionsManager.ModOptions.RoadCustomizerTool) { AddTool <RoadCustomizerTool>(ToolsModifierControl.toolController); } if ((TrafficMod.Options & OptionsManager.ModOptions.UseRealisticSpeeds) == OptionsManager.ModOptions.UseRealisticSpeeds) { for (uint i = 0; i < PrefabCollection <CitizenInfo> .LoadedCount(); i++) { CitizenInfo cit = PrefabCollection <CitizenInfo> .GetLoaded(i); cit.m_walkSpeed *= 0.25f; } } AddQueuedActionsToLoadingQueue(); FileManager.ClearCache(); } catch (KeyNotFoundException knf) { Logger.LogInfo("Error initializing a prefab: " + knf.Message + "\n" + knf.StackTrace + "\n"); } catch (Exception e) { Logger.LogInfo("Unexpected " + e.GetType().Name + " initializing prefabs: " + e.Message + "\n" + e.StackTrace + "\n"); } })); Logger.LogInfo("Prefabs queued for loading."); return(true); }
public static void ChangeLoadedRoadColor() { for (uint i = 0; i < PrefabCollection <NetInfo> .LoadedCount(); i++) { NetInfo asset = PrefabCollection <NetInfo> .GetLoaded(i); if (Utils.IsCSUR(asset)) { Utils.SetColor(asset, roadColor); } else if (OptionUI.changeAllRoadColor) { if (asset != null && asset.m_netAI is RoadAI) { //Debug.Log("Process color change for " + asset.name.ToString()); Utils.SetColor(asset, roadColor); } } } }
private static void SetPillarFeature(NetInfo netInfo, string pillarName, PillarType type, Dictionary <NetInfo, BuildingInfo> userModePillars) { if (pillarName == null) { return; } BuildingInfo pillar = null; if (pillarName != NoneValue) { pillar = PrefabCollection <BuildingInfo> .FindLoaded(pillarName); } // save previous set pillar userModePillars[netInfo] = PillarCustomizer.instance.GetActivePillar(netInfo, type); PillarCustomizer.instance.SetPillar(netInfo, type, pillar); }
//based on CitizenManager#RefreshGroupCitizens() private static FastList <ushort> RefreshAnimals() { var animals = new FastList <ushort>(); var num1 = PrefabCollection <CitizenInfo> .PrefabCount(); for (var index = 0; index < num1; ++index) { var prefab = PrefabCollection <CitizenInfo> .GetPrefab((uint)index); if (prefab == null) { continue; } if (prefab.m_citizenAI.IsAnimal()) { animals.Add((ushort)index); } } return(animals); }
private static string GetElevationName(string rawNetInfo, int elevationType) { switch (elevationType) { case 1: return(AssetEditorRoadUtils.TryGetElevated(PrefabCollection <NetInfo> .FindLoaded(rawNetInfo)).name); case 2: return(AssetEditorRoadUtils.TryGetBridge(PrefabCollection <NetInfo> .FindLoaded(rawNetInfo)).name); case 3: return(AssetEditorRoadUtils.TryGetSlope(PrefabCollection <NetInfo> .FindLoaded(rawNetInfo)).name); case 4: return(AssetEditorRoadUtils.TryGetTunnel(PrefabCollection <NetInfo> .FindLoaded(rawNetInfo)).name); default: return(""); // make it return error maybe? } }
public static List <PropInfo> GetAvailableStreetLights() { var streetLights = new List <PropInfo>(); var prefabCount = PrefabCollection <PropInfo> .LoadedCount(); for (uint prefabIndex = 0; prefabIndex < prefabCount; prefabIndex++) { var prefab = PrefabCollection <PropInfo> .GetLoaded(prefabIndex); if (IsStreetLightProp(prefab)) { streetLights.Add(prefab); } } streetLights.Sort((a, b) => string.Compare(a.GetUncheckedLocalizedTitle(), b.GetUncheckedLocalizedTitle(), StringComparison.Ordinal)); return(streetLights); }
private List <PropInfo> GetAvailableCatenaries(CatenaryType type) { var catenaries = new List <PropInfo>(); var prefabCount = PrefabCollection <PropInfo> .LoadedCount(); for (uint prefabIndex = 0; prefabIndex < prefabCount; prefabIndex++) { var prefab = PrefabCollection <PropInfo> .GetLoaded(prefabIndex); if (IsCatenaryProp(prefab, type) && CatenaryUtils.IsCatenaryPropVisibeInUI(prefab)) { catenaries.Add(prefab); } } catenaries.Sort((a, b) => string.Compare(a.GetUncheckedLocalizedTitle(), b.GetUncheckedLocalizedTitle(), StringComparison.Ordinal)); return(catenaries); }
public static VehicleInfo GetVehicleInfo(ref Randomizer randomizer, ItemClass m_class, ushort lineID, string prefabName) { PrefabData prefabData = Array.Find(VehiclePrefabs.instance.GetPrefabs(m_class.m_service, m_class.m_subService, m_class.m_level), item => item.ObjectName == prefabName); if (prefabData != null) { return(PrefabCollection <VehicleInfo> .GetPrefab((uint)prefabData.PrefabDataIndex)); } Utils.LogWarning((object)("Unknown prefab: " + prefabName)); VehicleManager instance = Singleton <VehicleManager> .instance; instance.RefreshTransferVehicles(); int service = (int)m_class.m_service; int subService = (int)m_class.m_subService; int level = (int)m_class.m_level; return(instance.GetRandomVehicleInfo(ref randomizer, (ItemClass.Service)service, (ItemClass.SubService)subService, (ItemClass.Level)level)); }
/// <summary> /// BuildingInfos require more effort because the NotUsedGuide/UnlockMilestone stuff gets into way. /// </summary> void LookupSimulationBuildings(HashSet <string> packages, HashSet <string> assets) { try { Building[] buffer = BuildingManager.instance.m_buildings.m_buffer; int n = buffer.Length; for (int i = 1; i < n; i++) { if (buffer[i].m_flags != Building.Flags.None) { Add(PrefabCollection <BuildingInfo> .PrefabName(buffer[i].m_infoIndex), packages, assets); } } } catch (Exception e) { UnityEngine.Debug.LogException(e); } }
/// <summary> /// generates unique name by adding prefix. /// </summary> /// <param name="excludeCurrent"> /// set to true when renaming /// set to false when cloning. /// </param> public static string GetUniqueNetInfoName(string name, bool excludeCurrent = false) { string strippedName = PackageHelper.StripName(name); if (excludeCurrent && strippedName == name) { return(name); } string finalName = strippedName; for (int i = 0; PrefabCollection <NetInfo> .LoadedExists(finalName); i++) { finalName = $"instance{i}." + strippedName; if (i > 1000) { throw new Exception("Infinite loop"); } } return(finalName); }
public RoadMaker2(OSM.OSMInterface osm) { this.osm = osm; this.rand = new Randomizer(0u); var roadTypes = Enum.GetNames(typeof(RoadTypes)); for (var i = 0; i < PrefabCollection <NetInfo> .PrefabCount(); i += 1) { var pp = PrefabCollection <NetInfo> .GetPrefab((uint)i); if (pp != null) { if (roadTypes.Contains(pp.name.Replace(" ", ""))) { netInfos.Add((RoadTypes)Enum.Parse(typeof(RoadTypes), pp.name.Replace(" ", "")), pp); } } } }
public override void HandleOnClient(NodeCommand command) { Extensions.NodeAndSegmentExtension._NetSegmentLocked = true; lock (Extensions.NodeAndSegmentExtension._netSegment) { NetInfo netinfo = PrefabCollection <NetInfo> .GetPrefab(command.InfoIndex); lock (Extensions.NodeAndSegmentExtension.NodeIDDictionary) { lock (Extensions.NodeAndSegmentExtension.VectorDictionary) { Singleton <NetManager> .instance.CreateNode(out ushort node, ref Singleton <SimulationManager> .instance.m_randomizer, netinfo, command.Position, Singleton <SimulationManager> .instance.m_currentBuildIndex); Extensions.NodeAndSegmentExtension.NodeIDDictionary.Add((ushort)command.NodeID, node); //Adds the NodeID recived and the NodeID generated on NodeCreation. Extensions.NodeAndSegmentExtension.VectorDictionary.Add(command.Position, node); } } } Extensions.NodeAndSegmentExtension._NetSegmentLocked = false; }
private void RunOnPrefabs <TPrefab, TAI>(Action <TAI> runner) where TPrefab : PrefabInfo where TAI : PrefabAI { if (runner == null) { return; } var prefabCount = PrefabCollection <TPrefab> .PrefabCount(); for (uint i = 0; i < prefabCount; i++) { var prefab = PrefabCollection <TPrefab> .GetPrefab(i); var ai = prefab.GetAI(); if (ai is TAI) { runner(ai as TAI); } } }
public override void Start() { name = "PRT_NetList"; padding = new RectOffset(4, 4, 4, 0); size = new Vector2(450 - 8 * 2, 200); autoLayoutPadding = new RectOffset(0, 0, 0, 4); autoFitChildrenVertically = true; autoLayout = true; autoLayoutDirection = LayoutDirection.Vertical; backgroundSprite = "GenericPanel"; color = Color.black; m_items = new List <UINetTypeItem>(); m_currentTool = AddUIComponent <UINetTypeItem>(); m_currentTool.isCurrentItem = true; m_currentTool.OnAddCallback = () => { DebugUtils.Log("Adding item to list"); // get sum of current offsets float prevOffset = 0; if (list.Count() > 0) { prevOffset = list.Last().offset; } NetInfo netInfo = PrefabCollection <NetInfo> .FindLoaded(m_currentTool.netInfo.name); DebugUtils.Log($"{m_currentTool.netInfo} halfWidth: {m_currentTool.netInfo.m_halfWidth}"); NetTypeItem item = new NetTypeItem(netInfo, prevOffset + netInfo.m_halfWidth * 2); list.Add(item); RenderList(); Changed(); }; m_space = AddUIComponent <UIPanel>(); m_space.size = new Vector2(1, 1); }
public void updateCapacity(float targetValue) { try { DormitoryMod seniorCitizenCenterMod = DormitoryMod.getInstance(); if (seniorCitizenCenterMod == null || seniorCitizenCenterMod.getDormitoryInitializer() == null) { Logger.logInfo(Logger.LOG_OPTIONS, "OptionsManager.updateCapacity -- Skipping capacity update because a game is not loaded yet"); return; } DormitoryInitializer dormitoryInitializer = DormitoryMod.getInstance().getDormitoryInitializer(); if (dormitoryInitializer.getLoadedLevel() != DormitoryInitializer.LOADED_LEVEL_GAME) { Logger.logInfo(Logger.LOG_OPTIONS, "OptionsManager.updateCapacity -- Skipping capacity update because a game is not loaded yet"); return; } } catch (Exception e) { Logger.logError(Logger.LOG_OPTIONS, "OptionsManager.updateCapacity -- Skipping capacity update because a game is not loaded yet -- Exception: {0}", e.Message); } Logger.logInfo(Logger.LOG_OPTIONS, "OptionsManager.updateCapacity -- Updating capacity with modifier: {0}", targetValue); for (uint index = 0; PrefabCollection <BuildingInfo> .LoadedCount() > index; ++index) { BuildingInfo buildingInfo = PrefabCollection <BuildingInfo> .GetLoaded(index); if (buildingInfo != null && buildingInfo.m_buildingAI is DormitoryAi) { ((DormitoryAi)buildingInfo.m_buildingAI).updateCapacity(targetValue); } } BuildingManager buildingManager = Singleton <BuildingManager> .instance; for (ushort i = 0; i < buildingManager.m_buildings.m_buffer.Length; i++) { if (buildingManager.m_buildings.m_buffer[i].Info != null && buildingManager.m_buildings.m_buffer[i].Info.m_buildingAI != null && buildingManager.m_buildings.m_buffer[i].Info.m_buildingAI is DormitoryAi) { ((DormitoryAi)buildingManager.m_buildings.m_buffer[i].Info.m_buildingAI).validateCapacity(i, ref buildingManager.m_buildings.m_buffer[i], true); } } }
public override void InitializePrefab() { base.InitializePrefab(); this.m_constructionCost = 2000; this.m_maintenanceCost = 250; try { NetInfo zonablePath = PrefabCollection <NetInfo> .FindLoaded("Zonable Pedestrian Pavement"); if (zonablePath == null) { throw new KeyNotFoundException("Can't find Zonable Pedestrian Pavement in PrefabCollection."); } ZonablePedestrianPathAI zonablePathAI = zonablePath.GetComponent <ZonablePedestrianPathAI>(); if (zonablePathAI == null) { throw new KeyNotFoundException("Zonable Pedestrian Pavement prefab does not have a ZonablePedestrianPathAI."); } zonablePathAI.m_elevatedInfo = this.m_info; zonablePathAI.m_bridgeInfo = this.m_info; GameObject pillarPrefab = Resources.FindObjectsOfTypeAll <GameObject>().Where(g => g.name == "Pedestrian Elevated Pillar").FirstOrDefault(); if (pillarPrefab == null) { throw new KeyNotFoundException("Can't find Pedestrian Elevated Pillar."); } this.m_bridgePillarInfo = pillarPrefab.GetComponent <BuildingInfo>(); Debug.Log("Traffic++: " + name + " initialized."); } catch (KeyNotFoundException knf) { Debug.Log("Traffic++: Error initializing Zonable Pedestrian Bridge AI: " + knf.Message + "\n"); } catch (Exception e) { Debug.Log("Traffic++: Unexpected " + e.GetType().Name + " initializing Zonable Pedestrian Bridge AI: " + e.Message + "\n" + e.StackTrace + "\n"); } }
/// <summary> /// Saves the current RICO settings to file and then applies them live in-game. /// </summary> private void SaveAndApply() { // Find current prefab instance. BuildingData currentBuildingData = Loading.xmlManager.prefabHash[currentSelection.prefab]; // Delete existing building button, if any. if (currentBuildingData.buildingButton != null) { Destroy(currentBuildingData.buildingButton); } // Save first. Save(); // If we're converting a residential building to something else, then we first should clear out all households. if (currentBuildingData.prefab.GetService() == ItemClass.Service.Residential && !IsCurrentResidential()) { // removeAll argument to true to remove all households. UpdateHouseholds(currentBuildingData.prefab.name, removeAll: true); } // Get the currently applied RICO settings (local, author, mod). RICOBuilding currentData = CurrentRICOSetting(); if (currentData != null) { // Convert the 'live' prefab (instance in PrefabCollection) and update household count and builidng level for all current instances. Loading.convertPrefabs.ConvertPrefab(currentData, PrefabCollection <BuildingInfo> .FindLoaded(currentBuildingData.prefab.name)); UpdateHouseholds(currentBuildingData.prefab.name, currentData.level); // Create new building button. PloppableTool.Instance.AddBuildingButton(currentBuildingData, CurrentUICategory()); } else { Debugging.Message("no current RICO settings to apply to prefab " + currentBuildingData); } // Force an update of all panels with current values. SettingsPanel.Panel.UpdateSelectedBuilding(currentSelection); }
/// <summary> /// Unlocks all road types and all intersections /// </summary> public void Unlock() { // Normal road types, easy. for (int index = 0; index < PrefabCollection <NetInfo> .LoadedCount(); ++index) { NetInfo loaded = PrefabCollection <NetInfo> .GetLoaded((uint)index); if (loaded == null || loaded.m_class == null || loaded.m_class.name == null) { continue; } if (UnlockClass(loaded.m_class)) { loaded.m_UnlockMilestone = null; } } // Intersections. for (int index = 0; index < PrefabCollection <BuildingInfo> .LoadedCount(); ++index) { BuildingInfo loaded = PrefabCollection <BuildingInfo> .GetLoaded((uint)index); if (loaded == null || loaded.m_class == null || loaded.m_class.name == null) { continue; } if (UnlockClass(loaded.m_class)) { loaded.m_UnlockMilestone = null; var intersectionAI = loaded.m_buildingAI as IntersectionAI; if (intersectionAI != null) { // The cached milestone here is generally the "highest" road type used. Base.SetPrivateVariable <MilestoneInfo>(intersectionAI, "m_cachedUnlockMilestone", null); } } } }
public static void SortPrefabs() { foreach (ModConfig.SortRule sortRule in ModConfig.prefabRules) { PrefabInfo prefab = null; switch (sortRule.Type) { case "Network": prefab = PrefabCollection <NetInfo> .FindLoaded(sortRule.Name); break; case "Building": prefab = PrefabCollection <BuildingInfo> .FindLoaded(sortRule.Name); break; case "Transport": prefab = PrefabCollection <TransportInfo> .FindLoaded(sortRule.Name); break; case "Tree": prefab = PrefabCollection <TreeInfo> .FindLoaded(sortRule.Name); break; case "Prop": prefab = PrefabCollection <PropInfo> .FindLoaded(sortRule.Name); break; default: break; } if (prefab != null) { prefab.m_UIPriority = sortRule.Priority; } } }
public void Load() { GameObject newRoad = GameObject.Instantiate <GameObject>(PrefabCollection <NetInfo> .FindLoaded(baseNetwork).gameObject); if (newRoad == null) { Debug.Log("newRoad is null"); } newRoad.name = name; NetInfo ni = newRoad.GetComponent <NetInfo>(); ni.m_prefabInitialized = false; ni.m_netAI = null; typeof(NetInfo).GetField("m_UICategory", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ni, category); Locale locale = (Locale)typeof(LocaleManager).GetField("m_Locale", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(SingletonLite <LocaleManager> .instance); locale.AddLocalizedString(new Locale.Key() { m_Identifier = "NET_TITLE", m_Key = name }, title); locale.AddLocalizedString(new Locale.Key() { m_Identifier = "NET_DESC", m_Key = name }, description); MethodInfo initMethod = typeof(NetCollection).GetMethod("InitializePrefabs", BindingFlags.Static | BindingFlags.NonPublic); Singleton <LoadingManager> .instance.QueueLoadingAction((IEnumerator)initMethod.Invoke(null, new object[] { category, new[] { ni }, new string[] { } })); Singleton <LoadingManager> .instance.QueueLoadingAction(inCoroutine(() => { setup(ni); PrefabCollection <NetInfo> .BindPrefabs(); GameObject.Find(category + "Panel").GetComponent <GeneratedScrollPanel>().RefreshPanel(); })); }
/* The extraInfo is a prefab which user has selected in the roads menu and does not have to be in the list (It might not be one-way road) * In that case we add it temporatily to the list */ private void UpdateListWithPrefab(NetInfo extraInfo) { bool freeCursor = UIWindow2.instance?.toolOnUI is FreeCursorTool; if (m_lastToolInfo != null && !IsEligible(m_lastToolInfo, freeCursor)) { m_dictionary.Remove(new StringWithLaneCount(m_lastToolInfo, " [S]")); } if (extraInfo != null && !IsEligible(extraInfo, freeCursor)) { m_dictionary.Add(new StringWithLaneCount(extraInfo, " [S]"), extraInfo); } // This should never happen, but I will leave there. Some NetInfos could have been missing from the list due to name duplicity, but that was // solved in the Populate() method if (extraInfo != null && IsEligible(extraInfo, freeCursor) && !m_netInfos.Contains(extraInfo)) { m_dictionary.Add(new StringWithLaneCount(extraInfo, " [E]"), extraInfo); } items = m_dictionary.Keys.Select(x => x.Name).ToArray(); m_netInfos = m_dictionary.Values.ToArray(); if (extraInfo != null) { int i = Array.IndexOf(m_netInfos, extraInfo); selectedIndex = i >= -1 ? i : selectedIndex; } else { /* Set strandard oneway as default */ int i = Array.IndexOf(m_netInfos, PrefabCollection <NetInfo> .FindLoaded("Oneway Road")); if (i > -1 && i < m_netInfos.Length) { selectedIndex = i; } } //Debug.Log($"Loaded {items.Length} netinfos."); }
private static void SetupTunnelPrefab(NetInfo prefab) { var trainStationTrack = FindOriginalPrefab("Train Station Track"); prefab.m_class = ScriptableObject.CreateInstance <ItemClass>(); prefab.m_class.m_subService = ItemClass.SubService.PublicTransportTrain; prefab.m_class.m_service = ItemClass.Service.PublicTransport; prefab.m_class.m_layer = ItemClass.Layer.MetroTunnels | ItemClass.Layer.Default; prefab.m_canCollide = false; var metroAI = prefab.GetComponent <MetroTrackAI>(); GameObject.DestroyImmediate(metroAI); var trackAI = prefab.gameObject.AddComponent <UndergroundTrainStationTrackAI>(); trackAI.m_transportInfo = PrefabCollection <TransportInfo> .FindLoaded("Train"); prefab.m_netAI = trackAI; trackAI.m_createPassMilestone = trainStationTrack.GetComponent <TrainTrackAI>().m_createPassMilestone; trackAI.m_info = prefab; var field = typeof(PrefabInfo).GetField("m_UICategory", BindingFlags.Instance | BindingFlags.NonPublic); field.SetValue(prefab, field.GetValue(trainStationTrack)); prefab.m_averageVehicleLaneSpeed = trainStationTrack.m_averageVehicleLaneSpeed; prefab.m_vehicleTypes = VehicleInfo.VehicleType.Train; prefab.m_buildHeight = 0; foreach (var lane in prefab.m_lanes) { if (lane.m_vehicleType == VehicleInfo.VehicleType.None) { lane.m_stopType = VehicleInfo.VehicleType.Train; } else { lane.m_vehicleType = VehicleInfo.VehicleType.Train; } } }
public static bool LoadTextures() { NetInfo container = PrefabCollection <NetInfo> .FindLoaded("CSURTextureContainer_Data"); if (container == null) { return(false); } foreach (NetInfo.Segment info in container.m_segments) { // lod material main texture name is TEXNAME_lod string textureKey = info.m_material.name; Debug.Log($"loaded {textureKey}"); textures.Add("CSUR_TEXTURE/" + textureKey, info.m_material); if (LOAD_LOD) { textures.Add("CSUR_LODTEXTURE/" + textureKey, info.m_material); } } return(true); }
//Load settings from settings mods. (Currently disabled) public void ModSettings() { var workshopModSettingsPath = Path.Combine(Util.SettingsModPath("629850626"), "WorkshopRICOSettings.xml"); var xmlSerializer = new XmlSerializer(typeof(PloppableRICODefinition)); PloppableRICODefinition workshopSettings = null; using (StreamReader streamReader = new System.IO.StreamReader(workshopModSettingsPath)) { workshopSettings = xmlSerializer.Deserialize(streamReader) as PloppableRICODefinition; } foreach (var buildingDef in workshopSettings.Buildings) { if (PrefabCollection <BuildingInfo> .FindLoaded(buildingDef.name) != null) { var buildingPrefab = PrefabCollection <BuildingInfo> .FindLoaded(buildingDef.name); //Add settings mod settings here } } }
public static VehicleInfo GetVehicleInfo(ref Randomizer randomizer, ItemClass m_class, ushort lineID, string prefabName) { PrefabData prefabData = Array.Find <PrefabData>(VehiclePrefabs.instance.GetPrefabs(m_class.m_subService), (Predicate <PrefabData>)(item => item.ObjectName == prefabName)); if (prefabData != null) { return(PrefabCollection <VehicleInfo> .GetPrefab((uint)prefabData.PrefabDataIndex)); } Utils.LogWarning((object)("Unknown prefab: " + prefabName)); VehicleManager instance = Singleton <VehicleManager> .instance; instance.RefreshTransferVehicles(); // ISSUE: explicit reference operation // ISSUE: variable of a reference type Randomizer& r = @randomizer; int service = (int)m_class.m_service; int subService = (int)m_class.m_subService; int level = (int)m_class.m_level; return(instance.GetRandomVehicleInfo(r, (ItemClass.Service)service, (ItemClass.SubService)subService, (ItemClass.Level)level)); }
/// <summary> /// Attempts to find the replacement prefab with the specified name. /// </summary> /// <param name="replacementName">Prefab name to find</param> /// <param name="isTree">True if the desired prefab is a tree, false if it's a prop</param> /// <returns>Requested prefab, or null if not found</returns> internal static PrefabInfo FindReplacementPrefab(string replacementName, bool isTree) { // Null check. if (replacementName.IsNullOrWhiteSpace()) { Logging.Error("invalid replacement prop name"); return(null); } // Attempt to load from prefab collection. PrefabInfo replacementPrefab = isTree ? (PrefabInfo)PrefabCollection <TreeInfo> .FindLoaded(replacementName) : (PrefabInfo)PrefabCollection <PropInfo> .FindLoaded(replacementName); if (replacementPrefab == null && CurrentConfig != null) { // If we couldn't load from prefab collection, attempt to find in our list of replacement prefabs. replacementPrefab = isTree ? (PrefabInfo)CurrentConfig.randomTrees.Find(x => x.name.Equals(replacementName))?.tree : (PrefabInfo)CurrentConfig.randomProps.Find(x => x.name.Equals(replacementName))?.prop; } // Return what we have. return(replacementPrefab); }
private static GameObject GetPlayerModelPrefab() { GameObject citizenPrefabModel = null; for (int i = 0; i < PrefabCollection <CitizenInfo> .LoadedCount(); i++) { if (PrefabCollection <CitizenInfo> .GetLoaded((uint)i).name.ToLower().Contains(CITIZEN_PREFAB_NAME.ToLower())) { citizenPrefabModel = PrefabCollection <CitizenInfo> .GetLoaded((uint)i).gameObject; break; } } if (citizenPrefabModel == null) { Debug.LogError("Coulden't load player model"); } return(citizenPrefabModel); }