• 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
Question by kevinseligmann · Nov 21, 2012 at 04:57 AM · c#variableclassclassesinherit

Access to a variable inside a C# class

Hello everybody,

I'm having trouble accesing a variable inherited from a class.

This is my class:

 using UnityEngine;
     using System.Collections;
     
     public class RecetaInitializer : MonoBehaviour {
     
         public RecetaConstructor[] Receta;
     
         void Start () {
             Receta = new RecetaConstructor[9];
     
             for (int i = 0; i < Receta.Length; i++)
             {
                 Receta[i] = new RecetaConstructor();
             }
     
             Receta[0].AddReceta(1, "Huevo Duro", "agua,huevo");
             Receta[1].AddReceta(2, "Papas Fritas", "papa,aceite");
             Receta[2].AddReceta(3, "Omelette", "huevo,queso,jamon");
             Receta[3].AddReceta(4, "Licuado De Banana", "leche,banana");
             Receta[4].AddReceta(5, "Chocolatada", "leche,chocolate");
             Receta[5].AddReceta(6, "Fideos Con Queso", "fideos,queso");
             Receta[6].AddReceta(7, "Pancho", "pan,salchicha,queso");
             Receta[7].AddReceta(8, "Pizza", "pan,queso,jamon,tomate");
             Receta[8].AddReceta(9, "Hamburguesa", "pan,paty,queso,lechuga,tomate");    
             // Debug.Log(Receta[7].GetRecetaName());
         }
         
     }

Now, I want to access from another script the variable Receta. To achieve this I created another class that I use to manage my game:

 using UnityEngine;
 using System.Collections;
 
 public class MenuGUI : RecetaInitializer{
 
     public RecetaConstructor[] Receta;
     // RecetaConstructor is a class I have which works fine, it lets me create different recipes for my game.
     
     
     void Start()
     {
         Receta = gameObject.GetComponent<RecetaInitializer>().Receta;
         PrepareGame();
     }
     
     private void PrepareGame()
     {
         Debug.Log(Receta[0].GetRecetaName());
         // GetRecetaName() is self-explanatory, given the index it returns the name of the Recipe/Receta
     }
 
 }

I'm clearly missing something here, ad Unity gives me a nice "Object reference not set to an instance of an object".

I also tried by not inheriting the class and add it with AddComponent and then RecetaConstructor[] Receta = gameObject.GetComponent().Receta; But the result is the same.

Any hint? Thanks very much!

Comment

People who like this

0 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 MarkFinn · Nov 21, 2012 at 06:23 AM 0
Share

gameObject.GetComponent()

will be null unless there is a RecetaInitializer on the object. It will not pick up a child class of RecetaInitializer.

I'm not sure this is causing your problem. But as you didn't say what line the error was occurring on it's my best guess.

avatar image kevinseligmann · Nov 21, 2012 at 06:25 AM 0
Share

Sorry, the line was 'Debug.Log(Receta[0].GetRecetaName());'.

And I added the component through the inspector to the same GameObject that has this script, so it shouldn't be null.

avatar image MarkFinn · Nov 21, 2012 at 06:40 AM 0
Share

Is the script attached to the gameobject RecetaInitializer or MenuGUI ?

if it's MenuGUI then the line

Receta = gameObject.GetComponent().Receta;
won't find anything.
avatar image kevinseligmann · Nov 21, 2012 at 06:43 AM 0
Share

Both RecetaInitializer.cs and MenuGUI.cs are attached to the same camera. That's pretty much the scene. And the class RecetaConstructor (which seems to work fine) is not attached to anything as I didn't inherited MonoBehaviour on it, I just made it public.

2 Replies

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by MarkFinn · Nov 21, 2012 at 06:45 AM

Ok, just remove the line

 Receta = new RecetaConstructor[9]; 

from the start method in RecetaInitializer.

and replace

 public RecetaConstructor[] Receta;

with

 public RecetaConstructor[] Receta = new RecetaConstructor[9];

That line has been blanking your preset data each time.

And make sure to rename your Start() in RecetaInitializer to Awake().

Comment
kevinseligmann

People who like this

1 Show 5 · 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 MarkFinn · Nov 21, 2012 at 06:48 AM 0
Share

Just to add, unless there's more to the classes than you are showing us then the inheritance is really unnecessary and, frankly, only going to cause confusion.

avatar image kevinseligmann · Nov 21, 2012 at 06:52 AM 0
Share

It's working perfeclty now @markfinn , thank you very much. I still don't understand exactly what the problem was, but I'm looking forward to learn more of it as this was my first attemp at classes.

Also, there's not a lot more that this, I just thought that classes where the way to go on something like this, as I wanted to store data and using 3 different arrays seemed a little odd at the time.

avatar image nicloay · Nov 21, 2012 at 06:57 AM 1
Share

in your first listing problem was that you overrided the method Start(), and didn't call this metod from your derrived class if you want to fix your previous code in MenuGUI class in metod Start at first call base.Start(), so only after that it will cal your Start function of your base class.

avatar image kevinseligmann · Nov 21, 2012 at 06:59 AM 0
Share

thank you very much guys, it's way clearer now

avatar image MarkFinn · Nov 21, 2012 at 07:09 AM 1
Share

One thing to note. The actual problem here was that when two classes on the same object depend on eachother's Start() functions the data will not be set. Start() is done before the first time Update() is run.

If one monobehaviour has data that another will use, make sure that data is done in Awake().

avatar image

Answer by nicloay · Nov 21, 2012 at 06:34 AM

why do you need to initialize data in Start() looks like you data is hardcoded and static, so just use static initialization

 using UnityEngine;
 using System.Collections;
 
 public class RecetaInitializer : MonoBehaviour {
 
 public static RecetaConstructor[] Receta = new RecetaConstructor[9]{
     new Receta(1, "Huevo Duro", "agua,huevo"),
 new Receta(2, "Papas Fritas", "papa,aceite"),
 new Receta(3, "Omelette", "huevo,queso,jamon"),
 new Receta(4, "Licuado De Banana", "leche,banana"),
 new Receta(5, "Chocolatada", "leche,chocolate"),
 new Receta(6, "Fideos Con Queso", "fideos,queso"),
 new Receta(7, "Pancho", "pan,salchicha,queso"),
 new Receta(8, "Pizza", "pan,queso,jamon,tomate"),
 new Receta(9, "Hamburguesa", "pan,paty,queso,lechuga,tomate")
 };
         
 }


or, if you don't like it, make use getter and setter and in getter just check if you private array=null initialize them.

Comment

People who like this

0 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 kevinseligmann · Nov 21, 2012 at 06:38 AM 0
Share

Thanks Nikolay, that's definetely a better way of doing it and you're correct that my data is indeed static.

But the problem I have is still happening, whenever I try to access the Receta variable I get a null reference and I really don't know why.

avatar image nicloay · Nov 21, 2012 at 06:50 AM 0
Share

sorry, mixed up a right part of archive initialization, already fixed in the code, must be public static RecetaConstructor[] Receta = new RecetaConstructor[9]{

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

11 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

Related Questions

Can I choose what to pass into .getcomponent<{VARIABLE}>(); 1 Answer

object assigns but does not show when added to list, or any other var 0 Answers

Unity C# Start function without extending Mono 2 Answers

Accessing a variable inside a class inside other script... 2 Answers

How to bind different type of data in an array ? 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