Search Unity

How to make one object move to another object by tag?

Discussion in 'Getting Started' started by Pollawat, Jul 11, 2018.

  1. Pollawat

    Pollawat

    Joined:
    Aug 27, 2016
    Posts:
    192
    Hello sir. I'm a newbie and sorry if this is a stupid question.

    For example, I need missile move to an enemy with a tag called "Enemy", so now, how can I write a concept of creating object A that can detect object B (with object B tag) and move to it.

    Thank you.
     
  2. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    There are a multitude of ways to do this, the specifics of which depends on your game. Should missiles target any enemy at random? Or try to find the ones closest along its path? Do they have to be within a certain range? If the missile passes the target, does it turn around or try to acquire a new target? The more complex the logic, the more robust the code will need to be.

    With that said, to simply get the a random enemy and move a missile towards them when spawned, start with something like this:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SimpleMissile : MonoBehaviour {
    6.     public float missileSpeed = 5f;
    7.     private GameObject[] enemies;
    8.     private Transform targetedEnemy;
    9.  
    10.     void Awake () {
    11.         enemies = GameObject.FindGameObjectsWithTag ("Enemy");
    12.         targetedEnemy = enemies[Random.Range (0, enemies.length)].transform;
    13.     }
    14.  
    15.     void Update () {
    16.         float step = missileSpeed * Time.deltaTime;
    17.         transform.position = Vector3.MoveTowards (transform.position, targetedEnemy.position, step);
    18.     }
    19. }
     
    CurryQuest, Pollawat and JoeStrout like this.
  3. Pollawat

    Pollawat

    Joined:
    Aug 27, 2016
    Posts:
    192
    Thank you, sir, Accuracy I using to move enemy at the right position to execute by a player character, and look like it working out.
     
  4. Altonilite

    Altonilite

    Joined:
    Feb 1, 2023
    Posts:
    2
    weird, it doesnt work for me. it says that the index was out of bounds of the array.