Using a string reference?

This is the advanced Unity C# coding course… And we’re using the Player-tag to find the player? Really? Why? Why in the name of everything that is (un)holy are we using a string reference in an advanced C# course? I hope this problem will be addressed in the later lectures… :frowning:

Sorry for the rant… But you don’t need a noob like me telling you that string references are baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaadddddddd… :frowning:

It’s not only that string references are bad, but tag usage must also be used with caution because if you have multiple GameObjects with the same tag, it does not guarantee which one will be returned, that’s why it’s mostly used to find UNIQUE objects in the scene.

Of course the best way to get a hold of an object, is by just assigning it in the inspector, that’s the least expensive and also the safest method to do your job, however, in this case it doesn’t matter if we use tags, we want to find a UNIQUE object in the scene and we know that there won’t be another object with the “Player” tag.

It also doesn’t matter if you’re in a basic, advanced, expert course, the goal here (and I think it was already said many times prior to reaching the Enemy AI section), is to first get something to work with, then refactor along the way. Sam chose to do it this way, someone else might use inspector assignment from the beginning, you are always welcome to improve anything you are given in this course.

3 Likes

Generally, I agree with you that string references are bad. I personally take great pains to avoid them. Sometimes, however, it’s the least troublesome solution. In this case, it’s the fastest solution with no need for dependencies. There are other ways to get the player, each with it’s own advantages and drawbacks…

  1. You could Serialize the field and set it in the Inspector. This assures no misspellings, but can break if you miss making the connection in a component.
  2. You could FindObjectOfType() instead of looking for a tag. This is slower than a tag search, but not so much it would generally be noticeable. It also introduces a dependency on RPG.Control, which could lead to circular dependencies.
  3. You could create a class in RPG.Core called Player.cs that you only put on the player. This object could be used to locate the player in the same way as PlayerController() but would introduce no new dependencies.
3 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms