- Home /
Question by
LowTierCoder · May 29, 2020 at 01:07 PM ·
c#scripting problemgameobjectbeginner
how to change a GameObject from another script
[SerializeField]
GameObject obj1;
[SerializeField]
GameObject obj2;
[SerializeField]
Script script ;
void Start()
{
obj1= transform.Find("/Game/Player/obj1").gameObject;
script = obj1.GetComponent<Script>();
}
void OnEnable()
{
script.Cube = obj2;
}
I want to change the "Cube" GameObject from the Script script to the obj2 GameObject, and the script above is not working. What happens is that the "Cube" GameObject(that is already not set) is not set to an instance of an object so that means that its not setting obj2 to be Cube, so any help will be much appreciated.
Comment
Answer by KoenigX3 · May 29, 2020 at 01:16 PM
Are script and obj2 assigned through the inspector? OnEnable gets called first, and if they are not assigned to anything, it will cause a NullReferenceException.
oh thank you I just changed the void Start to void Awake it work now thx.