Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

[C#] Script problem

Discussion in 'Editor & General Support' started by Namarand, Aug 9, 2015.

  1. Namarand

    Namarand

    Joined:
    Aug 8, 2015
    Posts:
    2
    Hi,
    I work on a personal project and i'm facing to some dificulty.
    I've, in this game, some AI who look for enemy. They got a FOV made with Raycast. The player MeshRenderer was desactivate since they aren't in the AI FOV. For this, I use that script in this order :
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Control : MonoBehaviour {
    5.    
    6.    void Update () {
    7.      foreach (GameObject b in GameObject.FindGameObjectsWithTag ("Runner")) {
    8.        b.GetComponent<SeePlayer>().isSee = false;
    9.      }
    10.    }
    11. }
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class IA : MonoBehaviour
    6. {  
    7.    public float angle = 75f; // Angle d'ouverture, degré
    8.    public float distance = 10f;
    9.    public int precision = 20; // Nombre de rayons lancé dans l'angle ci dessus
    10.    public Material material; // Mat appliqué au mesh de vue
    11.    public bool debug = false; // Dessine les rayons dans la scene view
    12.    public float freq = 0.05F; // Fréquence de calcul. > 0.05F ça devient moche
    13.    public LayerMask mask; // Layers qui vont bloquer la vue
    14.    
    15.    Vector3[] directions; // va contenir les rayons, déterminés par precision, distance et angle
    16.    Mesh sightMesh; // Le mesh dont les vertex seront modifiés selons les obstacles
    17.    Transform m_Transform;
    18.    
    19.    int nbPoints;
    20.    int nbTriangle;
    21.    int nbFace;
    22.    int nbIndice;
    23.    int row;
    24.    Vector3[] points;
    25.    int[] indices;
    26.  
    27.    public float speed = 0.1f;
    28.    public List<Vector3> destination = new List<Vector3>(){new Vector3(3,0.73f,10)};
    29.    int i = 0;
    30.    GameObject target = null;
    31.    bool getTarget = false;
    32.    NavMeshAgent agent;
    33.    
    34.    // Use this for initialization
    35.    void Start ()
    36.    {
    37.      destination.Add (this.transform.position);
    38.      agent = this.gameObject.GetComponent<NavMeshAgent> ();
    39.      // Initialisation du cone
    40.      GameObject sightObject = new GameObject( "ConeSight" );
    41.      sightMesh = new Mesh();
    42.      (sightObject.AddComponent( typeof( MeshFilter )) as MeshFilter).mesh = sightMesh;
    43.      (sightObject.AddComponent( typeof( MeshRenderer )) as MeshRenderer).material = material;
    44.      m_Transform = transform; // histoire de limiter les getcomponent dans la boucle
    45.      
    46.      // Préparation des rayons
    47.      precision = precision > 1 ? precision : 2;
    48.      directions = new Vector3[precision];
    49.      float angle_start = -angle*0.5F;
    50.      float angle_step = angle / (precision-1);
    51.      for( int i = 0; i < precision; i++ )
    52.      {
    53.        Matrix4x4 mat = Matrix4x4.TRS( Vector3.zero, Quaternion.Euler(0,angle_start + i*angle_step,0), Vector3.one );
    54.        directions[i] = mat * Vector3.forward;
    55.      }
    56.      
    57.      // préparations des outils de manipulation du mesh
    58.      nbPoints =  precision*2;
    59.      nbTriangle = nbPoints - 2;
    60.      nbFace = nbTriangle / 2;
    61.      nbIndice =  nbTriangle * 3;
    62.      row = nbFace+1;
    63.      
    64.      points = new Vector3[nbPoints];
    65.      indices = new int[ nbIndice ];
    66.      
    67.      for( int i = 0; i < nbFace; i++ )
    68.      {
    69.        indices[i*6+0] = i+0;
    70.        indices[i*6+1] = i+1;
    71.        indices[i*6+2] = i+row;
    72.        indices[i*6+3] = i+1;
    73.        indices[i*6+4] = i+row+1;
    74.        indices[i*6+5] = i+row;
    75.      }
    76.      
    77.      sightMesh.vertices = new Vector3[nbPoints];
    78.      sightMesh.uv = new Vector2[nbPoints];
    79.      sightMesh.triangles = indices;  
    80.      
    81.      StartCoroutine( "Scan" );
    82.    }
    83.    
    84.    // Appelle la modification du mesh tous les freq secondes
    85.    IEnumerator Scan()
    86.    {
    87.      while (true) {
    88.        UpdateSightMesh ();
    89.        yield return new WaitForSeconds (freq);
    90.      }
    91.  
    92.    }
    93.  
    94.    void Update(){
    95.      this.gameObject.GetComponent<Rigidbody> ().velocity = new Vector3 (speed, speed, speed);
    96.      if (getTarget) {
    97.        agent.SetDestination(target.transform.position);
    98.      } else {
    99.        if (Vector3.Distance(this.gameObject.transform.position, destination[i]) < 0.5f){
    100.          i = (i+1)% destination.Count;
    101.        }else{
    102.          agent.SetDestination(destination[i]);
    103.        }
    104.      }
    105.    }
    106.  
    107.    // Fonction qui modifie le mesh
    108.    private void UpdateSightMesh()
    109.    {  
    110.      GameObject bestTarget = null;
    111.      float bestRange = 0;
    112.      // Lance les rayons pour placer les vertices le plus loin possible
    113.      for (int i = 0; i < precision; i++) {
    114.        Vector3 dir = m_Transform.TransformDirection (directions [i]); // repere objet
    115.        RaycastHit hit;
    116.        float dist = distance;
    117.        if (Physics.Raycast (m_Transform.position, dir, out hit, distance, mask)) { // Si on touche, on rétrécit le rayon
    118.          dist = hit.distance;
    119.          if (hit.transform.CompareTag ("Runner")){
    120.            if (hit.distance > bestRange)
    121.              bestTarget = hit.transform.gameObject;
    122.            hit.transform.gameObject.GetComponent<SeePlayer>().isSee = true;
    123.            Debug.Log("42");
    124.          }
    125.        }
    126.        if (debug)
    127.          Debug.DrawRay (m_Transform.position, dir * dist);
    128.      
    129.        // Positionnement du vertex
    130.        points [i] = m_Transform.position + dir * dist;
    131.        points [i + precision] = m_Transform.position;
    132.  
    133.        if (bestTarget != null) {
    134.          getTarget = true;
    135.          target = bestTarget;
    136.        } else {
    137.          getTarget = false;
    138.          target = null;
    139.        }
    140.      }
    141.      // On réaffecte les vertices
    142.      sightMesh.vertices = points;  
    143.      sightMesh.RecalculateNormals (); // normales doivent être calculé pour tout changement
    144.      // du tableau vertices, même si on travaille sur un plan
    145.    }
    146.  
    147.    void OnTriggerEnter(Collider other){
    148.      if (other.CompareTag("Runner")){
    149.        Destroy (other.gameObject);
    150.      }
    151.    }
    152.    
    153. }
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class SeePlayer : MonoBehaviour {
    5.  
    6.    public bool isSee = false;
    7.    public MeshRenderer mesh;
    8.  
    9.    void Update () {
    10.   mesh.enabled = isSee;
    11.    }
    12. }
    There script was respictively attach to an object, the IA and the ennemie.
    But, when an ennemy was in the AI FOV, the mesh doesn't activate. I've try to disable the first script, and then when a ennemy enter into the FOV, the become visible and doesn't desactivate, what's normaly suppose to do.
    If you can help me...

    Thank to suport my bad english, sorry i'm french!:D
     
  2. renman3000

    renman3000

    Joined:
    Nov 7, 2011
    Posts:
    6,683
    In your control script, to each frame, find each object tagged runner then get its component, seems such a waste of memory. You should learn to pool and cache.

    I am not sure why your FOV is not working as you would like. However, for an FOV, I would just use a trigger. On enter of required object, I would perform required task.

    Your approach seems very bloated.
     
  3. Namarand

    Namarand

    Joined:
    Aug 8, 2015
    Posts:
    2
    Thanks for you're quick answer.
    I'm a beginner, i will try to optimize this.

    And I've choose this approach because, with this, I got a graphical aspect of the FOV.