easy Question getComponent [SOLVED]

Simple question, how do i tell the variable “player” that it has to look for the Gameobject with the Tag Player.

The script is for a Homing missle which is instanciated as a prefab shot vom a Turret.

using UnityEngine;
using System.Collections;

public class Homing : MonoBehaviour {

    public float speed;
    private Transform player;


    void Start() // how do i say that player is the GameObject with the tag Player ???
    {
        player = gameObject.GetComponent<transform>GameObject.FindGameObjectWithTag("Player");             //GameObject.FindGameObjectWithTag ("Player");  
//  <-- this is not corret right?^^
    }


    void FixedUpdate ()
    {
        float z = Mathf.Atan2 ((player.transform.position.y - transform.position.y), (player.transform.position.x - transform.position.x)) * Mathf.Rad2Deg - 90;
        transform.eulerAngles = new Vector3 (0, 0, z);
        rigidbody2D.AddForce (gameObject.transform.up * speed);
    }

    void OnTriggerEnter2D (Collider2D coll)
    {
        if (coll.gameObject.tag == "Respawn") {
         
         
            Destroy(gameObject); // , 0.3f   für ani delay
         
        }

    }


}

do you want your player variable to be a transform or a GameObject?

your player variable is a transform so

player = GameObject.FindWithTag (“Player”).transform;

if you make player a GameObject leave .transform out

  1. determining the difficulty to a question you yourself don’t know the answer to… not exactly accurate

  2. what? what do you mean by “look for the GameObject”?

If you want to find something by tag:

GameObject.FindWithTag:

    void Start()
    {
        GameObject goPlayer = GameObject.FindGameObjectWithTag("Player");

        if (goPlayer != null) {
               player = goPlayer.transform;
        }
    }

Change
player = gameObject.GetComponentGameObject.FindGameObjectWithTag(“Player”);

To
player = GameObject.FindGameObjectWithTag (“Player”).transform;

1 Like

Hehe.

Thats what comes from opening windows and not replying instantly - well what Sbizz said, cheching for null would be best :wink:

thats exactly what i was looking for :slight_smile:

THX !