Kindest regards everyone. I am a newbie when it comes to Unity and c# scripting and I kindly ask for your help. In my project, I have a button which changes its image on press and I have random prefab spawner. Prefabs have the same images as the button. Simple thing I want to achieve is, when image of the button and image of the spawned prefab which collide are the same do something and when they are different do something else. I dont know how to link that collision between button image and the prefab. I tough I could do it with tags but i can not attach tags to images which change when button is pressed. Any idea is welcome and thanks in advance.
get their sprite renderer components and check them if are equal. Or if your gameobjects already have an animator, check if their animation states are equal.
If both button and prefab have colliders https://docs.unity3d.com/Manual/Collider2D.html you have to decide do you need those two colliders to interact (button hitting prefab stops prefab or something else) or if that is not needed you can make both collider triggers (there is option in collider for that https://docs.unity3d.com/Manual/class-BoxCollider2D.html first image). Then, use OnCollisionEnter2D, OnCollisionStay2D or OnTriggerEnter2D, OnTriggerStay2D to detect on one object collision with other. Example is here: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionStay2D.html Lets say that this is in your button script: Code (CSharp): void OnTriggerStay2D(Collider2D objectThatCollidedWithButton) { if ( gameObject.GetComponent<SpriteRenderer>().sprite == objectThatCollidedWithButton.gameObject.GetComponent<SpriteRenderer>().sprite ) { // Do something when sprite on button and prefab are the same } } - gameObject.GetComponent<SpriteRenderer>().sprite - this is sprite on your button - objectThatCollidedWithButton.gameObject.GetComponent<SpriteRenderer>().sprite - this is sprite on object that collided with button If you use UI element as button you need to enable collision between those layers in project settings: https://docs.unity3d.com/Manual/LayerBasedCollision.html and you cannot reference sprite on UI element with SpriteRenderer https://learn.unity.com/tutorial/ui-components#5c7f8528edbc2a002053b4d2 and then on button use: gameObject.GetComponent<Image>().sprite == objectThatCollidedWithButton.gameObject.GetComponent<SpriteRenderer>().sprite Off course, both sprites must be the exact same image from Assets. If that is not the case, maybe try comparing sprite.name