Reputation: 3
Hello dear developers and engineers! I stumbled upon the usage of a generic method. I don't have to use generic. However, I preferred it. I use Unity3D. MageAA class has access to EnemyID class and Player controller class. PlayerController class has no access to others. My point is to create a generic method in PlayerController class. Then call that method in MageAA with EnemyID as an argument. Here what I've. How can I make it work? Thank you!
public class MageAA : MonoBehaviour
{
public GameObject selectedTarget;
PlayerController controller;
// Start is called before the first frame update
void Awake()
{
controller = GetComponent<PlayerController>();
}
// Update is called once per frame
void FixedUpdate()
{
selectedTarget = controller.SelectPointedObject<EnemyID>();
}
}
public class PlayerController : MonoBehaviour
{
public GameObject SelectPointedObject<T>() where T: class
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
RaycastHit[] hits = RaycastAllSorted();
if (hits.Length > 0 && hits[0].transform.GetComponent<T>() != null)
{
return hits[0].collider.gameObject;
}
else
{
return null;
}
}
return null;
}
Upvotes: 0
Views: 485
Reputation: 176
public interface ICharacter
{
public string Name { get; set; }
public int Health { get; set; }
}
public class Character : ICharacter
{
public string Name { get;set; }
public int Health { get; set; }
public string GetOrSetName(string name)
{
if (Name != null)
Name = name;
return Name;
}
}
public class Hero : Character
{
public string Name { get; set; }
public int Health { get; set; }
}
public class NPC : Character
{
public string Name { get; set; }
public string Role { get; set; }
}
public class NamerClass
{
public Character Character { get; set; }
public string GetOrSetName<T>(string text) where T : Character, new ()
{
return Character.GetOrSetName(text);
}
}
static void Main(string[] args)
{
Hero hero = new Hero();
NPC npc = new NPC();
NamerClass genericNamer = new NamerClass();
genericNamer.GetOrSetName<Hero>("SUPER MARIO");
genericNamer.GetOrSetName<NPC>("POTION MARKET");
}
"May be this gives you an idea"
Upvotes: 1