- Home /
,Changing variable in an instantiated objects script is not updating
I have an object that I'm instantiating. Sometimes I want this object to be live and other times I don't. When I instantiate it I want to set it's live state right after. The problem is that when I try to change the public variable attached to the object's animationStateController script it doesn't change.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawner : MonoBehaviour
{
public void SpawnUnit(GameObject unit){
GameObject spawnedUnit = Instantiate(unit, transform.position, transform.rotation);
spawnedUnit.GetComponent<animationStateController>().live = true;
}
}
When the SpawnUnit function is called the live variable is not updated and the Debug.Log never happens. The unit spawns, and it has the script attached, and I can go into the scene tab during runtime and check the public variable for live and then expected behavior occurs, I just cant change it from the script for some reason.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class animationStateController : MonoBehaviour
{
public bool live;
void Start()
{
live = false;
}
void Update()
{
if(live){
Debug.Log("ACTIVATED");
}
}
}
Answer by Elias_g · May 29 at 05:37 AM
I believe animationStateController's start function is called by the end of the current frame, which means it's called after your SpawnUnit function, so the live variable gets changed again.
You DO set it true, it just changes to false in the Start function.
Your answer
![](https://koobas.hobune.stream/wayback/20220613061048im_/https://answers.unity.com/themes/thub/images/avi.jpg)