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

Why isn't my code working

Discussion in 'Scripting' started by masterlewis05, Jan 31, 2016.

  1. masterlewis05

    masterlewis05

    Joined:
    Jan 16, 2016
    Posts:
    8
    This is a segment of my code but it doesn't seem to work:

    if (combatthings == null)
    combatthings = GameObject.FindGameObjectsWithTag("combat");

    foreach (GameObject combats in combatthings)
    {
    combat comScript = combats.GetComponent<combat>();
    comScript.attack = false;
    }

    it is meant to find all objects with the tag "combat" and find a script called combat and then set attack to false in the script
     
  2. Craig8726

    Craig8726

    Joined:
    Jul 5, 2013
    Posts:
    79
    maybe combatThings != null.
    add
    else
    {
    debug.log(combatThings != null)
    }
    to the if statement to check.
     
  3. The-Little-Guy

    The-Little-Guy

    Joined:
    Aug 1, 2012
    Posts:
    297
    maybe this is still null? did you test and see what it contains?

    Code (CSharp):
    1. combatthings = GameObject.FindGameObjectsWithTag("combat");
     
  4. masterlewis05

    masterlewis05

    Joined:
    Jan 16, 2016
    Posts:
    8
    i just tried that but it printed true so the top part of the code isnt the issue
     
  5. RecursiveRuby

    RecursiveRuby

    Joined:
    Jun 5, 2013
    Posts:
    163
    What happens when you do this.

    Code (CSharp):
    1. foreach (GameObject combats in combatthings)
    2. {
    3. combat comScript = combats.GetComponent<combat>();
    4. if(combat == null){
    5. Debug.LogError("No combat script was found on gameobject " + combats.name);
    6. }else{
    7. comScript.attack = false;
    8. }
    9. }