- Home /
GetComponentInChildren(Renderer).active wont work?
Hi in one of my scripts this part, the other.gameObject.GetComponentInChildren(Renderer).active = false; line works great but in this script(script below) that same line doesn't work and it gives me the error below. And it doesn't reactivate the child renderer when it runs the if statement(note the line right above it works so it is getting inside the if statement)
function RespawnDoublePoints ()
{
for (var i : int = 0; i < doublePointsClonesArray.Length; i++)
{
if (doublePointsClonesArray[i].transform.position.x < doublePointsResetPosition)
{
doublePointsClonesArray[i].transform.position = gameObject.transform.position + Vector3(Random.Range(4, 15), Random.Range(-4, 4), 0);
doublePointsClonesArray[i].gameObject.GetComponentInChildren(Renderer).active = true;
}
}
}
The part not working:
doublePointsClonesArray[i].gameObject.GetComponentInChildren(Renderer).active = true;
Error:
NullReferenceException: Object reference not set to an instance of an object Double Points Spawner Script.RespawnDoublePoints () (at Assets/Scripts/Double Points Spawner Script.js:38) Double Points Spawner Script.Update () (at Assets/Scripts/Double Points Spawner Script.js:22)
If you just want to enable/disable the renderer, then use Renender.enabled:
var rend = doublePointsClonesArray[i].gameObject.GetComponentInChildren(Renderer);
if (rend != null) {
rend.enabled = true;
}
Answer by Jammer3000 · Jun 19, 2014 at 01:44 PM
I found a work around I just made another array and gave the child objects tags and filled that separate array with those objects. Thanks @robertbu and @Eric5h5
function Start ()
{
for (var j : int = 0; j < 2; j++)
{
array[0] = GameObject.FindGameObjectWithTag("DoublePointsChildGlow");
array[1] = GameObject.FindGameObjectWithTag("DoublePointsChildCore");
}
}
function Update ()
{
RespawnDoublePoints();
}
function RespawnDoublePoints ()
{
for (var j : int = 0; j < array.Length; j++)
{
if (array[j].transform.position.x < doublePointsResetPosition)
{
array[j].gameObject.active = true;
}
}
}
Answer by Eric5h5 · Jun 18, 2014 at 08:47 PM
It means the component doesn't exist. Check for whether the component is null first before you try to do anything with it. By the way, .active is deprecated; you should be using SetActive().
Could you give me an example of how to use SetActive()?
http://docs.unity3d.com/ScriptReference/GameObject.SetActive.html
Although that's actually not the thing to use here anyway; active is only for GameObjects, not components.
Your answer
Follow this Question
Related Questions
How to add a peaking system? 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
How Do I Make A Health Bar 6 Answers
GUI.Box that will appear for 3sec 1 Answer