Using " if " Statement from Different Scripts

Hi! Can I use and connect " if " statements from different scripts? For example;

//ScriptOne
        if (hit.transform.gameObject.tag == "Enemy")
        {            
            Destroy(hit.transform.gameObject);
        }
     
//ScriptTwo
        if (thisList == enemylist)
        {
            Debug.Log("Enemy");
        }
//ScriptOne or ScriptTwo (and what I ask)
        if (thisList == enemylist && hit.transform.gameObject.tag == "Enemy")
       {
            Destroy(hit.transform.gameObject);
            Debug.Log("Enemy");  
        }

Thank you very much for any help.

1 Like

Yes you can. You should store both ifs into a variable in each script locally and then access that variable through the thrid script using GetComponent<>().

Inside first script:

public bool condition1;
//stuff to do
condition1 = hit.transform.gemObject.tag == "Enemy";

Inside second script:

public bool condition2;
//stuff to do
condition2 = thisList == enemylist;

combined:

script1 s1 = gameObject.GetComponent<script1>();
script2 s2 = gameObject.GetComponent<script2>();
if(s1.condition1 && s2.condition2)
//do your thing

Keep in mind that you need public variables and public functions if you want to access them from another script.

1 Like

Thank you very much!!! I will try!!!

@AlmantusK Thank you very much for solution. It work perfect. But now, I have another problem :smile: How can I hide/show an object from list? Here;

ScriptOne s1 = gameObject.GetComponent<ScriptOne>();
            if(s1.conditionList1 != null)
            {
                if (hit.transform.gameObject.tag == "Apple" || hit.transform.gameObject.tag == "Car" || hit.transform.gameObject.tag == "Flower")  //Apple,car and flower just for example
            {
                    GameObject[] list1;
                    list1 = GameObject.FindWithTag("Apple").SetActive(false); //ofcourse its not working. This line give me " CS0029: Cannot implicitly convert type `void' to `UnityEngine.GameObject[]' " error.
                    
         }
}
list1 = GameObject.FindWithTag("Apple");
Foreach(GameObject oneApple in list1)
{
oneApple.SetActive(false);
}
1 Like

FindWithTag returns a single object…

2 Likes

GameObject.FindGameObjectsWithTag(“Apple”);
That’s better no ?

2 Likes

that would stop the conversion error, yes :slight_smile:

1 Like

@CrymX and @LeftyRighty thank you very much guys!! You are perfect! But :smile: I have another problem. I can’t figure out. I try everythnk.

ScriptOne s1 = gameObject.GetComponent<ScriptOne>();
            if(s1.conditionList1) // This line give me this error: "NullReferenceException: Object reference not set to an instance of an object"
            {
                if (hit.transform.gameObject.tag == "Apple")
            {
                    GameObject[] list1;
                    list1 = GameObject.FindGameObjectsWithTag("Apple");
                    foreach(GameObject oneApple in list1)
                    {
                        oneApple.SetActive(false);
                    }
                 
                gameController.AddScore (scoreValue);
                Destroy (hit.transform.gameObject);
            }

you are welcome.

i think the problem is : your gameObject don’t have component “ScriptOne”.

so there’s no reference to the propertie conditionList1 because s1 is null.

Thank you for fast reply and sorry for my inexperience. If its possible can you explane little more?Or with an example?

your gameObject have some component (like a rigidbody, a script, a meshRenderer). If your gameObject don’t have the component ScriptOne, GetComponent return null.
So you can drag and drop your script into your GameObject or Add the componenent ScriptOne at runtime like this :

void Start()
{
this.gameObject.AddComponent<ScriptOne>();
}
ScriptOne s1 = gameObject.GetComponent<ScriptOne>();

this requires a “ScriptOne” component to be on the same gameobject as this script… if there isn’t one, s1 is null. You then try to access a property of s1 which causes the error.

Thank you guys @LeftyRighty and @CrymX but I used @CrymX 's code

and now I get another error :confused: I think I can’t fix it.

//ScriptOne
...
void UpdateScore ()
    {
        scoreText.text = "Score: " + score;  // this line. " NullReferenceException: Object reference not set to an instance of an object
    }
}

