The question is answered, right answer was accepted
How to make a prefab remember a public gameObject?
I am making a survival game and i have a problem. I made it so the way you pick up items needs to remember a gameobject because the script is on the item itselft, but when i instantiate the object it doesnt remember that gameobject. How do i fix this? (I dont know everything about scripting yet)
script for the object "stick" :
private bool Collect;
public GameObject gameobject;
private Inventory inventory;
void Start()
{
inventory = gameobject.GetComponent<Inventory>();
Collect = false;
}
void Update()
{
if (Collect == true)
if (Input.GetButton("pickup"))
{
inventory.sticks += 1;
Destroy(gameObject);
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == ("collector"))
{
Collect = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.name == ("collector"))
{
Collect = false;
}
}
(collector is a dot in the middle of the screen that has a long block collider and is attached to the camera)
Answer by Elthen · Aug 04, 2017 at 02:37 PM
If I undersand correctly; You should make that variable private and in start get a reference to it, like so:
gameobject= GameObject.FindGameObjectsWithTag("YourTag");
Just create a tag inside the inspector and assign it to your object, then replace "YourTag" with the name of the tag you've created.
awesome, glad I could help; remember to accept to answer!^^
Answer by ShadyProductions · Aug 04, 2017 at 02:14 PM
instead of Destroy(gameObject);
do
gameObject.enabled = false;
And from the moment you know that you can 100% remove the item then you destroy it
That can be useful but i already dont need it after i have added +1 to the inventory .
Then why do you still need to reference it :) $$anonymous$$aybe I don't understand your question, what do you mean with after instantiate it doesn't remember it. Can you explain? and maybe share the instantation code aswel.
because i want the game to be a survival game and when you cut down a tree it drops sticks and logs
Follow this Question
Related Questions
Only allowing one instance of prefab created by button press & destroying prefab on collision? 0 Answers
How to instantiate a prefab using a string variable ? 1 Answer
How to copy GameObject and preserve Prefab connection and Component values from editor script 2 Answers
Making a time bomb 1 Answer
Problems with instantiated objects in a circle formation 0 Answers