Search Unity

want to target rocket to nearest gameobject who is tag as Enemy, after instintiate !

Discussion in 'Scripting' started by ashishkushwaha, Sep 16, 2019.

  1. ashishkushwaha

    ashishkushwaha

    Joined:
    May 12, 2015
    Posts:
    35
    can anybody help , :(after spawning rocket its going towards left direction , this issue can be fixed if it automatically locked its target when get instantiate




    Code (CSharp):
    1. public class HelicopterRocket : MonoBehaviour
    2. {
    3.     private new Rigidbody rigidbody;
    4.     private bool launched;
    5.     public float Speed;
    6.     public GameObject ExplosionFx;
    7.     bool fire;
    8.     void Start()
    9.     {
    10.         rigidbody = GetComponent<Rigidbody>();
    11.         launched = false;
    12.         fire = true;
    13.     }
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    17.         if (fire==true)
    18.         {
    19.             rigidbody.isKinematic = false;
    20.              rigidbody.velocity = transform.forward * Speed;
    21.          
    22.             launched = true;
    23.             var f = transform.Find("Fire");
    24.            var p= f.GetComponent<ParticleSystem>();
    25.             var e = p.emission;
    26.             e.enabled = true;
    27.         }
    28.         if (launched)
    29.         {
    30.             transform.rotation = Quaternion.LookRotation(rigidbody.velocity);
    31.          
    32.         }
    33.      
    34.     }
    35.     private void OnCollisionEnter(Collision collision)
    36.     {
    37.         Instantiate(ExplosionFx, transform.position, Quaternion.identity);
    38.        Destroy(gameObject);
    39.     }
    40. }


    // launched script

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class MissileButtonLauncher : MonoBehaviour
    5. {
    6.     public GameObject Missileprefab;
    7.     public GameObject missileSpwawnpoint;
    8.     // Start is called before the first frame update
    9.     void Start()
    10.     {
    11.    
    12.     }
    13.     // Update is called once per frame
    14.     void Update()
    15.     {
    16.    
    17.     }
    18.     public void missileLaunched()
    19.     {
    20.         Instantiate(Missileprefab,missileSpwawnpoint.transform.position, Quaternion.identity);
    21.     }
    22. }
     
    Last edited: Sep 16, 2019
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Use code tags (see the first sticky post), it makes it easier to read and talk about your code.
     
  3. ashishkushwaha

    ashishkushwaha

    Joined:
    May 12, 2015
    Posts:
    35
    done !
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    OK, so in HelicopterRocket's start, you need to:
    1) Find all the objects with the desired tag
    2) find which one of these is closest

    And then continually:
    3) Aim towards that object

    1 is easy: FindGameObjectsWithTag.
    2 is a little harder, but a "find lowest-valued whatever" algorithm is something that you'll want to have in your programming toolchest. It basically looks like:
    Code (csharp):
    1. GameObject[] allEnemies = FindGameObjectsWithTag("Enemy");
    2. GameObject closestEnemy = null;
    3. float lowestDist = 99999f;
    4. for (int e=0;e<allEnemies.Length;e++) {
    5. float thisDist = Vector3.Distance(transform.position, allEnemies[e].transform.position);
    6. if (thisDist < lowestDist) {
    7. lowestDist = thisDist;
    8. closestEnemy = allEnemies[e];
    9. }
    10. }
    11. //now, closestEnemy has a valid value and you can do whatever with it.
     
    ashishkushwaha likes this.
  5. CosmicGiant

    CosmicGiant

    Joined:
    Jul 22, 2014
    Posts:
    23
    Depending on the number of rockets and/or enemies that can be present at any one time, it might be a good idea to create a centralized list of enemies, in the game-manager for example, where enemies register themselves on spawn and unregister on despawn. This prevents having to
    FindGameObjectsWithTag
    every time a missile is fired, which is an expensive operation.


    The core of the behaviour is the same:

    Code (CSharp):
    1.  
    2. GameObject GetClosestEnemy() {
    3.     GameObject closestEnemy = null;
    4.     var closestEnemyDistance = float.PositiveInfinity;
    5.     foreach (var enemy in someCollectionOfAllEnemies) {
    6.         var enemyDistance = Vector3.Distance(transform.position, enemy.transform.position);
    7.         if (enemyDistance < closestEnemyDistance) {
    8.             closestEnemy = enemy;
    9.             closestEnemyDistance = enemyDistance;
    10.         }
    11.     }
    12. }
    13.  
    Also, it is recommended to
    FindGameObjectsOfType<>
    instead of finding by tag, as that avoids the problems related to using "magic strings", and I hear finding by tag is also expensive.
     
  6. ashishkushwaha

    ashishkushwaha

    Joined:
    May 12, 2015
    Posts:
    35
    not enough experience in coding how can i implement this ! and yes you are right tag system is bit heavy because i also found this kind of issue , but no idea how to define
    FindGameObjectsOfType<>
    , means in tag system i create tag to distinguished gameobjects , but
    FindGameObjectsOfType<>
    how system know this game object is enemy , and this game object is ally ?
     
  7. ashishkushwaha

    ashishkushwaha

    Joined:
    May 12, 2015
    Posts:
    35
    getting error but not getting it how to implement this :(
     
  8. CosmicGiant

    CosmicGiant

    Joined:
    Jul 22, 2014
    Posts:
    23
    That is c# generics. Your enemies probably have a specific script that only enemies have. You can use that to find all enemies without using tags or magic strings. Put the script's type between the <>:
    FindObjectsOfType<YourEnemyScript>()
     
  9. ashishkushwaha

    ashishkushwaha

    Joined:
    May 12, 2015
    Posts:
    35
    , after waiting to get response nobody came ,thanks for the reply but i used tag system , i will try this "FindObjectsOfType<YourEnemyScript>()" in updates if i can ! anyways thanks for the awesome reply !
     
  10. CosmicGiant

    CosmicGiant

    Joined:
    Jul 22, 2014
    Posts:
    23
    Sorry it took a while. I am not very active in the unity forums. I tend to stay in StackOverflow.

    It's not that you absolutelly can't use the tag system. It's just that you should generally avoid magic strings, because it is very easy to mess up the references by using the wrong string, making typos, etc, and also very unfriendly to modifications, as strings will still be valid, but the references they represent will not, if you change a tag.

    You can make it work with a management system to remove the "magic" part, and make the string references more solid. It's not too hard to do either. Maybe look into c# enums if you really want to implement it like that. But it's not too beginner-friendly, so considering you're not familiar with even generics yet, I'd recommend not doing it just yet.
     
  11. ashishkushwaha

    ashishkushwaha

    Joined:
    May 12, 2015
    Posts:
    35
    thanks , :D