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 13dnizinski · Dec 23, 2013 at 06:17 AM · gameobjectinstanceclasses

Why does my class script not recognize variables in its own instance?

Hello, I am making a game where multiple citizens will coexist in a city, so I need to be able to use multiple instances of the Citizen class at one time (By having multiple citizen mesh GameObjects where each citizen has this same script attatched to it). Whenever I have more than one citizen, the game does not recognize variables in the Update() section as belonging to that specific instance of the class. I am very new to c# and any help would be greatly appreciated.

This is my code so far:

public class Citizen : MonoBehaviour

{

 public string citizenName;
 public string gender;
 public int happiness;
 public int hunger;
 public int energy;
 public int social;

 public int speed;
 private List<Vector3> waypointList;
 private int waypointIndex;

 public void Start() {
     citizenName = generateName();
     gender = "male";
     happiness = 0;
     hunger = 0;
     energy = 0;
     social = 0;
     waypointIndex = 0;

     speed = 2;
     Debug.Log(citizenName);
     waypointList = findRoute(new Vector3(40,0,40), Block.blockGrid);
 }

 void Update() {
     if(waypointList.Count >= 0 && waypointIndex < waypointList.Count) {
         walkToDestination(waypointList[waypointIndex], ref waypointIndex);
         animation.CrossFade("Walk");
     } else {
         animation.CrossFade("Idle");
     }
     GetComponent<CharacterController>().Move((float)(speed * Time.deltaTime * (-1)) * transform.TransformDirection(Vector3.up));//FOR GRAVITY
 }
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 KellyThomas · Dec 23, 2013 at 06:24 AM 0
Share

Is findRoute(new Vector3(40,0,40), Block.blockGrid) returning a valid List for waypointList.

You can test this by adding this line to the end of Start():

 Debug.Log(waypointList);
avatar image 13dnizinski · Dec 23, 2013 at 06:30 AM 0
Share

Yes - every called function is returning what it claims. It completely works with one script attached to a GameObject, but when I have two GameObjects with one script on each one, only one GameObject actually is affected by the Update() function. It also throws an exception:

Object reference not set to an instance of an object Citizen.Update () (at Assets/Scripts/Citizen.cs:34)

Where line 34 is the line just after void Update()

avatar image KellyThomas · Dec 23, 2013 at 08:10 AM 0
Share

This is not the full script, we a missing at a $$anonymous$$imum findRoute() and walkToDestination(). It looks like the problem might be in the sections of code we don't have access to.

A null object error on that line would mean that waypointList is being set to null "somewhere". As it is a private variable it must be somewhere in this class.

I recommend doing a search through the file to exa$$anonymous$$e each line that refers to waypointList, it is likely one of them is causing the problem.

avatar image Owen-Reynolds · Dec 23, 2013 at 04:37 PM 0
Share

You never say what the problem is. Does only one person move?

"By having multiple ... GameObjects [with] same script": yes, this is the normal Unity way of doing things.

"does not recognize variables ... as belonging to that specific instance": That isn't the problem. Each citizen does have it's own vars. The only way to break that is by using static (which is rarely useful.) Try pausing and changing hunger in one citizen, to test.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by 13dnizinski · Dec 23, 2013 at 04:49 PM

using UnityEngine; using System.Collections; using System.Collections.Generic;

public class Citizen : MonoBehaviour

{

     public string citizenName;
     public string gender;
     public int happiness;
     public int hunger;
     public int energy;
     public int social;

     public int speed;
     private List<Vector3> waypointList;
     private int waypointIndex;

     public void Start() {
         citizenName = generateName();
         gender = "male";
         happiness = 0;
         hunger = 0;
         energy = 0;
         social = 0;
         waypointIndex = 0;

         speed = 2;
         Debug.Log(citizenName);
         waypointList = findRoute(new Vector3(40,0,40), Block.blockGrid);
     }

 void Update() {
     if(waypointList.Count >= 0 && waypointIndex < waypointList.Count) {
         walkToDestination(waypointList[waypointIndex], ref waypointIndex);
         animation.CrossFade("Walk");
     } else {
         animation.CrossFade("Idle");
     }
     GetComponent<CharacterController>().Move((float)(speed * Time.deltaTime * (-1)) * transform.TransformDirection(Vector3.up));//FOR GRAVITY
 }

