Problems with get component

Hi,
I have a Main Camera with a Camera 2D Follow Component. I want to change the target of this script by script, using get component, but Get component don’t find “Camera2DFollow” As a component of the main camera.

How i can solve this?

//this script is attached to Main Camera//

using UnityEngine;
using System.Collections;

public class CreaNavicellaRandom : MonoBehaviour {
    int rnd;
    public GameObject Arancione;
    public GameObject Azzurro;
    public GameObject Bianco;
    public GameObject Blu;
    public GameObject Giallo;
    public GameObject Nero;
    public GameObject Rosso;
    public GameObject Rosa;
    public GameObject Verde;
    public GameObject Viola;
    // Use this for initialization
    // Da aggiunger la posizione Randomica una volta detereminato lo spazio in cui possono muoversi le cellule
    void Start () {
        rnd=Random.Range(1,11);
        switch (rnd) {
        case 1:
            Instantiate(Arancione);
            break;
        case 2:
            Instantiate(Azzurro);
            break;
        case 3:
            Instantiate(Bianco);
            break;
        case 4:
            Instantiate(Blu);
            break;
        case 5:
            Instantiate(Giallo);
            break;
        case 6:
            Instantiate(Nero);
            break;
        case 7:
            Instantiate(Rosso);
            break;
        case 8:
            Instantiate(Rosa);
            break;
        case 9:
            Instantiate(Verde);
            break;
        case 10:
            Instantiate(Viola);
            break;

        }
        GetComponent<Camera2DFollow> ().target = GameObject.FindGameObjectWithTag ("Player").transform;
    }
   
    // Update is called once per frame
    void Update () {
   
    }
}

this will work only if that instance of the class CreaNavicellaRandom is a component of the camera.

If CreaNavicellaRandom is not a component of the camera and your camera is tagged as main camera you could use Camera.main.transform.GetComponent().target

(edit) if both scripts are components of the main camera it should work

(second edit) unless you’re instantiating your player object on start and script execution order is not on your side… you should make sure that the player object already exists when the start method gets called.

I tried to put that function in awake beacouse camera start on void start, but still don’t work

Just to be sure: “Get component don’t find ‘Camera2DFollow’” means there’s a runtime error like NullReferenceException: Object reference not set to an instance of an object or something?

Or are we talking about error CS0246: The type or namespace name `Camera2DFollow’ could not be found. Are you missing a using directive or an assembly reference?

Out of sheer curiosity… did you type those errors out from memory? lol

Of course not. :slight_smile: