Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 PsyanExists · Jul 12, 2021 at 07:01 PM · gameobjectreferencereferencinggameobject.findreferences

Weird problem with referencing game manager

I'm trying to reference my game manager script, but it's not working. Weird thing is, all I did was make something depend on a variable in the game manager, and both that thing and something else, unrelated, broke.

 

In my game, you get score by shooting objects that spawn that each have different random speeds. In the Target script (attached to the spawned objects), the speed of each object is determined by a method that returns a number from a random range. Then when it's shot, it tells a method in the Game Manager to update the score. It uses GetComponent to reach the game manager.

This all worked fine. until the fire nation attacked

I want to add different difficulties, so I made a difficulty variable in the game manager. I want the range used to determine speed to be different depending on the difficulty. So i replaced the one line that returns the speed with if statements that have different ranges depending on the difficulty. And THAT is when everything broke.

The if statements couldn't reference the difficulty variable from the Game Manager, even though it was able to reference a method from the GM just fine when it tells it to run the update score method. Not only that, but when I used the if statements in the random-speed method, the code that referenced the GM update-score method stopped working, even though it's in a completely different method! Both are fine syntax-wise, but when the game is running it shows the message "Null reference exception: Object reference not set to instance of an object", which makes me think it can't reference the GM for some reason.

Also, I've tried making a static variable in the GM and reference that to get the difficulty variable and use the update-score method, but then nothing works even without the new if statements, idk why.

The code shown here is only parts that are relevant, i removed other methods that arent related to the problem so it doesnt take up the whole screen. Full code here https://pastebin.com/DUZ51CgK

Ty in advance

relevant Target code:

     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;
     
     public class Target : MonoBehaviour
     {
         private Rigidbody2D targetRb;
         public GameObject player;
         public GameManager gameManager;
         public int pointValue;
         [SerializeField] private float minSpeed;
         [SerializeField] private float maxSpeed;
         [SerializeField] private float ySpawnPos = 11;
     
         public void Start()
         {
             gameManager = GameObject.Find("Game Manager").GetComponent<GameManager>();
         }
     
         public void Awake()
         {
             targetRb = GetComponent<Rigidbody2D>();
             transform.position = RandomSpawnPos();
             targetRb.AddForce((player.transform.position - transform.position) * RandomSpeed());
             targetRb.AddTorque(RandomTorque());
             Time.timeScale = 0.8f;
         }
     
         public void OnTriggerEnter2D(Collider2D other)
         {
             if(other.gameObject.CompareTag("Bullet"))
             {
                 Destroy(gameObject);
                 gameManager.UpdateScore(pointValue); //line that score error directs to
             }
         }
     
         float RandomSpeed()
         { 
             //code that works when there are no if statements, just 1 line:
             //return Random.Range(minSpeed, maxSpeed);
             //replacing that line with the following makes both this & score not work:
             if (gameManager.dif == 0) //easy; line that speed error directs to
               {
                   return Random.Range(minSpeed, maxSpeed);
               }
               else if (gameManager.dif == 1) //med
               {
                   return Random.Range(minSpeed, maxSpeed);
               }
               else //hard
               {
                   return Random.Range(minSpeed, maxSpeed);
               }
         }
     }

relevant GameManager code:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using TMPro;
 using UnityEngine.SceneManagement;
 using UnityEngine.UI;
 
 public class GameManager : MonoBehaviour
 {
     public bool isGameActive = true;
     private int score;
     public int lives;
     public int dif;
 
     IEnumerator SpawnTarget()
     {
         while (isGameActive)
         {
             spawnRate = RandomTime();
             yield return new WaitForSeconds(spawnRate);
             int index = Random.Range(0, targetPrefabs.Length);
             Instantiate(targetPrefabs[index]);
         }
     }
 
     public void UpdateScore(int scoreToAdd)
     {
         if(isGameActive)
         score += scoreToAdd;
         scoreText.text = "Score: " + score;
     }
 }

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 veyseler · Jul 13, 2021 at 06:56 AM

I created a new project with the code you have given. I had no issues on that RandomSpeed method. Can you provide your console output?

Comment
Add comment · Show 3 · 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 veyseler · Jul 13, 2021 at 07:52 AM 0
Share

Okay a wild guess but since you can directly access the player gameobject in the target class it is serialized in the Editor and since you gave reference to the target class i am also considering that your target prefabs are on the scene. Now another wild guess. I think one of the references you had in the array of target prefabs in GameManager is the original prefab. Not one of the correctly referenced prefabs in the screen. Can you make sure that every prefab in targetPrefabs array is actually in the scene?

avatar image PsyanExists veyseler · Jul 13, 2021 at 05:15 PM 0
Share

Would it be best if I could send you the whole project? I don't understand some of what you're saying lol

avatar image veyseler PsyanExists · Jul 14, 2021 at 06:17 AM 0
Share

yeah sure :)

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

185 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image 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

[Probably an easy question]Troubles saving my GameObject through scenes 1 Answer

Newly created scripts cannot be referenced 2 Answers

How to get a List of references of instances in a static variable 1 Answer

How do you reference different cameras 2 Answers

[UNSOLVED] Object reference not set to an instance of an object 0 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