- Home /
Question by
kizzagarhu · Feb 13, 2015 at 10:00 AM ·
tutorialgenericroguelikedatatype
How does Unity figure out generic component type as Wall in Project: 2D Roguelike tutorial?
Unity released a tutorial for 2d roguelike game a couple days ago: http://unity3d.com/learn/tutorials/projects/2d-roguelike
In the project movement of both enemy and player units are handled by MovingObject script, which first attempts the move by checking collisions. If collisions return true, a generic component is passed, which later is assumed to be either a Wall or Player component to deal damage. Here is the AttemptMove code sample from MovingObjects from the project:
protected virtual void AttemptMove <T> (int xDir, int yDir)
where T : Component
{
//Hit will store whatever our linecast hits when Move is called.
RaycastHit2D hit;
//Set canMove to true if Move was successful, false if failed.
bool canMove = Move (xDir, yDir, out hit);
//Check if nothing was hit by linecast
if(hit.transform == null)
//If nothing was hit, return and don't execute further code.
return;
//Get a component reference to the component of type T attached to the object that was hit
T hitComponent = hit.transform.GetComponent <T> ();
//If canMove is false and hitComponent is not equal to null, meaning MovingObject is blocked and has hit something it can interact with.
if(!canMove && hitComponent != null)
//Call the OnCantMove function and pass it hitComponent as a parameter.
OnCantMove (hitComponent);
}
How does either Wall or Player component picked and not say Transform, SpriteRenderer or any other component?
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613183147im_/https://answers.unity.com/themes/thub/images/avi.jpg)