- Home /
How do i understand which gameObject is player touching ?
I have a game with 4 stationary balls and 1 cube (player) like that one in image. Every time player touches balls, it get destroyed, and new Player (cube) appears with a random color (Red, Blue, Green or Yellow).
My question is, how do i write a code that understands if player touches ball with the same color as he is, in order to add score, or to end the game if he touches ball with different color? This is my actual script:
using UnityEngine;
using System.Collections;
public class DestroyOnContact : MonoBehaviour {
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "Player")
{
Destroy (gameObject);
//AddScore();
}
}
}
!
Answer by etaxi341 · Aug 30, 2016 at 02:39 PM
you can acces the material of the collided Gameobject.
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "Player")
{
if (col.gameObject.GetComponent<Renderer>().material.color = GetComponent<Renderer>().material.color)
//DIE
}
}
In this script you just compare the 2 colors of the materials. if they are exactly the same the player dies
FWIW I don't think using the material color is a good idea, because it's pretty inflexible. I would have given each object a different tag (which you can easily set in the editor) and then checked col.tag.
Or a public variable that says the color, to just use Color.green etc.
Also, (maybe) the material color might change in compression if it happens
Your answer
Follow this Question
Related Questions
How to detect collision between 2 objects while checking are they the ones that need to collide? 1 Answer
Avoid Player bouncing when colliding with objects 3D 1 Answer
How to do collision of external objects on script? 1 Answer
Colliders not working when rotating 2 Answers
Mesh Collider doesn't work without reset 2 Answers