Sunday, February 11, 2018

c# - Trying to better understand Unity gameobjects


New to Unity, but develop in C# normally. I can't seem to get how / why / where to grab certain elements. For simplicity, I have a top-level game object, say a cube. I add a sphere to the scene as child to the cube. The child sphere (actually more complex), has navigation mesh, animation object, collider and finally a script in C#.



Now, my C# class is comprised of an instance of an C# class on the class. Something like


public class CMyGeneric
{
public void someMethod()
{
// invalid getting to "gameObject" reference
}
}



public class CMyMainScript
{
public CMyGeneric myGeneric;

void Start()
{
myGeneric = new CMyGeneric();
}

void Update()

{
myGeneric.someMethod();
}
}

So, the parent game object is the cube, the child is the sphere, and the CMyMainScript script is attached to the sphere. However, when I try to reference "gameObject" via the CMyGeneric (instance), call within the "someMethod", the "someMethod" doesn't appear to see the overall "gameObject".


Now, how/what am I missing as each thing that gets attached, unity adds to these game objects, and I don't know how to get respective hierarchical levels of where things are even though I know where they are from a relative perspective.



Answer



I assume you've left out some code? Like that CMyMainScript and CMyGeneric extends MonoBehaviour? Are you expecting to be able to access gameObject inside your CMyGeneric class because you'd instantiated it inside another class?


If you want to access gameObject you need to attach that script to a game object by using this.gameObject.AddComponent(). This returns the reference to CMyGeneric that you'd want to use, and will have the gameObject reference properly set.



However, if you're attaching CMyGeneric as a script you may as well call someMethod inside of the CMyGeneric Update() method.


Alternatively, if you're not making CMyGeneric into a script to be attached, and you want CMyGeneric to act on a gameObject, just pass the game object into the someMethod call.


public void someMethod(GameObject gameObject)
{
// valid "gameObject" reference
}

And:


void Update()
{

myGeneric.someMethod(this.gameObject);
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...