Alternative way to get unit (Unity Turn Based Strategy Course)

I set up my code a bit differently for the challenge and it works, but is there any drawback to the way I did it? I added the unitLayerMask variable to the MouseWorld script along with this method:

public static Unit GetUnit()
	{
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		Physics.Raycast(ray, out RaycastHit rayCastHit, float.MaxValue, instance.unitLayerMask);

		if(rayCastHit.transform.TryGetComponent<Unit>(out Unit unit))
		{
			return unit;
		}

		return null;
	}

Then, in the UnitActionSystem script, I have:

private void Update()
	{
		if (Input.GetMouseButtonDown(0))
		{
			HandleUnitSelection();
		}

		if (Input.GetMouseButtonDown(1))
		{
			selectedUnit.Move(MouseWorld.GetPosition());
		}
	}

	private void HandleUnitSelection()
	{
		Unit unit = MouseWorld.GetUnit();
		if (unit != null)
		{
			selectedUnit = unit;
		}
	}
1 Like

That does work but now you made it so the MouseWorld script now handles calculating the Mouse Position and checking for Units under the Mouse.

So it works perfectly fine but it’s a question of code cohesion, does it make sense for the MouseWorld script to also have knowledge of what is a Unit? Personally I don’t think so.

I reuse my equivalent MouseWorld script in pretty much every video I make, I only want that class to be responsible for getting the mouse position and nothing else. I can reuse it in any tutorial I make regardless if it has “Units” or not.

If you try to reuse that class in another project where you wanted the mouse position, like for example a City Builder game that has no concept of a Unit, then that class would throw an error and you’d have to refactor that code and remove references to the Unit.

14 Likes

Ah, okay. I see now. I am still getting used to the idea of keeping things separated, which is why I am taking this course! Thank you!!

I am currently finishing up my junior year in an online university, working toward a software development degree, and I wish you were one of my instructors there too! They don’t take the time to explain the importance of concepts like this the way you do.

6 Likes

I also did a Game Development program in college, and in the three years I was in that program I didn’t get a single clear and concise explanation of encapsulation either.

The GDTV team and CodeMonkey (over on YouTube first, and now here) have taught me more about good programming practices than my college ever did.

I personally think that Hugo is one of the best Unity educators on the internet right now, and I’m really glad he’s participating in the GDTV ecosystem now.

12 Likes

Privacy & Terms