Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 Nivius@School · Apr 15, 2013 at 03:06 PM · c#gameobjectgetcomponentdontdestroyonload

How to run a function in a GO that have DontDestroyOnLoad

The code i am using following

using UnityEngine; using System.Collections; public class CollisonWin : MonoBehaviour { GameObject goMAINMENU; public MainMenu MM; void OnTriggerEnter(Collider collision) { if (collision.gameObject.tag == "Player") { goMAINMENU = GameObject.Find("ScoreSystemCube"); MM = goMAINMENU.gameObject.GetComponent(); MM.SaveScore(); Debug.Log("Winning!"); Application.LoadLevel("2DKemi_Level2"); } } }

SaveScore

 using UnityEngine;
 using System.Collections;
 
 public class ScoreSystem : MonoBehaviour {
     public int score;
     public GUISkin Scoreskin;
     public bool saveScoreSetting;
 
     GameObject goMAINMENU;
     public MainMenu MM;
 
     public void ToggleScore()
     {
 
         goMAINMENU = GameObject.Find("ScoreSystemCube");
         MM = goMAINMENU.gameObject.GetComponent<MainMenu>();
 
         saveScoreSetting = MM.WhatModeIsIt();
 
         if (Application.loadedLevelName == "2DKemi_Level1")
         {
             
             
             if (saveScoreSetting == true)
             {
                 //ADD points 
                 score = 0;
             }
             if (saveScoreSetting == false)
             {
                 //LOSE points
                 score = 500;
             }
         }
         if (Application.loadedLevelName == "2DKemi_Level2")
         {
             if (saveScoreSetting == true)
             {
                 //ADD points
                 score = 0;
             }
             if (saveScoreSetting == false)
             {
                 //LOSE points
                 score = 1000;
             }
 
         }
 
     }
 
 
     public void AdjustScore(int adj)
     {
         if (saveScoreSetting == true)
         {
             if (adj < 0)//om minus poäng, sätt till 0;
             {
                 adj = 0;
             }
         }
         if (saveScoreSetting == false)
         {
             if (adj > 0)//om plus poäng, sätt till 0;
             {
                 adj = 0;
             }
         }
 
         if (score < 0)
         {
             score = 0;
         }
         else
         {
             score = score + adj;
         }
     }
 
     void OnGUI()
     {
         float InfoBoxWidth = (Screen.width * 0.15f);
         float InfoBoxheight = (Screen.height * 0.10f);
         float scoreBarLengthLock = (Screen.width / 4);
 
 
         GUI.skin = Scoreskin;
 
 
         GUI.Box(new Rect(Screen.width - (scoreBarLengthLock + 10), Screen.height - 32, (InfoBoxWidth*1.8f), InfoBoxheight), " ");
         GUI.Box(new Rect(Screen.width - (scoreBarLengthLock + 10), Screen.height - 32, (InfoBoxWidth*1.8f), InfoBoxheight), "Poäng: " + score);
 
 
 
         
 
     }
 
     void Start () {
         ToggleScore(); // CHANGES SCORE SYSTEM TO POSITIVE OR NEGATIVE
     }
     
     // Update is called once per frame
     void Update () {
         if (score < 0)
         {
             score = 0;
         }
     }
 }

MainMenu

 using UnityEngine;
 using System.Collections;
 
 public class MainMenu : MonoBehaviour {
 
     GameObject goPLAYER;
 
     public bool ChoosenMode;
 
     public int[] SavedScore = new int[10]; //totalpoäng i 0, poäng för bana 1 i 1, bana 2 i 2 osv.
 
     public GUISkin Scoreskin;
     public ScoreSystem SS;
 
     float InfoBoxwidth = (Screen.width * 0.15f);
     float InfoBoxheight = (Screen.height * 0.10f);
 
     float scoreBarLengthLock = (Screen.width / 4);
     
     void OnGUI()
     {
         if (Application.loadedLevelName == "Start_Menu")
         {
             GUI.skin = Scoreskin;
             if (GUI.Button(new Rect(((Screen.width / 2) - (InfoBoxwidth + 10)), ((Screen.height / 2) - (InfoBoxheight / 2)), InfoBoxwidth, InfoBoxheight), "+"))
             {
                 ChoosenModeFunction(true);
                 Application.LoadLevel("2DKemi_Level1");
 
             }
             if (GUI.Button(new Rect(((Screen.width / 2) + 10), ((Screen.height / 2) - (InfoBoxheight / 2)), InfoBoxwidth, InfoBoxheight), "-"))
             {
                 ChoosenModeFunction(false);
                 Application.LoadLevel("2DKemi_Level1");
             }
 
         }
     }
 
 
     void ChoosenModeFunction(bool Choosen_feedback)
     {
         ChoosenMode = Choosen_feedback;
         print("THE CHOSEN MODE IS: " + ChoosenMode);
     }
 
     public bool WhatModeIsIt()
     {
         return (ChoosenMode);
     }
 
     public void SaveScore()
     {
         int scoreToSave;
         scoreToSave = SS.score;
         if (Application.loadedLevelName == "2DKemi_Level1")
         {
             SavedScore[1] = scoreToSave;
             SavedScore[0] = SavedScore[0] + scoreToSave;
             print("PLAYER GOT THIS SCORE LAST MAP: " + scoreToSave);
         }
 
         if (Application.loadedLevelName == "2DKemi_Level2")
         {
             SavedScore[2] = scoreToSave;
             SavedScore[0] = SavedScore[0] + scoreToSave;
             print("PLAYER GOT THIS SCORE LAST MAP: " + scoreToSave);
         }
     }
 
     void awake()
     {
 
         //DontDestroyOnLoad(this);
         DontDestroyOnLoad(transform.gameObject);
         goPLAYER = GameObject.Find("First Person Controller");
         SS = goPLAYER.gameObject.GetComponent<ScoreSystem>();
         SS.ToggleScore();
 
         print("THE CHOSEN MODE IS: " + ChoosenMode);
 
     }
     
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
     
     }
 }


