- Home /
All instances of a prefab effected by single access -- no Static variables
I'm really at my wits end with this. Sunk a bunch of time into figuring out how to access a variable attached to an object that was a child of a child. I've got some treasure chests that are supposed to open when I 'ping' them from a second script. I figured out how to access the script, but now all of the treasure chests open with one click which I don't want. I have not declared any static variables, but its as though I'm using some kind of implicit static declaration. I can't find anything unusual assigned in the inspector. Here's the code from the animation script:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Animator))]
//[RequireComponent(typeof(SonarcursorScript))]
public class TreasureControl : MonoBehaviour {
public SonarcursorScript sonarcursorScript;
public GameObject TreasureLight;
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
anim.SetBool ("open", false);
TreasureLight.renderer.enabled=false;
GameObject sub = GameObject.Find ("Sub");
sonarcursorScript = sub.GetComponentInChildren<SonarcursorScript>();
}
// Update is called once per frame
void Update () {
if (sonarcursorScript.boxInt == 21)
{
anim.SetBool ("open", true);
// Debug.Log ("This is it "+sonarcursorScript.boxInt);
TreasureLight.renderer.enabled=true;
}
}
}
and relevant code from the calling script:
using UnityEngine;
using System.Collections;
public class SonarcursorScript : MonoBehaviour {
public int boxInt = 0;
public string sonrTarget = "helpme";
void Update() {
if(sonrTarget == "Box")
boxInt =21;
}
When boxInt is passed as 21 to TreasureControl.cs, all my boxes animate at once. They were all instances of the same prefab. Breaking the prefab instance did not fix it. Changing the instantiation method didn't either. I'd appreciate any help. Thanks!
Follow-up. I created a new treasureControl2.cs script as well as a new animator (both renamed), attached them to one of the chests, and they all still opened at once - even with different/multiple scripts and controllers .
how you distinguish between what you clicked , how you check which object you clicked
Answer by robertbu · Sep 27, 2014 at 03:44 PM
The problem is how you have things structured, but since I don't know your hierarchy, I'm unsure of the fix. These two lines:
GameObject sub = GameObject.Find ("Sub");
sonarcursorScript = sub.GetComponentInChildren<SonarcursorScript>();
...will always return the same game object, and therefore the same component.
Your answer

Follow this Question
Related Questions
Get list of gameObjects and change booleans within them 2 Answers
GameObject.FindGameObjectWithTag 3 Answers
Find a GameObject without a reference 2 Answers
C# to find a Object in a direction on a 2D map 0 Answers
Remove all objects that a certain type 2 Answers