- Home /
Detecting collision with a specific game object while being a child
I am programming a timer for my game. I am trying to implement an obstacle where the timer gets subtracted my 2 seconds if the player touches a specific cube. I have made a lot of progress, however, I need the specific item to be a child of another game object.
#pragma strict
var timercode : GameObject;
function OnCollisionEnter (hit : Collision){
if(hit.transform.gameObject.name == "timecube")
{
timercode.GetComponent.< timer >().gametime -= 2;
}
}
the code above works perfectly only if the timecube is not a child of another object. The way the game functions relys that the timecube is a child. How can i modify the line if(hit.transform.gameObject.name == "timecube") if timecube is a child?
Also, the timecube has to be a child of an item called "Pivot", if that helps. This code is running on the player. I will answer any extra questions.
Answer by Habitablaba · Jun 20, 2017 at 09:34 PM
Here is the (untested) code I've come up with to solve this problem without modifying your code too much.
if(hit.transform.gameObject.name == "Pivot"){
for(int i = 0; i < hit.transform.childCount; ++i){
var child = hit.transform.GetChild(i);
if(child.name == "timecube"){
timercode.GetComponent.<Timer>().gametime -=2;
break;
}
}
}
looks good, although, unity Console is telling me the two ; in the code are causing it to error.
Any ideas?
its saying: Assets/Scripts/playercontroll.js(32,13): BCE0044: expecting ;, found 'i'.
and
Assets/Scripts/playercontroll.js(32,53): BCE0043: Unexpected token: ).
I looked into it a bit and just changed where the 'i' variable is it has to be declared before the loop (for some reason), like this:
var timercode : GameObject;
var i: int;
function OnCollisionEnter (hit : Collision){
if(hit.transform.gameObject.name == "Pivot"){
for(i = 0; i < hit.transform.childCount; i++){
var child = hit.transform.GetChild(i);
if(child.name == "timecube"){
timercode.GetComponent.<Timer>().gametime -=2;
break;
}
}
}
}
It works, sort of. The timer only gets subtracted if it collides with a block that isn't the timer block! I'm not sure what to do.
Your answer
![](https://koobas.hobune.stream/wayback/20220612124553im_/https://answers.unity.com/themes/thub/images/avi.jpg)