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

Question Check if a script of another object is on? (C#)

Discussion in 'Scripting' started by ezequielbfocuus, Jun 7, 2022.

  1. ezequielbfocuus

    ezequielbfocuus

    Joined:
    Aug 17, 2020
    Posts:
    6
    Pretty simple but I dont know how to do it as im new to programming:

    We have Obj A and Obj B. I want Obj A to have a script that detects if a script in Obj B is on. Here is what I have so far (The following occurs on ScripOnA, in the Obj A:

    Code (CSharp):
    1. if(Vector3.Distance(ObjB.transform.position, transform.position) < 1.5f)
    2.     {
    3.       if(ObjB.ScriptOnB.enabled == true)
    4.       {
    5.         NotFollow.enabled = false;
    6.         YesFollow.enabled = true;
    7.        
    8.  
    9.         this.transform.SetParent(BParent.transform);
    10.  
    11.       }
    12.  
    13.     }
     
  2. ezequielbfocuus

    ezequielbfocuus

    Joined:
    Aug 17, 2020
    Posts:
    6
    The problem seems to be with line 3 as that doesnt exist but I dont know how it should be
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,954
    Referencing variables, fields, methods (anything non-static) in other script instances:

    https://forum.unity.com/threads/hel...-vars-in-another-script.1076825/#post-6944639

    https://forum.unity.com/threads/accessing-a-gameobject-in-different-scene.1103239/

    REMEMBER: it isn't always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.

    Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.

    That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.