I have a script that goes over every child gameobject and changes its material based on whether that weapon is unlocked or not:
void HighlightWeapon()
{
int i = 0;
foreach (Transform weapon in transform)
{
if (i == weaponSwitcher.selectedWeapon)
{
weapon.gameObject.GetComponent<Image>().material = null;
}
else
{
weapon.gameObject.GetComponent<Image>().material = hideWeapon;
}
i++;
}
}
If that weapon is selected in the weaponSwitcher then remove the material, and if not then apply the material on its icon that signifies that the weapon is either unavailable or not selected.
The code is working as it should and only the selected weapon has the material removed and all others have it applied, as expected… but every time the function is called I get the following error:
directing at the line: weapon.gameObject.GetComponent<Image>().material = hideWeapon;.
The code works and the material on the icons is updated, but I keep getting this error…
Add debugging to figure out which reference is null, and output the name of the child object. You’ll probably find you have a child without an Image component is my guess.
It is best to use null checks on calls to GetComponent before trying to use the returned reference.
It’s also possible you accidently put this script into your scene on another gameobject. Double check you don’t have an extra copy of this script in your scene.
Hi, Yes you’re right. One of the child objects does not have the image component on it. But it is a parent GameObject to two children that do have the Image component on them. How do I solve this?
You would need to get the children of the child. I’d probably check if GetComponent() returns null, and if it does then loop through its children if you want to keep doing it how you’re doing.
The way I’d rewrite this is whenever children are added to the parent object, I’d add their Image component to a list maintained on the parent. If the child has children with Image components, add them. If this is all just one prefab, just set them in the inspector, otherwise at runtime whenever you add one of these child objects. If you remove a child, also remove its Image components from the list. Then instead of using GetComponent in a loop, you just loop through your maintained list.