I have some trouble with my code that lets you launch and dock a fleet from a space station. When I launch, I instantiate a fleet object from a prefab, this object has the PlayerFleetOnMap script, which inherits from FleetOnMapBase. When a fleet tries to dock, that fleet object should be destroyed. This works, but from that moment on all other fleets that were launched or are launched later give MissingReferenceException errors when accessing their child objects.
Both the objects and their child objects are still there in the Hierarchy, and in the inspector I can even see that the references to those child objects (assigned as variables on the PlayerFleetOnMap script) are still there and pointing to the correct objects. But breakpoints in the script show that, within the running PlayerFleetOnMap script, those variables have values of “null” (including those quotation marks).
I’ve looked at questions from people with similar problems, and most seemed to be overwriting their prefab when instantiating, but as far as I can see that’s not happening here:
public bool TryLaunchFleet(List<VesselInfo> vessels, out FleetOnMapBase fleetOnMap)
{
fleetOnMap = null;
FleetInfo newFleet = dockedFleet.SplitFleet(vessels);
newFleet.isDocked = false;
newFleet.faction = faction;
var fleetOnMapInstance = Instantiate(fleetOnMapPrefab, transform.position, Quaternion.identity);
fleetOnMap = fleetOnMapInstance.GetComponent<FleetOnMapBase>();
return fleetOnMap.TrySetFleetInfo(newFleet, this);
}
public virtual void DockFleet(FleetOnMapBase fleetOnMap)
{
dockedFleet.MergeFleet(fleetOnMap.fleetInfo);
Destroy(fleetOnMap.gameObject);
}
If instead of destroying I use SetActive(false) no problems occur, but the fleet object will stay in the hierarchy. I could try object pooling, but first I want to know what I’m doing wrong here to prevent other problems later on. Can anyone see what the mistake is?
Okay, it was just a stupid mistake on my part: There wasn’t a problem with the other instances at all. It’s just that when selecting another fleet, or creating one which results in it automatically being selected, it would first try to deselect the previously selected fleet. If that previous fleet was the docked and destroyed fleet it would, quite reasonably, result in the above errors. I didn’t see it because I use SetSelected(bool selected) as the same method for both selecting and deselecting a fleet, and I assumed the error occured when selecting a new fleet.