This is seposed to findout when the player collide whit this objektive to make it a "goal" and then load the next map.

but before this i have had a simple script in the start that chooses if the game will use positive or negative feedback. this is then stored in that GO.

in the same file i have a "save score" kind of function that saves the games score to an array

Error: NullReferenceException: Object reference not set to an instance of an object MainMenu.SaveScore () (at Assets/Standard Assets/Scripts/Scripts/MainMenu.cs:55) CollisonWin.OnTriggerEnter (UnityEngine.Collider collision) (at Assets/Standard Assets/Scripts/Scripts/CollisonWin.cs:26)

as the go does not show up, but its still active, it reconnaissances it as null

PS: c# please :)

Comment
Add comment
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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Yokimato · Apr 15, 2013 at 03:11 PM

 MM = goMAINMENU.gameObject.GetComponent<MainMenu>();

From what you posted, your GetComponent call is missing the type parameters.

However, From your error message, your function SaveScore is throwing the exception, and there is a null reference somewhere in it. Since the code for that is not posted, this is as much help as one can give.


So now that we have the code, let's find where the issue could be happening.

  public void SaveScore()
     {
        int scoreToSave;
        scoreToSave = SS.score; // <--- #1
        if (Application.loadedLevelName == "2DKemi_Level1")
        {
          SavedScore[1] = scoreToSave;
          SavedScore[0] = SavedScore[0] + scoreToSave; // #2
          print("PLAYER GOT THIS SCORE LAST MAP: " + scoreToSave);
        }
  
        if (Application.loadedLevelName == "2DKemi_Level2")
        {
          SavedScore[2] = scoreToSave;
          SavedScore[0] = SavedScore[0] + scoreToSave; // #3
          print("PLAYER GOT THIS SCORE LAST MAP: " + scoreToSave);
        }
     }

Above is 3 spots where you could be getting your error from. #1, if the variable SS is null. Otherwise, for 2 and 3, if SaveScore[0] is null, then concatenation on a null value would also trigger a NullReferenceException. Check these spots and you'll find your answer

Comment
Add comment · Show 7 · 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 Nivius@School · Apr 15, 2013 at 03:22 PM 0
Share

i have that, it was removed for some reason while writing the question :/ anything whithin those $$anonymous$$ORE_THEN and LESS_THEN don't show

avatar image Yokimato · Apr 15, 2013 at 03:50 PM 0
Share

Did you see my second part though, you error happens in the SaveScore function...you'd need to post that functions code for me to help further.

avatar image Nivius@School · Apr 15, 2013 at 04:13 PM 0
Share

added that also, beware, its not good looking code

avatar image Yokimato · Apr 15, 2013 at 05:15 PM 0
Share

You added ScoreSystem.cs, but you're calling the SaveScore function on the $$anonymous$$ain$$anonymous$$enu class, so I'd need that code.

avatar image Nivius@School · Apr 15, 2013 at 05:41 PM 0
Share

sry <3 adding it

Show more comments

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

12 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Don't Destroy on Load Object and GameData 1 Answer

get script of another gameobject in c# 1 Answer

Don't Destroy on Load not working for me 1 Answer

How to get a variable value from another script(C#)? 1 Answer

Creating a single-line function for GameObject.Find and GetComponent (for multiple components) 3 Answers


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