Multiple GameObjects with same Script
I have a prefab which is instantiated in the scene ( 6 copies of prefab). I am trying to disable it with a touch on it , but when i tap on it it disables all the gameObjects of the prefab. I am using single Script to destroy it.
i can't figure what is happening. Can anyone check what 's wrong i am doing here....
void Update () {
for (int i = 0; i < Input.touchCount; i++)
{
if (Input.GetTouch (i).phase == TouchPhase.Stationary) {
hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.GetTouch (i).position), Vector2.zero);
if (hit.collider != null && hit.transform.gameObject.tag == "BlackSquare")
ClickedDown (hit.collider);
}
}
void ClickedDown(Collider2D collider){
Instantiate (blastEffect,transform.position,transform.rotation);
this.gameObject.SetActive (false);
waitForSecondsCounter = waitForSeconds;
Color c = this.transform.GetComponent <SpriteRenderer>().color;
c.a = 1f;
this.transform.GetComponent <SpriteRenderer> ().color = c;
}
Answer by Redwolve · Apr 12, 2016 at 03:38 AM
Your problem appears to be that you are setting a conditional in the Update() that makes perfect sense. However, by using
this.gameObject.SetActive(false);
instead of
collider.gameObject.SetActive(false);
you are essentially telling every prefab "hey you saw this object get touched so disable yourself", you are not telling the script to disable the object attached to the collision rather all of the objects with this script.
That should do the trick, happened to me in the past as well. Please let me know if it works out for you!
@Redwolve you are saying correct and it works perfectly but when collider is null , then what to do in that case?
like when i am setting gameObject.SetActive(false); it is applied to al the prefab instances;
Here is my code
if (collider != null) {
Instantiate (blastEffect,collider.transform.position,collider.transform.rotation);
GameObject obj = collider.gameObject;
obj.SetActive (false);
Color color = obj.GetComponent <SpriteRenderer> ().color;
color.a = 1f;
obj.GetComponent <SpriteRenderer> ().color = color;
waitForSecondsCounter = waitForSeconds;
} else {
Instantiate (blastEffect,transform.position,transform.rotation);
gameObject.SetActive (false);
Color c = sprite.color;
c.a = 1f;
sprite.color = c;
waitForSecondsCounter = waitForSeconds;
}
What are you wanting to happen different when the collider is not detected? Your code looks about the same for if and for else
Your answer
Follow this Question
Related Questions
GetComponent is not a member of Object 0 Answers
Enable/Disable other gameobject's scripts Unity 5 0 Answers
Reset rotation of gameobject 1 Answer