Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Primex · Sep 06, 2015 at 02:07 PM · arrayfor-loopfinite-state-machine

Array or for loop doesn't work with state machine in Unity, gives NullReferenceException

The randomizeMonster function gives a NullReferenceException: Object reference not set to an instance of an object, when it's called from the state machine. randomizeMonster works if i call it from the start or update functions. I think i've tracked the problem to the AllMonsters array, but i don't know how to solve it.

Help is much appreciated :)

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
  
  
  
 public class BattleStateStart : MonoBehaviour {
  
         public string region; //current region
        
  
         public monster[] AllMonsters; //array for premade monsters
         public monster enemyMonster; //the generated enemy
         public monster monsterEquiped; //our monster
  
         // Use this for initialization
         void Start () {
                 Debug.Log(AllMonsters.Length);
                 randomizeMonster ();    //<<<<<<<< Calling randomizeMonster in update or start works, from boths classes
         }
        
         // Update is called once per frame
         void Update () {
                
  
         }
  
         public void PrepareBattle(){
                 Debug.Log ("Preparing for battle");            
                 randomizeMonster ();   
  
  
         }
         //The NullReferenceException: Object reference not set to an instance of an object is somehow caused by the
         //AllMonsters array. If i change AllMonsters.Length bellow to ex. 3 then it works but then the problem jumps to the next                       
         //place AllMonsters[] is used.
         void randomizeMonster(){
                 List<monster> tempMonster = new List<monster>();
                 int randomNumber = Random.Range(0,100);
                
                 if(randomNumber==20){
                         for(int i=0;i<AllMonsters.Length;i++){
                                 if(AllMonsters[i].rarity==monster.Rarity.Rare && AllMonsters[i].Location==region){
                                         tempMonster.Add(AllMonsters[i]);
                                 }
                         }
                 }else{
                         for(int j=0;j<AllMonsters.Length;j++){
                                 if(AllMonsters[j].rarity==monster.Rarity.Common && AllMonsters[j].Location==region){
                                         tempMonster.Add(AllMonsters[j]);
                                 }
                         }
                 }
                
                 int newRandom = Random.Range (0, tempMonster.Count);
                 enemyMonster = tempMonster [newRandom];
                
                
         }
         //Basic monster GUI
         void OnGUI(){
                 //Enemy monster
                 GUI.Label (new Rect (Screen.width / 2, 100, 200, 100), "" + enemyMonster.Name);
                 GUI.Label (new Rect (Screen.width / 2, 110, 200, 100), "HP " + enemyMonster.curHP + "/" + enemyMonster.baseHP);
                        
                 //Player monster
                 GUI.Label (new Rect (50, 100, 200, 100), "" + monsterEquiped.Name);
                 GUI.Label (new Rect (50, 110, 200, 100), "HP " + monsterEquiped.curHP + "/" + monsterEquiped.baseHP);
         }
  
  
 }
  

 using UnityEngine;
 using System.Collections;
  
 public class TurnBasedCombatStateMachine : MonoBehaviour {
  
         private BattleStateStart battleStateStartScript = new BattleStateStart();
  
         //The different states
         public enum Battlestates{      
                 START,
                 PLAYERCHOICE,
                 ENEMYCHOICE,
                 LOSE,
                 WIN,
                 CALCULATEDAMAGE,
                 ADDSTATUSEFFECTS
         }
  
         private Battlestates currentState;
  
  
  
  
         // Use this for initialization
         void Start () {
                 currentState = Battlestates.START;
  
         }
        
         // Update is called once per frame
         void Update () {
                 Debug.Log (currentState);
                 switch (currentState) {
                 case(Battlestates.START):
                         battleStateStartScript.PrepareBattle(); //<<<<< Calling randomizeMonster by calling PreparBattle
                                                                 //      doesn't work, gives
                                                                 //      NullReferenceException: Object reference
                                                                 //      not set to an instance of an object
                         break;
                 case(Battlestates.PLAYERCHOICE):
                         break;
                 case(Battlestates.ENEMYCHOICE):
                         break;
                 case(Battlestates.CALCULATEDAMAGE):
                         break;
                 case(Battlestates.ADDSTATUSEFFECTS):
                         break;
  
  
  
                 case(Battlestates.LOSE):
                         break;
                 case(Battlestates.WIN):
                         //Add XP
                         break;
                 }
         }
  
  
         //Change state button
         void OnGUI(){
                 if(GUILayout.Button("Next State")){
                         if(currentState==Battlestates.START){
                                 currentState=Battlestates.PLAYERCHOICE;
                         }else if(currentState==Battlestates.PLAYERCHOICE){
                                 currentState=Battlestates.ENEMYCHOICE;
                         }else if(currentState==Battlestates.ENEMYCHOICE){
                                 currentState=Battlestates.LOSE;
                         }else if(currentState==Battlestates.LOSE){
                                 currentState=Battlestates.WIN;
                         }else if(currentState==Battlestates.WIN){
                                 currentState=Battlestates.START;
                         }
                 }
  
         }
 }
  

Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image _Gkxd · Sep 06, 2015 at 02:11 PM 0
Share

You should check if anything is null by printing things out.

Right before the line that causes the errors, put this

 Debug.Log(All$$anonymous$$onsters);
 for (int i = 0; i < All$$anonymous$$onsters.Length; i++) {
     Debug.Log(All$$anonymous$$onsters[i]);
 }

Do the same thing for line 109:

 Debug.Log(battleStateStartScript);

If you see anything that is null, then that's the problem.

avatar image Primex · Sep 06, 2015 at 04:52 PM 0
Share

Thanks for the reply, I did as you said with the debug.log. I ran the script and called randomize$$anonymous$$onster once in start() and it works, the debug.log shows that the array isn't null. Then the state machine calls randomize$$anonymous$$onster and it reports that the array is null. It reports already in the for statement.

The gameobject with the scripts, shows that the public array isn't null either. How can it work from just update and start?

avatar image cjdev · Sep 06, 2015 at 07:01 PM 0
Share

Did you check battleStateStartScript? You're creating a component but not actually assigning it to a GameObject.

avatar image Cryptomane · Sep 06, 2015 at 07:18 PM 0
Share

Does the State$$anonymous$$achine have the correct reference to the class?

What is the line of that error?

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Primex · Sep 06, 2015 at 08:04 PM

Thanks cj and Crypto! The problem was: private BattleStateStart battleStateStartScript = new BattleStateStart(); Insted of calling the script i had put on my GO i created a new one, in which the array length was null.

Solved it by using GetComponent to find my script:D

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Cryptomane · Sep 06, 2015 at 08:35 PM 0
Share

$$anonymous$$ost welcome!

Thinking it back it was quite obvious, since the issue only occurred in the state machine

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

For In Loop Fills all values in arrays problem 2 Answers

for() loop skipping the first entry. Scripting error? 4 Answers

Array error, cannot convert float to float[] ???? 2 Answers

Error CS0029 Help? (Screenshot of Exact Error) 1 Answer

Arrays and For loops question 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges