- Home /
How to detect if a collider is touching a gameobject (java)
I've looked up multiple things, but none of them seem to work. I keep getting errors saying things like it doesn't recognize "col" as well as there being an unexpected token >.> All I want this snipit of script I have pasted to do is make the object go up when touching the ground
function Update () { void OnCollisionEnter(Collision col){ if(col.gameObject.name == "grassTerrain"){ transform.position.y = transform.position.y + 0.02; } } }
Any help is much appreciated ^-^
in unitys javascript/java there is no "void". you would replace "void" with "function"
also the OnCollisionEnter would not go inside the update funtion brackets. its its own thing.
I highly recommend learning C# and writing with that because its an industry standard language that is good to know and more people will offer help here.
Answer by Commoble · Mar 17, 2017 at 03:21 AM
OnCollisionEnter doesn't go inside Update, it's its own function.
You have:
void Update ()
{
void OnCollisionEnter(Collision col)
{
if(col.gameObject.name == "grassTerrain")
{
transform.position.y = transform.position.y + 0.02;
}
}
}
You should have:
void Update ()
{
// nothing in here yet
}
void OnCollisionEnter(Collision col)
{
if(col.gameObject.name == "grassTerrain")
{
transform.position.y = transform.position.y + 0.02;
}
}
This is one problem fixed, but your script still isn't valid, because you can't alter the x/y/z values of vectors in Transforms directly, you have to alter the whole vector, so you do this:
void Update ()
{
// nothing in here yet
}
void OnCollisionEnter(Collision col)
{
if(col.gameObject.name == "grassTerrain")
{
Vector3 oldPos = this.transform.position;
this.transform.position = new Vector3(oldPos.x, oldPos.y + 0.02F, oldPos.z);
}
}
The code in this script is now valid. I recommend against comparing strings in a collision or update event, and you probably won't notice the object going up by just 0.02 units, but it is valid code.
Your answer
Follow this Question
Related Questions
Collider waiting for two differently tagged game objects to enter before doing something 1 Answer
How to make objects collide once 1 Answer
Precise Collision Detection 0 Answers
collision detection 4 Answers
Collision detection when no collision happens,OnCollision is called without a collision 1 Answer