Search Unity

  1. New Unity Live Help updates. Check them out here!

    Dismiss Notice

How to check object to start code?

Discussion in 'Scripting' started by daudau505, Sep 26, 2014.

  1. daudau505

    daudau505

    Joined:
    Jul 19, 2014
    Posts:
    27
    Hi, I'm very new to unity3d, I've been trying for hours now, but can't seem to figure it out.
    Basically this is an enemies object with a NavMesh2D pathfinding script. that require you to press E key for it to run the code?

    How can I make this activate or run the code without pressing the key E?
    I have tried " if(Gameobject.find("tag")" and some other combination, but I can't seem to get it working correctly.

    Sorry for not knowing how to explain this better.

    Thanks the your help.



    Code (CSharp):
    1. using PigeonCoopToolkit.Navmesh2D;
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6.  
    7. public class PathFollowercopy : MonoBehaviour
    8. {
    9.    
    10.     public Transform pathingTarget;
    11.     private List<Vector2> path;
    12.    
    13.     // LateUpdate is called once per frame
    14.     void Update () {
    15.         if(Input.GetKeyDown(KeyCode.E)) //how would I change this to where I don't have to do anything to start the code below?
    16.         {
    17.             path = NavMesh2D.GetSmoothedPath(transform.position, pathingTarget.position);
    18.         }
    19.        
    20.         if(path != null && path.Count != 0)
    21.         {
    22.             transform.position = Vector2.MoveTowards(transform.position, path[0], 5*Time.deltaTime);
    23.             if(Vector2.Distance(transform.position,path[0]) < 0.01f)
    24.             {
    25.                 path.RemoveAt(0);
    26.             }
    27.         }
    28.     }
    29. }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    7,322
    Have you tried "if (path == null)"?
     
    daudau505 likes this.
  3. Cpt Chuckles

    Cpt Chuckles

    Joined:
    Dec 31, 2012
    Posts:
    86
    Code (csharp):
    1. using UnityEngine;
    2. //etc.
    3.  
    4. public class PathFollowercopy : MonoBehaviour {
    5.  
    6.     public Transofmr pathingTarget;
    7.     private List<Vector2> path;
    8.  
    9.     void Awake() //this is the function you need
    10.     {
    11.         path = NavMesh2D.GetSmoothedPath(transform.position, pathingTarget.position);
    12.     }
    13.    
    14.     void Update() {
    15.         //etc.
    16.     }
    17. }
     
    daudau505 likes this.
  4. daudau505

    daudau505

    Joined:
    Jul 19, 2014
    Posts:
    27
    Both work great! Thanks Guys!
     
unityunity