- Home /
How to activate the child of an object without declaring a public transform?
My script is pretty simple. It involves a stick which I want to pick up, so when I walk into the box collider it is triggered and if I press E the stick is destroyed.
The problem is that I have a small floating 'E' above the stick so that the player knows which button to press in order to pick up the stick, this 'E' appears when you walk into the collider and is a child of the stick.
So when I destroy the stick I get an error saying that I am still trying to access the object after I have destroyed it. This is because I have publicly declared the child transform. Is there another way to setActive() the child of the stick without having to publicly declare the transform?
Here is my code......
using UnityEngine; using System.Collections;
public class PlayerInv : MonoBehaviour {
public GameObject interactIcon;
void OnTriggerStay(Collider col){
if(col.gameObject.CompareTag("Stick"))
{
interactIcon.gameObject.SetActive (true);
if(Input.GetKeyDown(KeyCode.E))
{
Destroy(col.gameObject);
}
}
}
void OnTriggerExit(Collider col){
if(col.gameObject.CompareTag("Stick"))
{
interactIcon.gameObject.SetActive (false);
}
Debug.Log ("exiting collider");
}
}
Quote: So when I destroy the stick I get an error saying that I am still trying to access the object after I have destroyed it.
I might sound like a CO, but don't access it. It's now destroyed. But to be serious: I would inject the E marker of the stick into the stick script. So when you enter a collider which you are sure is associated with a stick (check it either against a tag, a name, a component presence, etc.), get the stick component from the collider's game object and do whatever you're pleased with it inlcluding messing with marker. If the stick is destroyed - its collider won't trigger, so there is no stick and therefore no marker to access from. You have a rather logical problem, as you mess with dependencies in an unconventional way. The marker belongs to the stick, so why is it treated as it's a standalone object being able to exist without the stick. Why do you inject it into your player script bypassing the stick-owner. Decide on main participants of you gameplay/simulation first and it will be clear what to inject where, and who belongs to whom. Program it as if there is no marker first, just the player and the stick. And then add methods Show$$anonymous$$arker() and Hide$$anonymous$$arker() to the stick managing the marker injection internally in the stick script.
Answer by Owen-Reynolds · Aug 08, 2015 at 05:45 PM
" error [...] because I have publicly declared the child transform."
No. That's not true. It's like saying your fingers are smashed because your car has doors. The real problem is that you're using it wrong.
I think stepan_stulov is correct. Are you destroying the E marker? Pause the game and look for it. Do you want to destroy it? If not, how can you avoid it's destruction?