- Home /
Get access of just one clone's component in a script attached to that clone
Hi! I'm very new at this. I've been trying to get to the components of a clone but it keeps returning all the component of all the instantiated clones instead of the one the script is attached to.
This is the script that is attached to the objects.
using System.Collections; using System.Collections.Generic; using UnityEngine;
namespace Completed { public class CompareCards : MonoBehaviour {
[HideInInspector]public Sprite m_SelectedCard;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown ("mouse 0")) {
GetSelectedCard ();
}
}
void GetSelectedCard() {
Sprite selectedCard = m_SelectedCard;
selectedCard = gameObject.GetComponent<SpriteRenderer>().sprite;
Debug.Log ("m_SelectedCard in CompareCards: " + selectedCard);
}
Debug.Log shows mee that it get's the sprite of all the clones and not just the one the script is attached to. I need to select one so I can compare it to an other.
Thanks for any help you can offer!
To Elaborate. I need to get to the gameobjects component using the script attached to the gameobject. (script attached to a button with a sprite)
Answer by UDM1983 · Jan 26, 2017 at 11:33 AM
Since all the clones have this script on them, when you press the mouse 0 button, all scripts on all objects run at once, thus why you get this. To fix it, use a bool like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Completed {
public class CompareCards : MonoBehaviour {
[HideInInspector]public Sprite m_SelectedCard;
// Only the current selected card should have isSelected true.
public bool isSelected = false;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown ("mouse 0")) {
GetSelectedCard ();
}
}
void GetSelectedCard() {
Sprite selectedCard = m_SelectedCard;
if (isSelected)
{
selectedCard = gameObject.GetComponent<SpriteRenderer>().sprite;
Debug.Log ("m_SelectedCard in CompareCards: " + selectedCard);
}
}
Thanks for trying to help! I finally managed to get it to work with "button.onClick.AddListner(function)". I also had to add an image(script) to my button to make it able to register the click. It didn't have one since I started out with a spimple sprite ins$$anonymous$$d of a button. Rooky mistake, I'm sure but this is my first attempt at creating something myself.