0
votes

I am having problems accessing some components from others - this is mainly due to a failure to understand the Unity architecture. I was assuming that every time you 'name' a component, in effect you create a new C# type in the same way that a class definition does - but maybe not ... .

Note I am trying to hook all this up programatically for various reasons - I do not want to drag and drop in the editor, two reasons: (1) in some cases in practice this can only be done at runtime, and (2) I need to understand the architecture anyway.

My main player has a script attached, and in that I want to access a sub-component of the main player, being a camera. Called - for example - 'MyMainCamera'.

In Start() in the main player script I am doing this:

GameObject    tmp = GameObject.Find("MyMainCamera");

MyMainCamera  camera = tmp.GetComponent<MyMainCamera>();

//  do something with camera ....

(There's error checking code left out here). The problem is the compiler throws an error "The type or namespace name 'MyMainCamera' could not be found (are you missing a using directive ...?)". That is just an example, in other cases I need to access components that are not sub-components of the main player.

When I do the same thing with a Unity defined type like Text, Dropdown etc - presumably defined in 'using UnityEngine;' it all works fine.

Not clear how to do this therefore for a type that I define.

1

1 Answers

2
votes

Unfortunately, naming a gameobject in Unity doesn't create a new type.

So from my understanding you have a Camera component attached to a Player Gameobject that you are trying to get? In this case you should be trying to:

GameObject tmp = GameObject.Find("MyMainCamera");

Camera myMainCamera = tmp.GetComponent<Camera>();    

Where MyMainCamera should be the name of the GameObject containing the desired camera component.

Since the camera component class name is simply "Camera" and not MyMainCamera, what you can do is name your variable "MyMainCamera" if that helps, like I have in the code above.