- Home /
{java} so I want to enable/disable child objects through a parent script 2d
I'm trying to create a terrain engine that loops around using the same gameObjects over & over by changing their sprite & collider based on the position of the player. As the player progresses right, the previous terrain would become the next terrain but with the appropriate sprite & collider, as would the last terrain as you continue moving right, etc. What I can't figure out is how I can even change colliders of a gameObject What I've done so far is created the terrain & attached empty gameObjects each with the different colliders I want to switch between.
Here's the script for the terrain so far:
var terrain2 : Sprite;
var terrain1 : Sprite;
function Update () {
if(GameObject.Find("wWolf").transform.position.x > 20){ // checks position of player
transform.position.x = 40; // sets position of terrain
GetComponent(SpriteRenderer).sprite = terrain2; // change sprite
GameObject.Find("Terrain2").BoxCollider.SetActive(false); // disable PolygonCollider2D
GameObject.Find("Terrain1").BoxCollider.SetActive(true); // enable BoxCollider2D
}else{
transform.position.x = -15;
GetComponent(SpriteRenderer).sprite = terrain1;
GameObject.Find("Terrain2").BoxCollider.SetActive(true); // enable PolygonCollider2D
GameObject.Find("Terrain1").BoxCollider.SetActive(false); // disable BoxCollider2D
}
}
Right now it's giving me an error saying 'BoxCollider' is not a member of 'UnityEngine.GameObject' I've been scrounging together everything I can find & nothing has quite answered the question of how I enable/disable the colliders {or entire gameObject if it's more convenient} of the child gameObjects. Any help is much appreciated
Answer by FlaSh-G · Jul 05, 2017 at 09:25 PM
You can't just throw any term behind a dot. There is a specific set of words that can come after a dot after a specific thing, like a GameObject. That set is deocumented in the scripting reference. As you can see, there's no "BoxCollider" there.
When you want to get the reference to a component on a GameObject, you need to use GetComponent like this:
GameObject.Find("Terrain1").GetComponent.<BoxCollider>()
Next up, also documented in the scripting reference, SetActive is a GameObject function. You can enable and disable GameObjects with that, not components. For components, it's enabled. Like this:
GameObject.Find("Terrain1").GetComponent.<BoxCollider>().enabled = true;
There's multiple other things worthy of looking into, but I'll just mention the most important thing: JavaScript is not Java. They're completely different things that are better not confused.
Your answer
Follow this Question
Related Questions
Switch for children not working 1 Answer
Problem with rotation in unity2D with PolygonCollider2D 0 Answers
how to make 2d sprite with polygon collider bounce? 1 Answer
Why is parenting not working? 0 Answers
Renaming Child Assets in Project 4 Answers