I am quite new in game development but was experience in C# in windows application.
I am currently working on the creep’s script over a week now and still not able to figure the best way doing it in unity.
This is what I wish to have :-
Creep is spawn from building
When there is enemy attacking the building, Creep will directly set its target to the enemy attacking building.
If no enemy found when creep is spawn from building, then creep will head to enemy base.
Creep will detect for enemy on the way to enemy base, and auto attack the enemy.
Currently this is my creep script structure :-
I have
CreepStatus.cs ( handling HP, attack damage, moveSpeed, currentTarget… blah blah blah, but without function, just public variable, and other script will refer to this)
EnemyDetector.cs ( this script put under child GameObject with collider with Trigger. currently work like this ::
Awake () = search for nearby enemy using overlapSphere
OnTriggerEnter = set CreepStatus.currentTarget = collider.gameobject
But I feel that the structure for my creep is hardly to maintain and is not really fully working , so I hope someone here able to give some idea or advice for me.
** Is it better to use OverlapSphere or OnTriggerEnter in order to achieve the objective for my enemyDetector ?
You might want a controller class such as CreepScript that gets/references all of the other scripts and uses a State Machine to decide what to do. It should listen to certain Events such as “creepHealthScript.Died”, then set its state to Dead, or listen to “enemyDetector.DetectedEnemy(GameObject enemyGO)” and set its state to ChaseEnemy.
Having a lot of scripts doing their own thing can become tangled sometimes. Use a controller script to use the functionality inside the other scripts.
Is it better to fully using OverlapSphere for enemy detector instead of using OnTrigger in your opinion?
I am always concerning on game performance while developing my game.
Besides, I am facing an issues on using OnTrigger Event. When the enemy is nearby creep spawn point, the creep that newly spawn is not able to detect the enemy using OnTrigger upon spawned.
For detecting on spawn you should make sure detectable objects have a RigidBody component (make isKinematic=true to stop them reacting to gravity/etc). OnTriggerEnter should work then.
I’m not a performance expert, but I do use OnTriggerEnter/Exit events with a List to track everything inside the sphere. For performance I guess this is better than using OverlapSphere all of the time, but OnTriggerStay might not be as good as OverlapSphere. OverlapSphere can use a layermask to ignore things too.