error CS0029: Trying to access component in parent - c#

Hello there,

I’m trying to access the rigidbody2D and Animator in the parent of the gameobject this script is attached to.

However I get this: Assets/scripts/EnemyMoveLeft.cs(17,17): error CS0029: Cannot implicitly convert type UnityEngine.Animator[]' to UnityEngine.Animator’

Script:

using UnityEngine;
using System.Collections;

public class EnemyMoveLeft : MonoBehaviour {

	public Rigidbody2D rb;
	public Animator anim;
	MovementController player;

	public Vector2 newPos;
	public Vector2 negativeNewPos;
	
	public float maxSpeed;

	void Start()
	{
		anim = GetComponentsInParent<Animator> ();
		rb = GetComponentInParent<Rigidbody2D> ();
		player = GameObject.FindGameObjectWithTag ("Player").GetComponent<MovementController> ();
	}

	void OnTriggerEnter2D(Collider2D col)
	{
		if(col.isTrigger = !true && col.CompareTag ("Player"))
		{
			anim.SetFloat("Speed",Mathf.Abs(1));
			rigidbody2D.velocity = new Vector2(-maxSpeed, rigidbody2D.velocity.y);
		}
	}
}

Is it something to do with the brackets around the animator?

Thanks in advance!!

Instead of

anim = GetComponentsInParent<Animator> ();

use

anim = GetComponentInParent<Animator> ();

You are using GetComponentsInParent (notice ‘s’ after component) to get Animator component which will return an array since it is used to get multiple components.

If you want to get just one component then use GetComponentInParent which you have used to get the Rigidbody2D component on parent. Or if you want to get multiple Animator components attached to parent then you should use GetComponentsInParent as you are doing currently but make your anim variable to be an array of Animator like:

public Animator[] anim;