Mkoch
Mkoch

Reputation: 2024

Accessing script component right after instantiation

I have a script creating UI buttons in Unity. It creates instances of a prefab, which has also custom script components in it. I'd like to instantiate a new copy and immediately access values members/fields of the newly created object's scripts:

turretButtons.Add(Instantiate(buttonProto, gameObject.transform));
turretButtons[turretButtons.Count - 1].image.sprite = turretIcon;
turretButtons[turretButtons.Count - 1].GetComponent<DetailsWindowController>().turretDefinition = turretDef;

The first line creates the new instance, the second change the icon, both work perfectly. The third however, in which I try to access the DetailsWindowController script/class's turretDefinition public member throws "NullReferenceException: Object reference not set to an instance of an object". What am I missing?

Upvotes: 0

Views: 732

Answers (1)

derHugo
derHugo

Reputation: 90679

The component you are looking for is probably not attached to exactly the same GameObject the Button component is attached to.

You should use GetComponentInChildren in order to always look for the component recursive downwards inside of the button's hierachy. Also note the true parameter which is required to find components on disabled children. This might be usefull in the case the button is spawned disabled.

var newButton = Instantiate(buttonProto, gameObject.transform);

newButton.image.sprite = turretIcon;
newButton.GetComponentInChildren<DetailsWindowController>(true).turretDefinition = turretDef;

turretButtons.Add(newButton);

Upvotes: 1

Related Questions