 List<Vector3> findRoute(Vector3 destination, List<List<List<GameObject>>> blockList) {
     List<Vector3> newList = new List<Vector3>(); // The list of route coordinates
     Vector3 curPos = gameObject.transform.position;
     curPos.x = (int)Mathf.Floor( (float)((curPos.x/2)+.5f) );
     curPos.z = (int)Mathf.Floor( (float)((curPos.z/2)+.5f) );
     destination.x = (int)Mathf.Floor( (float)((destination.x/2)+.5f) );
     destination.z = (int)Mathf.Floor( (float)((destination.z/2)+.5f) );
     while((int)(curPos.x) != (int)(destination.x) || (int)(curPos.z) != (int)(destination.z)) {
         if(curPos.x < destination.x && blockList[(int)(curPos.x+1)][(int)(curPos.z)][1].name == "EmptyBlock") {
             curPos.x += 1;
         } else if(curPos.x > destination.x && blockList[(int)(curPos.x-1)][(int)(curPos.z)][1].name == "EmptyBlock") {
             curPos.x -= 1;
         } else if(curPos.z < destination.z && blockList[(int)(curPos.x)][(int)(curPos.z+1)][1].name == "EmptyBlock") {
             curPos.z += 1;
         } else if(curPos.z > destination.z && blockList[(int)(curPos.x)][(int)(curPos.z-1)][1].name == "EmptyBlock") {
             curPos.z -= 1;
         }
         blockList[(int)(curPos.x)][(int)(curPos.z)][1].name = "EmptyBlock1";
         Debug.Log(curPos.x + "  "+curPos.z);
         newList.Add(new Vector3(curPos.x, 0, curPos.z));
     }
     onesToZeros2D(blockList);
     return newList;
 }

 public void onesToZeros2D(List<List<List<GameObject>>> blockList) {//Turns all the ones in the list to default values
     for(int r = 0; r < blockList.Count; r++) {
         for(int c = 0; c < blockList[r].Count; c++) {
             if(blockList[r][c][1].name == "EmptyBlock1") {
                 blockList[r][c][1].name = "EmptyBlock";
             }
         }
     }
 }
 
 void walkToDestination(Vector3 destination, ref int waypointIndex) {//To be called in Update()
     CharacterController citizenController = GetComponent<CharacterController>();
     int x = (int)(destination.x * 2);
     int z = (int)(destination.z * 2);

     Vector3 vertical = transform.TransformDirection(Vector3.forward);
     Vector3 height = transform.TransformDirection(Vector3.up);

     if(Mathf.Floor(transform.position.x) < x) {
         transform.rotation = Quaternion.Euler(0,90,0);
         citizenController.Move((float)(speed * Time.deltaTime) * vertical);
     } else if(Mathf.Floor(transform.position.x) > x) {
         transform.rotation = Quaternion.Euler(0,270,0);
         citizenController.Move((float)(speed * Time.deltaTime) * vertical);
     } else if(Mathf.Floor(transform.position.z) < z) {
         transform.rotation = Quaternion.Euler(0,0,0);
         citizenController.Move((float)(speed * Time.deltaTime) * vertical);
     } else if(Mathf.Floor(transform.position.z) > z) {
         transform.rotation = Quaternion.Euler(0,180,0);
         citizenController.Move((float)(speed * Time.deltaTime) * vertical);
     } else {
         waypointIndex++;
     }
 }


 public string generateName() { // Generates a random name
     List<string> firstNames = new List<string>();
     List<string> lastNames = new List<string>();
     int firstIndex;
     int lastIndex;

     firstNames.Add("Milford");
     firstNames.Add("Leroy");
     firstNames.Add("Morpheus");
     firstNames.Add("Elroy");
     firstNames.Add("Fynn");

     lastNames.Add("Cubicle");
     lastNames.Add("Cumberbatch");
     lastNames.Add("Blocksickle");
     lastNames.Add("DooLittle");
     lastNames.Add("Dumas");

     firstIndex = Random.Range(0, firstNames.Count);
     lastIndex = Random.Range(0, lastNames.Count);

     return firstNames[firstIndex]+" "+lastNames[lastIndex];
 }

}

Comment
Add comment · Show 2 · 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 13dnizinski · Dec 23, 2013 at 03:50 PM 0
Share

This is the entire script. I don't think the problem is that one of the functions isn't returning the right value. Everything works fine, except when another GameObject with the same script is in the scene. It appears to be triggering exceptions for all the class variables being used inside the Update() function - not just one of them. I am getting a whole slew of exceptions - one for each of the class variables that appear in lines 0 to 10 above. Each time any of those variables appear in my Update() function, some kind of exception is thrown. The strange thing is that this only happens when I have multiple GameObjects using this same script.

And by the way, I just want to say thank you for trying to help. :)

avatar image 13dnizinski · Dec 23, 2013 at 03:58 PM 0
Share

Wow! You were so right! It DID have to do with what findRoute() returned! Thank you so much! Oh-and $$anonymous$$erry Christmas! And Happy Chanukah! And $$anonymous$$wanza! Oh - I'm so happy! Thank you so much!

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

20 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

Related Questions

How to access an instance of a class when the class isn't known 2 Answers

How to add items (or players) to the scene from classes? 1 Answer

Add an instance of a script as a component? 1 Answer

Fade 2 out of 3 gameobjects on the screen who have the same material 2 Answers

What is an instance of a GameObject? 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