An overview of objects in c# - need help with references

I’m about a third of the way through my first unity project and I’m starting to implement some of the more complex functionality.

I’m having a real problem understanding either the syntax or the workflow of dynamically creating objects via c# script, and then later referencing them.

I’ve resorted to using a singleton pattern for shared objects but even with defensive coding I feel like it’s devolving into spaghetti with no real encapsulation.

What I’d like to understand is the best way to instance an unattached prefab and then call the scripts it contains.

My efforts have resulted in a large body of null reference errors.

I don’t mind researching for myself, but if anyone could point to a decent tutorial that covers this subject in detail I’d appreciate it. Really anything that covers structuring a unity program such that it doesn’t become too top-heavy and become difficult to extend.

Thanks.

You may need to explain your situation a bit more. What/why are you referencing.

I have a manager class (can be singleton or monobehaviour) with a List (search MSDN if you don’t know what that is) of an object.
When an object gets added, in its Start function it adds itself to the Manager’s list, and when its destroyed it removes itself.

Object could be the GameObject to reference, or an individual script within if needed.

Another way to add them to the list is when your instantiating them.

GameObject obj = Instantiate (Resources.Load ("Baddie")); as GameObject  // You mentioned unreferenced prefabs, so I threw that in there
manager.Add (obj);

When you use instantiate it return a reference to the object created. The first solution is to assign variables at this point.

Another way is to name or tag your objects when you instantiate them and then use functions like GameObject.Find() or GameObject.FindWithTag(). There is also a function that returns all gameobjects with the specified tag in an array.

I’ve also found that the ObjectPool system (available for free on the forums somewhere) is a very good way to pre instantiate and reuse objects at run time. The usage is pretty much identical to using instantiate and destroy.

But as DMan said we need to know what you’re doing to help you in the best way.

Guys, I re-hit the documentation and got it figured out. I’m still learning that some of the functionality lies inside some of the inner classes, so while gameObject can’t do a foreach, gameObject.transform can. Thank you for the help.

A related question, Is Resources.Load() going to parse every folder in my project or do I have to qualify the subfolder? For example (“/prefabs/myprefab”); ?