GameObject in class? Unity3D -
im in middle of tower defense - style developing in unity using c#. so, have abstract class towers has int range, rate of fire, etc. , have few child classes different type of towers. im in doubt of having attribute of type gameobject in tower class, contains tower game object (for spawning projectile, move tower if necesary) or having class attributes , having controller controls tower class atributes , controls game object itself(when need move it, set active or not, etc).
i wish made self clear! thanks!
edit
im not sure wich option better.
option 1:
public abstract class tower{ private int health; ... private gameobject object; public healthdown(){ if(health >1){ health -= 1;} else { object.setactive(false);} } }
option 2:
public abstract class tower{ private int health; ... public healthdown(){ if(health >1){ health -= 1;} } }
and script controlls tower:
public class controller : monobehaviour { tower tower; ... void update(){ if(tower.health <= 1){this.gameobject.setactive(false);} } }
i wish more clear!
thanks!
i assuming have different models/materials each tower , therefore parameterize these different attack rates etc via monobehavior
-derived script (towercontroller.cs
) attached each prefab:
tower1 prefab: model = tower material = tower1 script = towercontroller.cs attackrate = 10 projectileprefab = projectile1 tower2 prefab: model = tower material = tower2 script = towercontroller.cs attackrate = 20 projectileprefab = projectile2
this follows normal unity workflow , allows editing via ui , overridden instances if required.
therefore neither option 1 nor option 2, closer option 2 without class inheritance, , more unity-conventional.
here's example implementation of towercontroller
allowing attackrate
, projectile prefab set (so can have different versions each tower type, set via ui):
using unityengine; using system.collections; public class towercontroller: monobehaviour { public int health = 50; public int attackrate = 10; public gameobject projectileprefab; public void takedamage(int damage) { health -= damage; if (health <= 0) { gameobject.setactive(false); } } private void fireprojectile() { gameobject projectile = instantiate(projectileprefab, transform.position, transform.rotation) gameobject; projectile.transform.setparent(transform.parent, true); // add force etc. } }
Comments
Post a Comment