I hate " NullReferenceException " errors -_-

Can you show us the full code of ScriptOne ?

Of course;
ScriptOne = GameController

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using System.Linq;


public class GameController : MonoBehaviour
{

    public Camera cam;
    public GameObject[] letters;
    public GUIText scoreText;
    private int score;
    public GameObject splashScreen;
    public GameObject startButton;

  


    public GameObject[] list1;
    public GameObject[] list2;
    public GameObject[] list3;


    private float maxWidth;

    void Start()
    {
        score = 0;
        UpdateScore();

        if (cam == null)
        {
            cam = Camera.main;
        }
        Vector3 upperCorner = new Vector3(Screen.width, Screen.height, 0.0f);
        Vector3 targetWidth = cam.ScreenToWorldPoint(upperCorner);
        float letterWidth = letters[0].GetComponent<Renderer>().bounds.extents.x;
        maxWidth = targetWidth.x - letterWidth;

    }

    public void StartGame()
    {
        splashScreen.SetActive(false);
        startButton.SetActive(false);
        StartCoroutine(Spawn());
  
        int rand = Random.Range(1, 3); //Note that the top end of Random.Range is non-inclusive


        if (rand == 1) ShowOnScreen(list1);
        if (rand == 2) ShowOnScreen(list2);
        if (rand == 3) ShowOnScreen(list3);

    }

    public Vector3 startPoint = new Vector3(0, 0, 0);
    public Vector3 endPoint = new Vector3(5, 0, 0);

    public bool conditionList1;
    public bool conditionList2;
    public bool conditionList3;
    public void ShowOnScreen(GameObject[] thisList)
      
    {
      
        for (int i = 0; i < thisList.Length; i++) {
            Instantiate (thisList[i], Vector3.Lerp (startPoint, endPoint, (float)i / (thisList.Length - 1)), Quaternion.identity);
        }
        if (thisList == list1)
            conditionList1 = thisList == list1;
        {
            Debug.Log("list1");
        }
        if (thisList == list2)
            conditionList2 = thisList == list2;
        {
            Debug.Log("list2");
        }


    }
  
    IEnumerator Spawn()
    {
        yield return new WaitForSeconds(0.0f);
        while (true)
        {
            GameObject letter = letters[Random.Range(0, letters.Length)];
            Vector3 spawnPosition = new Vector3(
                Random.Range(-maxWidth, maxWidth),
                transform.position.y,
                0.0f
                );
            Quaternion spawnRotation = Quaternion.identity;
            Instantiate(letter, spawnPosition, spawnRotation);
            yield return new WaitForSeconds(Random.Range(0.0f, 1.0f));
        }
    }

    public void AddScore (int newScoreValue)
    {
        score += newScoreValue;
        UpdateScore();
    }

    void UpdateScore ()
    {
        scoreText.text = "Score: " + score;
    }
}

I suppose you have attached the component GUIText via the inspector. Are you sure the GUIText exist in your scene when updateScore is called ?

guitext is from the legacy ui system… might want to use the new UI system Learn game development w/ Unity | Courses & tutorials in game design, VR, AR, & Real-time 3D | Unity Learn

1 Like

Thanks for suggestion @LeftyRighty :slight_smile: @CrymX If I delete this;

void Start()
    {
        this.gameObject.AddComponent<GameController>();
    }

and do this;

if (s1.conditionList1 != null)

My other scripts works fine and I don’t get Null error but this line/code doesn’t work;

GameController s1 = gameObject.GetComponent<GameController>();
            if (s1.conditionList1 != null) // Alert(In Visual Studio): The result of the expression is always true since a value of type 'bool' is never equal to 'null' of type 'bool?'  Alert(In Unity): The result of comparing value type `GameController.conditionList1' with null is `true'

Its don’t give me error but its not work. @CrymX and yes. GUIText attached to component via the inspector.