Best Practices for touch event on GameObject C#,Best Practices for touch events C#
Hi guys,
It's better to detect a touch event on a GameObject in a generic Main Script that handles multiple types of object (player, enemy, item etc) or detect the event in the script attached to the GameObject itself (enemy.cs, item.cs, player.cs)?
Main.cs or Enemy.cs, Player.cs, Item.cs
Thank you in advance!
Answer by UnityCoach · Mar 20, 2018 at 12:02 AM
I'd say it's better to handle touch in one script only to avoid any conflict in design.
Then this script can forward events to whatever is touched, using interfaces for example, such as
public interface IHandleTouchTap
{
void OnTap ();
}
public interface IHandleTouchDoubleTap
{
void OnDoubleTap ();
}
public interface IHandleTouchDrag
{
void OnDrag (Vector2 drag);
}
public interface IHandleTouchMultiple
{
void OnMultiTouch (int touchCount);
}
// etc..
Thank you for you answer! So, what about performance? $$anonymous$$y game is pretty simple, you touch GameObjects to interact with them but there are 10 different types of them. I cannot find any conflict now in both approach, because if I touch an enemy it will be attacked, if i touch an item it will be acquired by the player. In this moment I have only one script to handle events as su suggest but in someway looks not-so-object-oriented to me. So I was just wondering.
Like you said, if your game is pretty simple, there's probably no value in making it more complicated with some object oriented architecture. Although, if you need to split things up and add more features, you may want to. Here's an article I wrote a while back on profiling performances in regards to architecture. Sometimes, it's far from what you'd expect. So I'd say the best practice, is to benchmark.
Your answer
Follow this Question
Related Questions
Destroy a GameObject when it Collides with any other GameObject 3 Answers
How To how ?? 2 Answers
Collision between two prefabs not being detected 0 Answers
Rigidbody object colliding with plane. 0 Answers
Multiple joints on GameObject 1 Answer