Search Unity

  1. Click here to see what's on sale for the "Best of Super Sale" on the Asset Store
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

TowerDefense ToolKit 4

Discussion in 'Assets and Asset Store' started by songtan, Apr 18, 2012.

  1. bastilar

    bastilar

    Joined:
    Apr 9, 2017
    Posts:
    17
    Hi, great asset so far and it's a lot easier to use than other solutions I've been trying (i'm new to coding). I wanted to know, how do I change the display text when I click or hover over a built turret (and in the build icons) so that it displays the armor type and damage?

    Basically it'll just be simple text in the red box area like:

    Armor - Reactive
    Damage - 40
    Attack Speed - 0.5 sec

    Basically the stats of the actual tower so the player knows what they are building.

    Thanks!
     
    Last edited: May 4, 2020
  2. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    The code in question is in UITowerSelect.cs, UpdateDisplay(). You can see the existing code has two line of code that display the tower name and description. So what you need is to add a new Text object and link to the UITowerSelect to display the stats. The stats themselves can be pulled from the Unit.cs script. Take a look at line500 onwards, that's all the stats corresponding to the unit.

    For hover over button tooltip, the code you are looking for is in UITooltip.cs, specifically _Show() in line61. Same principal applies there.

    Make sense?
     
  3. bastilar

    bastilar

    Joined:
    Apr 9, 2017
    Posts:
    17
    Awesome, that's exactly what I was looking for, thanks! Hopefully I can get it to work properly.

     
  4. bastilar

    bastilar

    Joined:
    Apr 9, 2017
    Posts:
    17
    Thanks songtan, I fiddled with it for a couple of hours and got it working! I'm surprised you disabled the getstatsdescription() method as it was exactly what I needed but I re-enabled it and modded the code (minimally as I could) and instead of creating new objects which kept causing problems, I just used ur pre-built in functions and kept calling them. Works perfectly from what I can tell. I'll come back with more questions (no doubt) when I run into them. Back to fun!
     
    Proto-G likes this.
  5. BlackManatee

    BlackManatee

    Joined:
    Jun 13, 2013
    Posts:
    61
    Hi, Songtan - long time no see! I did a diabetes game with your old TDTK several years ago, and I'm working on a different game with some RTS elements now, so I wanted to use some elements from TDTK's building/placement/resource system.

    Unfortunately, I'm working in the Universal pipeline (Unity 2019.3.10f1), and I'm unable to get the cameras to work properly. I managed to upgrade the materials (most of them, anyway), but the camera "stack" seems to be reversed or something. The UI cameras all seem to be layered in reverse order, so that I have to delete (or deactivate) all of the UI cameras in order to see the actual level in the game window.

    I'm getting some seemingly minor errors as well, but I'm not sure if they're related. There are two errors which are repeated a total of three times. The two errors are red and yellow:

    RED:
    Component GUI Layer in Main Camera for Scene Assets/TDTK/Scenes_Demo/Demo_Linear.unity is no longer available.
    It will be removed after you edit this GameObject and save the Scene.
    UnityEngine.GUIUtility: ProcessEvent(Int32, IntPtr)

    YELLOW:
    Component at index 2 could not be loaded when loading game object 'Main Camera'. Removing it!
    UnityEngine.GUIUtility: ProcessEvent(Int32, IntPtr)

    Any ideas about how I might solve this? Thanks!
    ~~Bill
     
  6. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    I'm not sure what you are referring to with regards to the camera stack. Things are just fine on my end.

    The error and warning however are harmless. The prefab contains an obsolete component from earlier version of Unity. You can get rid of it by opening the prefab TDTK in the Resource folder, select 'CameraControl_Pivot/MainCamera'. Unity would get rid of the obsolete component on the prefab and you should be able to create new scene without any error from there on.
     
  7. BlackManatee

    BlackManatee

    Joined:
    Jun 13, 2013
    Posts:
    61
    Hi again, Song,
    I realized that my use of the phrase "camera stack" was unfortunate, because I'm not referring to the post-processing "stack." Instead, I'm just referring to the various UI layers (and their cameras) and how they are ordered (stacked) on top of each other. Sorry about that!

    To make things clearer, I've taken a few screen shots with the different cameras turned off.

    This first screenshot (#1, "All Cams Active") shows what the game screen looks like when I hit "play" with any of the TDTK demo scenes. As you can see, only one of the UI screens is visible, because the blue backdrop is covering everything else.

    1-Demo-OnPlayAllCamsActive.PNG
    The second screenshot (#2, "UICamera_Screen-Off") shows "Play" mode with one of the UI cameras turned off.
    2-Demo-OnPlay_UICamera_Screen-Off.PNG

    The third screenshot (#3, "BothUICameras_Off") shows "Play" mode with both UI cameras deactivated.
    3-Demo-OnPlay_BothUICameras_Off.PNG
    The fourth screenshot (#4, "UICamsOff,OverlayCamOff") is the only one that actually shows the game scene rather than just UI. I've marked the cameras that I've deactivated and the one that's still active.
    4-Demo-OnPlay_UICamsOff,OverlayCamOff.PNG

    If you have any suggestions, I'd appreciate it. I haven't tried this version of TDTK in the conventional/standard version of Unity; perhaps the problem is tied to my use of the URP/LWRP.

    Thanks for any ideas you can offer!
     
    MaxiMaximaal likes this.
  8. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    I have to say I have no problem on my end. Try checking the setting on those cameras, make sure the 'Clear Flags' is on both UICameras and OverlayCamera are set to 'Depth Only'.
     
  9. BlackManatee

    BlackManatee

    Joined:
    Jun 13, 2013
    Posts:
    61
    Thanks, Song--

    Quick update: I installed TDTK into two totally new projects: one brand-new project used the standard 3D render pipeline and the other brand-new project used the URP/LWRP option.

    To my great relief, the standard 3D pipeline version of the project works perfectly with TDTK. Howevere, the URP version of the project has all the same problems I described in the previous posts -- i.e., UI backdrops that completely obscure the layers beneath.

    Not sure why this is, but you may want to add a warning to your latest TDTK releases, so buyers don't try to use it with Unity's new render pipeline. That could save a lot of frustration, at least until you issue a URP-compatible update.
     
  10. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    Ah. Sorry I missed the bit where you say you are using URP. I'll add a warning in the future update. Very sorry for the trouble.
     
  11. BlackManatee

    BlackManatee

    Joined:
    Jun 13, 2013
    Posts:
    61
    Thanks, Song! I'm sure it's just something that needs tweaking in the camera and backdrop setup. I can always reconstruct the UI with new cameras, which I'll probably be doing anyway -- but if I come across a specific solution before your next update, I'll let you know. :)

    (or, more likely, if Unity updates the URP to address the issue, lol!)
     
  12. UlfvonEschlauer

    UlfvonEschlauer

    Joined:
    Dec 3, 2014
    Posts:
    101
    Hey Song!
    I have another question: Is there a way to pass the AudioManager which (I presume) handles all the sounds of TDTK into the AudioMixer as a separate Group?
    Thanks!
    Edit: Never Mind I added the necessary lines to the AudioManager Code. All good now :)
     
    Last edited: May 30, 2020
  13. bastilar

    bastilar

    Joined:
    Apr 9, 2017
    Posts:
    17
    Hey Songtan,

    been busily working on the game adding content but I'm still running into weird simple bugs though I'm just using the editor. I wanted to add 50 max life to player's life cap but it doesn't work. I purchased the perk etc and let enemies hit me but it stays stuck at 50/50 instead of 100/100. Here's the screenshots.



    I did not mess with the code for upgrading or perks etc. I also tried changing the perk to life gain and it doesn't work either. I noticed some of my perks kept breaking (use ot work then stopped working) when I was adding more tower unlocks as perk upgrades and more towers. I'm not sure why the game isn't changing the values.

    Thanks Songtan.
     
  14. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    I'm not sure what's wrong in your case. I've just done a quick test and it seems to be working for me, both when perk is prepurchased or purchased during runtime. You must have accidentally broke something when modifying the code. First I would run the test again and check the life and lifecap value on GameControl instead of the one in GameView to make sure the display is correct. If that checks out, I would add some debug in Purchase() in Perk.cs to make sure the function is called when you purchase a perk in runtime.
     
  15. bastilar

    bastilar

    Joined:
    Apr 9, 2017
    Posts:
    17
    Hopefully we're getting somewhere. I never touched perk.cs ever but I did as you asked, and interestingly, it's not behaving like it should for some strange reason.



    That's odd, it's calling a function I guess but it's not accessing the gamecontrol.modifylifecap/gainlife part at all???? The debug.log msg did not trigger at all.

    I'm not sure why it's not being called. It seems like it should be calling this part.
     
    Last edited: Jun 2, 2020
  16. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    Check the PerkManager in your scene. Make sure that the option 'GameScene' is checked. If not, those line will not be executed.
     
  17. bastilar

    bastilar

    Joined:
    Apr 9, 2017
    Posts:
    17
    Omg, thank you. I knew it had to be something simple and I feel so dumb. Now it works, and my unlock towers via perk should be working again. Thanks Songtan!
     
  18. andreigrigore

    andreigrigore

    Joined:
    Jan 23, 2016
    Posts:
    3
    Hi Song! I have a couple of questions, would really appreaciate if you could help me out.
    It seems like the attack animations on AOE towers won't play. Is there any way to fix this?
    Also, I would like to have a turret tower that fires a shoot object, but the effect of the shoot object affects multiple creeps. Is that possible?

    Thanks !
     
  19. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    1. I'm afraid AOE towers, like Resources towers don't play any attack animation since they don't really 'attack' a particular target. if you want, you can add AnimPlayAttack(); in line196 of UnitTower (same line as FireMiscEffect();). That should have the animation play. Mind you I haven't test this so I'm not entirely sure it will work.

    2. I assume you are talking about visual-effect on an tower with aoe attack? You can create a 'dummy' effect for the said tower. The effect should be doing nothing gameplay wise except having a 'on-hit-visual-effect'. Then the visual effect will be spawned on every unit hit by the tower.
     
  20. UlfvonEschlauer

    UlfvonEschlauer

    Joined:
    Dec 3, 2014
    Posts:
    101
    Hey Song!
    Quick question: Do towers with two shoot points double the Damage Min/Max in each attack when compared to a tower with the same stats but a single shoot point?
    Also, get AOE effects recalculated for every nearby unity, or are they a hit only when the "main target" is hit (and then at the same damage)?
    Thanks!
     
  21. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    The number of shoot-points and shoot-object are just for visual. They do not affect the damage. The damage will be exactly as what they are specified as.

    The aoe will only apply on the first hit on the main target. They don't apply for the subsequent hit on the secondary target caught in the aoe radius. That said, the hit/miss/crit and damage amount are calculated independently for each target affected.
     
    UlfvonEschlauer likes this.
  22. UlfvonEschlauer

    UlfvonEschlauer

    Joined:
    Dec 3, 2014
    Posts:
    101
    Ok, in that case, it would be nice if we could have some sort of way to have a tower "spray" bullets into a group (and hitting random targets in that). Say I have a machine gun, which has a relatively low hit chance. So it will miss the main target often, but other nearby enemies (in the AOE radius) could get hit instead (with equal probability as the main target). I think that would be a really nice feature to have.

    Edit: Alternatively, what would happen if my tower had a min/max damage range from 0 to 1. Would a hit with zero damage still count as a hit and allow for the AOE effect to hit the other enemies in the area?
     
    Last edited: Jun 17, 2020
  23. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    You can do exactly that. Like I said, hit/miss for each target in the aoe radius are calculated independently so each unit has the equal amount of chances to be hit/miss by the same attack.

    For your alternate question, aoe applies regardless or the attack hit/miss the main target. So zero damage or not, every unit within range will still be subject to the attack.
     
    UlfvonEschlauer likes this.
  24. Complax

    Complax

    Joined:
    Nov 27, 2019
    Posts:
    3
    Hi there, I'm having a blast messing around with this. However a project I would like to test out a bit involves me making the game first person. How would I go about allowing this to function in a first person perspective?
     
  25. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    First ditch the default camera control and implement your own first person movement control. Then just change all the raycasting in the UI to using center of the screen instead of the cursor position. Basically that's it.
     
  26. Complax

    Complax

    Joined:
    Nov 27, 2019
    Posts:
    3
    Awesome, thank you. Also would there be any way to allow for a placement system that isn't locked by a grid? Something similar to a free placement system? From what I can see, that's something I would have to implement myself.
     
  27. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    Yes you can. Just enable the option 'Free Form Mode' in TowerManager. There's an example scene 'Demo_Linear_FreeForm'.
     
  28. Complax

    Complax

    Joined:
    Nov 27, 2019
    Posts:
    3
    Oh, perfect. Thank you so much!
     
  29. bastilar

    bastilar

    Joined:
    Apr 9, 2017
    Posts:
    17
    Hey SongTan,

    Have any ideas on how to change the display text in the resource cost part of the ability use window? On the lower right corner of the screenshot shows -10. The ability is working as intended but I just wanted to fix the display bug, and also create more space between the cash and parts labels. I could not find a dedicated window panel for the
    ability popup display on the lowerright even though I did find the ui object component that calls the button.

    I also tried to create a new effect on hit that grants 10 neutronium when you click the ability button but that didn't seem to work. I made sure the effect and hit chance were all set to 1.

    Oh I almost forgot, the way I did it was, the abilities cost resources (cash and parts) and I set it to 95000 cash cost, -10 parts cost (to get the plus 10 parts effect to work). I boxed in red what i did (centerish , above in screenshot)



    Thanks songtan.
     
    Last edited: Jun 24, 2020
  30. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    Look for UI/UICamera/Canvas_Toolip/Panel/Toolip/TextName/RscList_Left in the scene. There should be a Horizontal Layout Group on that game-object. Change the spacing should space out the resource display more. I should point out that this is the similar tooltip shared by the build button. So changing the spacing will affect the tooltip appearance for build button too.

    Regarding the ability, I have to say that is not how ability intended to be used. But I've just tested the way you did the ability and it works! In what way it doesn't work for you. The ability can't be activated?
     
  31. bastilar

    bastilar

    Joined:
    Apr 9, 2017
    Posts:
    17
    Ah Ok, letme try fiddling with the spacing. (update, thanks, the horizontal layout group was what I was looking for and I was able to change the spacing and padding to tidy up the text nicely.)

    Thanks about the ability! It actually works (and it can be activated, it deducts the 95k credits and gives you 10 neutronium parts) but the display shows "-10" but I wanted it to show as "+10". It's more of a polish issue so people don't think they are losing neutronium when in fact they are gaining +10. I wasn't sure where to change the label to show only positive values or do a negate command in the code.
     
    Last edited: Jun 24, 2020
  32. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    The code to change the cost display of the ability on tooltip is in Line142 or UITooltip.cs. Hope this helps.
     
  33. bastilar

    bastilar

    Joined:
    Apr 9, 2017
    Posts:
    17
    Awesome, that'll work, thanks!
     
  34. UlfvonEschlauer

    UlfvonEschlauer

    Joined:
    Dec 3, 2014
    Posts:
    101
    Hey Song!
    I am trying to do the same thing (have creeps hit by an AOE effect display some visual effect), but I can't seem to follow your instructions above. I look at the EffectEditor and I do not see any settings for visual effects. Is that because of my older version of TDTK, or am I misunderstanding the instructions?
     
  35. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    What version are you using? Visual effect for effect are added in version 4.0.4 f6. So if you are using anything from earlier, it won't be there.
     
  36. UlfvonEschlauer

    UlfvonEschlauer

    Joined:
    Dec 3, 2014
    Posts:
    101
    Darn! Is the code for that isolated to the effects or does it propagate through multiple files?
     
  37. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    3 files. UStats.cs where the variables for the visual effects is declared, Unit.cs where it's spawned/destroyed, and W_EffectEditor.cs for the editor option. You should be able to download the latest, do a search through the files in question and modify your own accordingly with relative ease.
     
  38. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    108
    Unfortunately the assets I purchased, for the towers, import 180 on the X axis. The designer won't correct the issue. Would I need to modify many scripts to make them face correctly? I've tried creating an empty game object and placing the tower as a child, but it doesn't work, so it must be in the scripting? Any assistance would be appreciated.
     
    Last edited: Jul 6, 2020
  39. songtan

    songtan

    Joined:
    Apr 9, 2011
    Posts:
    2,656
    Inverted model shouldn't be the problem. I've used inverted model myself at one point. You just need to create an additional empty game-object and place the model as child. You can then adjust the rotation of the child of the child object to make it look right. Take turret object for instance, you create an empty object and assign that as the turret object. The script will work with that just right. If you assign your inverted model as the child object and have it pointing at the right direction, it will stay that way.
     
  40. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    108
    I was able to get it functioning correctly. Thanks so much!
     
    Last edited: Jul 3, 2020
  41. RobG88

    RobG88

    Joined:
    May 28, 2015
    Posts:
    23
    Congrats! Hope you're still on target! Going to grab it as soon as it's available!
    If you need anyone to do any last minute play testing I'd be happy to help!
     
  42. spicybat

    spicybat

    Joined:
    Jul 28, 2019
    Posts:
    2
    Hi all! Has anyone tried creating a preview of the pathing indicator when building a Drag n Drop tower? Currently it seems like the pathing indicator only changes when a player builds a tower that is obstructing the path. I'd the pathing indicators to also update while players are in the middle of deciding when to place a tower.

    Thanks!
     
  43. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    108
    Hey Song, hope all is well! You sent me an updated UnitTower script / Utility, years ago, that would hide the tower being built so that a build effect could take place before the built tower appears. I've learned much since then, but still can't figure out how to achieve this with the new UnitTower.cs

    Would you mind updating the current UnitTower.cs so there can be an optional delay? I think this would be a very useful addition in future updates. I'm looking to be able to hide when building or upgrading so that I can place a half built tower before the built tower is complete and active.

    Here's the original code:
    Code (CSharp):
    1. public bool hideWhenBuilding=false;
    2.         [HideInInspector] public float builtDuration;
    3.         [HideInInspector] public float buildDuration;
    4.         public void UnBuild(){ StartCoroutine(Building(stats[currentActiveStat].unBuildDuration, true));    }
    5.         public void Build(){ StartCoroutine(Building(stats[currentActiveStat].buildDuration));    }
    6.         IEnumerator Building(float duration, bool reverse=false){        //reverse flag is set to true when selling (thus unbuilding) the tower
    7.             construction=!reverse ? _Construction.Constructing : _Construction.Deconstructing;
    8.          
    9.             if(hideWhenBuilding) Utility.DisableAllChildRendererRecursively(thisT);
    10.          
    11.             builtDuration=0;
    12.             buildDuration=duration;
    13.          
    14.             if(onConstructionStartE!=null) onConstructionStartE(this);
    15.  
    16.             if(buildingEffect!=null) ObjectPoolManager.Spawn(buildingEffect, thisT.position, thisT.rotation);
    17.          
    18.             yield return null;
    19.             if(!reverse && playConstructAnimation!=null) playConstructAnimation();
    20.             else if(reverse && playDeconstructAnimation!=null) playDeconstructAnimation();
    21.          
    22.             while(true){
    23.                 yield return null;
    24.                 builtDuration+=Time.deltaTime;
    25.                 if(builtDuration>buildDuration) break;
    26.             }
    Here's an example:
     

    Attached Files:

    Last edited: Jul 11, 2020
  44. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    108
    I'm trying to figure out how to make my cannon tower immune to stun effect from creep.
    I see immuned effect list for creeps, but not for towers.
    My low level skeleton will throw a bone at a low level soldier and (chance) stun him.
    But it doesn't make sense for it to stun the cannon tower.

    Also, when my skeleton is stunned by my ballista, it stops progressing forward, but the walk animation still plays. Is there a simple solution for making the walk animation stop playing during stun on a creep?

    Please advise, thank you.
     
    Last edited: Jul 11, 2020
  45. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    108
    Figured out the immuned effect issue. I just copied this section of script from the W_UnitCreepEditor.cs and pasted it into the W_TowerEditor.cs
    Code (CSharp):
    1. TDE.Label(startX, startY+=spaceY, width, height, "Immuned Effect:", "The list of effects the unit is immune to");
    2.             for(int i=0; i<unit.effectImmunityList.Count; i++){
    3.                 TDE.Label(startX+spaceX-height, startY, width, height, "-");
    4.                
    5.                 int effIdx=Effect_DB.GetPrefabIndex(unit.effectImmunityList[i]);
    6.                 effIdx = EditorGUI.Popup(new Rect(startX+spaceX, startY, width, height), effIdx, Effect_DB.label);
    7.                 if(effIdx>=0){
    8.                     int effID=Effect_DB.GetItem(effIdx).prefabID;
    9.                     if(effID>=0 && !unit.effectImmunityList.Contains(effID)) unit.effectImmunityList[i]=effID;
    10.                 }
    11.                
    12.                 if(effIdx<0 || GUI.Button(new Rect(startX+spaceX+width+3, startY, height, height), "-")) unit.effectImmunityList.RemoveAt(i);
    13.                
    14.                 startY+=spaceY;
    15.             }
    16.            
    17.             int newEffID=-1;
    18.             newEffID = EditorGUI.Popup(new Rect(startX+spaceX, startY, width, height), newEffID, Effect_DB.label);
    19.             if(newEffID>=0) newEffID=Effect_DB.GetItem(newEffID).prefabID;
    20.             if(newEffID>=0 && !unit.effectImmunityList.Contains(newEffID)) unit.effectImmunityList.Add(newEffID);
    Seems to be working fine so far.
     
  46. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    108
    Song, do you have that original script that you used on your TDTK demo towers menu scene that would cause the towers to randomly rotate/oscillate as if they were looking back and forth for enemies? (rotate Y axis 90, pause 5 seconds, rotate Y axis -130, pause 3 seconds, etc..) I've been trying to find a script that does this and your old one is the only one that I know will do what I'm attempting. Thanks!
     
  47. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    108
    Song, hope you're ok. Haven't seen a response in over a week.
     
  48. toddkc

    toddkc

    Joined:
    Nov 20, 2016
    Posts:
    89
    @Proto-G
    Code (CSharp):
    1.  
    2. namespace RotationExamples
    3. {
    4.     using System.Collections;
    5.     using UnityEngine;
    6.  
    7.     public class DelayedRandomRotationOnYAxis : MonoBehaviour
    8.     {
    9.         [Header("Settings")]
    10.         [SerializeField] private float rotationSpeed = 10f;
    11.         [Header("Delay Range")]
    12.         [SerializeField] private float minDelayTime = 4f;
    13.         [SerializeField] private float maxDelayTime = 10f;
    14.         [Header("Rotation Range")]
    15.         [SerializeField] private float minRotation = 15f;
    16.         [SerializeField] private float maxRotation = 90f;
    17.  
    18.         private Transform thisTransform;
    19.         private Quaternion targetRotationQuaternion;
    20.         private WaitForSeconds delayTime;
    21.  
    22.         private void Awake()
    23.         {
    24.             thisTransform = transform;
    25.         }
    26.  
    27.         private void OnEnable()
    28.         {
    29.             targetRotationQuaternion = thisTransform.rotation;
    30.             StartCoroutine(RotateAfterDelay());
    31.         }
    32.  
    33.         private void OnDisable()
    34.         {
    35.             StopAllCoroutines();
    36.         }
    37.  
    38.         private void FixedUpdate()
    39.         {
    40.             ApplyRotation();
    41.         }
    42.  
    43.         // rotate towards target rotation
    44.         private void ApplyRotation()
    45.         {
    46.             thisTransform.rotation = Quaternion.Lerp(thisTransform.rotation, targetRotationQuaternion, Time.deltaTime * rotationSpeed);
    47.         }
    48.  
    49.         // get a random float for a delay timer
    50.         private WaitForSeconds GetRandomDelayTime()
    51.         {
    52.             float _delayTimer = Random.Range(minDelayTime, maxDelayTime);
    53.             WaitForSeconds _newDelay = new WaitForSeconds(_delayTimer);
    54.             return _newDelay;
    55.         }
    56.  
    57.         // get a random rotation to rotate to
    58.         private Quaternion GetRandomRotationQuaternion()
    59.         {
    60.             Quaternion _currentRotation = thisTransform.rotation;
    61.             float _rotation = Random.Range(minRotation, maxRotation) * GetDirection();
    62.             Quaternion _targetRotation = Quaternion.AngleAxis(_rotation, thisTransform.up);
    63.             return (_currentRotation * _targetRotation);
    64.         }
    65.  
    66.         // get a positive or negative direction
    67.         private float GetDirection()
    68.         {
    69.             return Random.Range(0, 2) * 2 - 1;
    70.         }
    71.  
    72.         // wait random amount of time then set random rotation
    73.         private IEnumerator RotateAfterDelay()
    74.         {
    75.             while (true)
    76.             {
    77.                 delayTime = GetRandomDelayTime();
    78.                 yield return delayTime;
    79.                 targetRotationQuaternion = GetRandomRotationQuaternion();
    80.             }
    81.         }
    82.     }
    83. }
    84.  
     
    Last edited: Jul 15, 2020
    MaxiMaximaal and Proto-G like this.
  49. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    108
    You're awesome, thanks so much!!!
     
    toddkc likes this.
  50. toddkc

    toddkc

    Joined:
    Nov 20, 2016
    Posts:
    89
    I'm absolutely garbage with quaternions, so any excuse I can find to practice them is good lol
     
unityunity