Search code examples
c#unity-game-engine

Variable is only applied to prefab sometimes when instantiated in Unity 2d


I am working on a factory build game. When placing down specific buildings such as the market that sells ores and the chest that stores the ores, I need to access the GameManager GameObject in my Scene. Since the buildings are prefabs, I set the variable on placement. Sometimes, seemingly randomly, the variable will not be set. The BuildManager code is below.

GameObject Tower = Instantiate(towerToBuild, Camera.main.ScreenToWorldPoint(Input.mousePosition), Quaternion.identity);

if (towerToBuild == market)
{
    MarketScript marketScript = towerToBuild.GetComponent<MarketScript>();
    marketScript.gameManager_ = gameManager;
}

if (towerToBuild == chest) 
{
    StorageScript storageScript = towerToBuild.GetComponent<StorageScript>();
    storageScript.gameManager_ = gameManager;
}

The variable that is not being set is the gameManager_ variable in my storage and market scripts.

The code works about 80-90% of the time. Also when placing the builds I am doing nothing different between times when the code works and when it does not. It seems to me to be completely random.


Solution

  • You're modifying the tower prefab, not the newly created object. This means that the gameManager_ variable will not be set for the first object created of a given type, but it will be set for every copy created after the first.

    MarketScript marketScript = towerToBuild.GetComponent<MarketScript>();
    marketScript.gameManager_ = gameManager;
    

    Change towerToBuild.GetComponent(...) to Tower.GetComponent(...), since Tower is the variable containing the newly created gameObject:

    MarketScript marketScript = Tower.GetComponent<MarketScript>();
    marketScript.gameManager_ = gameManager;