C# (Unity 4.3) Cannot implicitly convert type `ShotScript[]' to `ShotScript'

Thanks all! The issue was I was using GetComponents rather than GetComponent, thanks!

I am fairly new to programming and I am trying to make a 2D game in Unity. I have found a tutorial online which is really good, up until a point (Tut can be found here http://pixelnest.io/tutorials/2d-game-unity/shooting-1/). I've come across an error and can't figure out why. The error occurs when I try and use another script inside my current script (if that makes sense to anyone). The two scripts in question have the name ShotScript and HealthScript and they are below

ShotScript:

using UnityEngine;
using System.Collections;

public class ShotScript : MonoBehaviour {


public int damage = 1;

public bool isEnemyShot = false;

void Start () {

    Destroy (gameObject, 20);
}



}

HealthScript:

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {


public int hp = 2;

public bool isEnemy = true;

void OnTriggerEnter2D(Collider2D Collider) {

        ShotScript shot = collider.gameObject.GetComponents<ShotScript>();
            if (shot != null) {
                    if (shot.isEnemyShot != isEnemy) {
                            hp -= shot.damage;
                            Destroy (shot.gameObject);

                            if (hp <= 0) {
                                    Destroy(gameObject);
                            }
                    }
            }
    }


}

The error I get is: "Assets/Scripts/HealthScript.cs(13,36): error CS0029: Cannot implicitly convert type ShotScript[]' toShotScript'"

I'm rather stuck and so if anyone could point me in the right direction, that'll be great =)

P.S I'm new to this asking questions thing, so if you need any extra info, I'll do my best to provide it

Jon Skeet
people
quotationmark

Well this is the problem:

ShotScript shot = collider.gameObject.GetComponents<ShotScript>();

It sounds like GetComponents<ShotScript> is returning an array of ShotScript references, i.e. its return type is ShotScript.

Do you want to take the same action for each ShotScript? If so, you probably want to just use a foreach loop... although you probably only want to check for the hp going negative at the end. I would expect you to be able to remove the check for nullity, too, assuming that GetComponents will just return an empty array if there aren't any such components:

ShotScript[] shots = collider.gameObject.GetComponents<ShotScript>();
foreach (ShotScript shot in shots)
{
    if (shot.isEnemyShot != isEnemy)
    {
        hp -= shot.damage;
        Destroy(shot.gameObject);
    }
}
if (hp <= 0)
{
    Destroy(gameObject);
}

(I've reformatted that to be rather more conventional C#, but of course you can use whatever indentation you want.)

people

See more on this question at Stackoverflow