- Home /
Object script triggering player animation
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?
Answer by sirjoan620 · Jan 30, 2019 at 01:15 PM
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);
}
}
Ok so I was trying the top one`myAnimator = GameObject.FindObjectOfType().GetComponent();`
Didn't work :/. I was assu$$anonymous$$g where you put "PlayerScript", I'd just put the name of the player object - am I wrong there? Then it comes up with this error which I can't quite figure out: " The type or namespace name 'PlayerP' could not be found (are you missing a using directive or an assembly reference?)"
FindObjectOfType finds the component by searching all the scene objects. So you should give the component not the name of gameObject.
Look: FindObjectOfType Docs
Answer by Chimer0s · Feb 06, 2019 at 12:21 PM
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.
Your answer
