- Home /
Reference instantiated object
I'm new to Unity, but have this strange problem. When I instantiate an object in which I have an update method that instantiate another object and this object has a script that increases value of variable of the first instaniated object it strangely increases the value of the variable in the assets menu not in the actual game.
And even strangely the increased value in the assets menu stays increased even after I stop the game.
New instance of a player:
void SetupPlayer()
{
GameObject newPlayer = Instantiate(player);
newPlayer.GetComponent<Player>().food = 100;
newPlayer.GetComponent<Player>().wood = 200;
newPlayer.GetComponent<Player>().ores = 50;
newPlayer.GetComponent<Player>().manpower = 10000;
}
This script is attached to the player:
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(temp);
print(foodIncome);
}
}
And this is attached to the "temp" object:
int income = 100;
public GameObject player;
private void Awake()
{
player.GetComponent<Player>().foodIncome += income;
}
I don't understand what's going on.
Answer by unity_ek98vnTRplGj8Q · Jul 24, 2020 at 07:56 PM
Your "player" variable on the script of you temp object is still pointing to the prefab, not to the instantiated player object. Do this when you spawn it instead
if (Input.GetMouseButtonDown(0))
{
Gameobject newTemp = Instantiate(temp);
newTemp.GetComponent<WhateverTheTempScriptIsCalled>().player = this.gameObject;
print(foodIncome);
}
Answer by miccalisto · Jul 24, 2020 at 08:15 PM
I did exactly this and I got an error that the player variable has not been assigned. Even though when I checked the instantiated "temp" objects in the inspector it all had "player(clone)" assigned to it, so it should work, but for some reason it doesn't register it. @unity_ek98vnTRplGj8Q
Change Awake() to Start() in your temp script, awake is called with the instantiate call before you have assigned the player variable, but Start is called sometime later so it will work there
thank you very much, now it works perfectly fine
Your answer
