- Home /
Referencing a collision from another script
So I want a collision from gameobjects 'Player' and 'Ball' to effect a variable in my timer script.
Is there a way to detect a collision between two objects on a separate script? I know how to detect a collision if the script is attached to the gameobject directly, but I need my collision detection to be on my timer script so I can effect it's variables.
public class Timer : MonoBehaviour {
public float timer = 300;
public float timerSpeed = 100;
void OnGUI () {
timer -= Time.deltaTime*timerSpeed;
if (timer > 0)
guiText.text = timer.ToString("F0");
else
guiText.text = "GAME OVER";
}
void OnCollisionEnter(Collision thecollision){
if(thecollision.gameObject.name == "Player")
timerSpeed = 50;
}
}
Anyway this is what I know what to do.
Very new to all this so any help would be most appreciated.
Answer by flaviusxvii · Sep 06, 2013 at 03:11 PM
You probably want the OnCollisionEnter function on your Player component. When a collision happens with a gameObject with a Ball component, announce the collision to your gameObject with Timer.
//// In Player.cs
void OnCollisionEnter(Collision thecollision){
if(thecollision.gameObject.name == "Ball") {
GameObject.Find("Timer").GetComponent<Timer>().whateverYouWant();
}
}
Thank you! I have been trying to work out how to use GetComponent and this is exactly what I needed.
Don't forget to upvote and accept the answer if it helped.
Your answer
![](https://koobas.hobune.stream/wayback/20220613113705im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Decrease life from another script 1 Answer
How to access Particle System Collision to change at runtime 1 Answer
Javascript score problems whilst referencing scripts. 2 Answers
How do you change a variable in a script, that is on an object instantiated from a prefab? 0 Answers
Variables from one script to another. 3 Answers