Hi,
I am new to Unity and I am currently writing a prototype for a game. My strategy so far was to use rather many scenes where each scene basically consists of a camera, a light, a player, enemies and several other prefabs. All of the mentioned prefabs consist of one or several scripts. Obviously, the enemies need to know the player’s position, or the camera’s position is changed when some other collision happens. In the latter case I use
myCamera = (Camera)FindObjectOfType(typeof(Camera));
and from here on transform myCamera the way I like.
This way, when I create a new level (i.e. new scene), I drag and drop my player prefab, the light prefab, enemy prefab etc. in the scene, position them, run the game and it works.
However, I was wondering whether this is more or less the way Unity is intended to work. Is this an efficient coding style? (More or less) exotic lines like the above seem necessary because I don’t want to drag and drop lots of relationships when I put my prefabs in my scene.
Curious about your responses.
IMO, that’s the way it should be done: Prefabbed/packaged in modules with very minimal extra setup.
However, if you’ll only have one camera in each scene as the Main Camera - it may be better to reference it as:
private var cameraTransform : Transform;
function Start() {
cameraTransform = Camera.main.transform;
}
and find the player by tag rather than by Object.
Thanks!
Yes, I thought there would be a more elegant way. Can you show me how to find the object by tag?
I’ve only used a tag attribute to check with whom I collide, like this:
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
myCamera.zDistance += increaseDistBy;
}
}
GameObject.FindGameObjectWithTag(“tagname”)
there is also GameObject.FindGamesObjectWithTag that returns many instead of one
You can Compare the tag in the Trigger method.
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("TheTag"))
{
myCamera.zDistance += increaseDistBy;
}
}
@markedagain: Thx, I tried it and it worked
@Vulegend: What is the difference between
if (other.tag == "Player")
and
if (other.gameObject.CompareTag("TheTag"))