- Home /
Assign EventTrigger reference Script at Runtime
Hello,
I am working on a mobile racing game and the player can choose several cars to start racing.
The cars are controlled by a gas and brake button, therefore I have created for each a Eventtrigger with onPointerUp- and OnPointerDown-EventBaseDatas which will call functions of the car's script to control its velocity.
But since the player can choose every car, I need also to create the matching reference. [Dynamic]
Is there are way how to assign those reference-fields through code with the car script?
BTW, the player car is spawning correctly and easy to find through script, so the search will be easy, but it is not driveable like every other player-car because of the dynamic reference that is missing (as written above).
$$anonymous$$aybe have a look at this video - https://www.youtube.com/watch?v=YAnLL1$$anonymous$$CNoI
Answer by LazyElephant · Dec 12, 2015 at 09:58 PM
In your button scripts, you can get a reference to your car objects by using GameObject.Find (string object)
or GameObject.FindObjectWithTag (string tag)
For example
public class AccelerateButton {
private CarScript theCar;
void Start () {
theCar = GameObject.Find( "Car" ).GetComponent <CarScript>();
}
void OnPointerDown {
theCar.Accelerate();
}
//...
}
Apologies if there are any syntax errors, I'm posting from my phone.
So, am I supposed to assign the onPointerDown/Up-Functions to the OnClick()-field of the button-component?
If you want the button to keep working as long as you're holding the mouse button, you should use On$$anonymous$$ouseDown in your script to start acceleration and On$$anonymous$$ouseUp to stop it. OnClick only fires the event once after you release the mouse button.