NKolda
1
Ok So I’ve got this block of code as of right now for when my player hits the ball. Right now, this does what I want it to do:
-checks the position of the ball.
-gets rid of the ball if the user presses a button at the right time.
Now, this script is attached to the ball and not the player, so I wouldn’t be able to set a trigger from the player’s animator like I normally would. Is there a line of code I can put so that I can utilise the player animator here?
You can use this code but it’s not optimal.
FindObjectOfType<PlayerScript>().GetComponent<Animator>().SetTrigger("Start");
Check this out: Animator.SetTrigger
Or better way,
[SerializeField] private Animator playerAnimator;
private void Hit()
{
if(yourStatement)
{
playerAnimator.SetTrigger("Start");
Destroy(gameObject);
}
}
You could create a static instance of a script attached to your player object and reference that. For example, say you have a script attached to your player object called “PlayerController.” In that script you would have something like
{
public static PlayerController instance;
void Start(){
if (!instance)
instance = this;
}
}
Then in your ball code you could have something like
private void Hit()
{
if(transform.position.x > -5 && transform.position.x < 1 && Input.GetKeyDown(KeyCode.LeftShift))
{
PlayerController.instance.GetComponent<Animator>().SetTrigger("Whatever");
Destroy(gameObject);
}
}
I’d point out that it’s important to have the animation event triggered before destroying the gameobject, unlike you have in your image as once the gameObject is destroyed, the script will go with it and fail to complete anything you had set to happen after.
Also, you can only have a single static instance of a script at a time. So if you were to have multiple player gameobjects with the PlayerController script, this wouldn’t work. The beauty of static instances such as these is that you don’t need an object to reference them, as you can see in the block of code. It’s as easy as directly referencing the script.instance. This is far faster and more efficient than trying to search for a game object by tag or component.