- Home /
The question is answered, right answer was accepted
Change materials of child object
I need to change material of child objects in LevelParts named gameobject when a another ball is taken.
I've been trying to do this with this kind of script:
using UnityEngine;
using System.Collections;
public class GlassBall : MonoBehaviour {
private GameObject Player;
private GameObject LevelParts;
public Material newtext;
public Material newtext2;
void Start()
{
Player = GameObject.Find("Player");
LevelParts = GameObject.Find("LevelParts");
}
void OnTriggerEnter (Collider other )
{
if (other.tag == "Player")
{
Player.renderer.material = newtext;
other.rigidbody.mass = 1f;
Transform[] allChildren = LevelParts.GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren) {
child.renderer.material = newtext2;
}
}
}
}
It gives error:
MissingComponentException: There is no 'Renderer' attached to the "LevelParts" game object, but a script is trying to access it.
Well, this tells me that my code doesnt load at all the children objects of that LevelParts gameobject, so I don't really know where I'm going on the wrong direction, as the way I see it, it should?
I tried to look for some other questions about this matter, but I could only find scripts that are mostly done like mine.
I think I'll change back to JS soon. I have an feeling that I can't never understand how C# works with Unity.
WORKING CODE:
using UnityEngine;
using System.Collections;
public class GlassBall : MonoBehaviour {
private GameObject Player;
private GameObject LevelParts;
public Material newtext;
public Material newtext2;
public Component[] allChildren;
void Start()
{
Player = GameObject.Find("Player");
LevelParts = GameObject.Find("LevelParts");
}
void OnTriggerEnter (Collider other )
{
if (other.tag == "Player")
{
Player.renderer.material = newtext;
other.rigidbody.mass = 1f;
foreach (Transform child in LevelParts.transform) {
child.gameObject.renderer.material = newtext2;
}
}
}
}
First, transform children is built into the Transform class, so replace:
Transform[] allChildren = LevelParts.GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren) {
with:
foreach (Transform child in LevelParts.transform) {
I believe the issue is that you are trying to get the renderer of the Transform, not the game object. Try ins$$anonymous$$d:
child.gameObject.renderer.material = newtext2;
Follow this Question
Related Questions
Changing the material on a prefab 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers