- Home /
GetComponentInChildren not Working
Hi, I got a script that instantiates a prefab each 20 seconds, and that prefab is supposed to choose a random sprite for itself and another for its child.
The thing is that it is getting his sprite with its random color but his child doesn't even get its random sprite.
Both have a SpriteRenderer component attached and the parent has the script too, here is my code if someone can help me:
using UnityEngine;
public class BGTemplate : MonoBehaviour
{
public Sprite[] upperPart;
public Sprite[] bottomPart;
private SpriteRenderer upperRenderer;
private SpriteRenderer bottomRenderer;
private float speed = 0.25f;
(float, float, float, float) upperColor;
(float, float, float, float) bottomColor;
// Start is called before the first frame update
void Awake()
{
bottomRenderer = GetComponent<SpriteRenderer>();
upperRenderer = GetComponentInChildren<SpriteRenderer>(true);
}
private void Start()
{
int randomSprite = Random.Range(0, upperPart.Length);
bottomRenderer.sprite = bottomPart[randomSprite];
upperRenderer.sprite = upperPart[randomSprite];
upperColor = (Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0.4f, 0.6f));
bottomColor = (Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0.4f, 0.6f));
Color newUpperColor = new Color(upperColor.Item1, upperColor.Item2, upperColor.Item3, upperColor.Item4);
Color newBottomColor = new Color(bottomColor.Item1, bottomColor.Item2, bottomColor.Item3, bottomColor.Item4);
upperRenderer.color = newUpperColor;
bottomRenderer.color = newBottomColor;
}
Is upperRenderer null?
What do you mean by "and the parent has the script too" did you put the script on the child? if so, that will be why its not working (Unless that also has a child with a sprite renderer)
Answer by qsp18 · Dec 08, 2020 at 05:03 PM
Are you sure, the spriteRenderer is Null? I would test, by writing Debug.Log(upperRenderer);
You could assign the childrens Sprite Renderer in the Unity Inspector, if make make it an [SerialzedField]. Would make better performance anyways...
Your answer
Follow this Question
Related Questions
Can't set the random position for an Instance. 1 Answer
Distribute terrain in zones 3 Answers
How To NOT Instantiate the same Prefab Twice (C#) 1 Answer
How to get script from Object with (Clone)'s script? 2 Answers
instantiating vertically 2 Answers