├── .gitattributes ├── .videoRecordSizes.txt ├── ActivateManager.cs ├── Aiming.cs ├── AlphaHitTest.cs ├── AlphaShader.shader ├── ArrayPrefs2.cs ├── ArrayResize.cs ├── AutoFov.cs ├── BackgroundAnimationRepeat.cs ├── Ball.cs ├── BasicCameraZoom.cs ├── BehindLeftRightControl.cs ├── BetterWaitForSeconds.cs ├── Blinker.cs ├── BlurOptimizedImageEffect.shader ├── Boomerang.cs ├── BoomerangEffect.cs ├── Bot.cs ├── BounceObject.cs ├── BoundsExtensions.cs ├── Break.cs ├── BridgeBuilder.cs ├── BulletMLPoolLink.cs ├── CalculatesMissileParabolicTrajectorAndSteering.cs ├── CamFollow.cs ├── CameraMovement.cs ├── CameraShaker.cs ├── Car.cs ├── CenterOfMass.cs ├── ChangeCameraTargets.cs ├── CinemachinePathShape.cs ├── CircularLoadingDash.cs ├── ClickerRunner.cs ├── CoinK.cs ├── ColliderToFit.cs ├── ColorHex.cs ├── ColorLerper.cs ├── ColorPaletteController.cs ├── CommandPattern.cs ├── CompareLists.cs ├── ComponentUtil.cs ├── ContinueCoroutine.cs ├── CountDown.cs ├── CreateCube.cs ├── CreateEnemiesAroundPoint.cs ├── CreatePlaneStack.cs ├── CubeCut.cs ├── DecalPainter.cs ├── DeleteAllChildObjects.cs ├── DestroyAfterTime.cs ├── DisplayingTrajectoryPath.cs ├── DragShotMover.cs ├── DragSpinner.cs ├── DrawCapsule.cs ├── Enlarger.cs ├── EnumRandom.cs ├── EnumVal.cs ├── EventsUnityEvents.cs ├── Explosion.cs ├── FPSDisplay.cs ├── FacebookLogin.cs ├── FadeToBlueScript.cs ├── FadeToGreenScript.cs ├── FadeToRedScript.cs ├── FancyBoxShader.shader ├── FancyBoxShader2.shader ├── FindAllChilds.cs ├── FindDeepChild.cs ├── FindDescendentTransform.cs ├── FindNearest.cs ├── FindSamples.cs ├── FindWithTag.cs ├── FishAnimation.shader ├── FitCamera.cs ├── Floater.cs ├── FlyweightPattern.cs ├── FollowDragger.cs ├── Following.cs ├── GameManagerInstanceSample.cs ├── GameObjectExtensions.cs ├── GameobjectsinaCollider.txt ├── GetCenter.cs ├── GetCurveTimeForValue.cs ├── GetSetSample.cs ├── Gradient_3Color.shader ├── GrayscaleLayers.cs ├── GridBase.cs ├── GridShader.Shader ├── GridSpawner.cs ├── HandMove.cs ├── HeightmapToMesh.cs ├── HoverCam.cs ├── HpRegeneration.cs ├── ImageSlicer.cs ├── ImpactReceiver.cs ├── InfiniteRoadManager.cs ├── InterfaceSample.cs ├── IsBetweenRange.cs ├── JoystickController.cs ├── Jump.cs ├── LaunchProjectiles.cs ├── LeanTweenOnComplete.cs ├── LeanTweenSamples.cs ├── LerpCameraZoom.cs ├── LerpDemo.cs ├── LerpDemo2.cs ├── LerpMoveDemo.cs ├── Lerper.cs ├── LevelGenerator.cs ├── LevelGeneratorWithStack.cs ├── LightAdjuster.cs ├── LineFollower.cs ├── LineRenderJob.cs ├── ListExamples.cs ├── LivingBox.cs ├── LivingEntity.cs ├── LivingEntityCollider.cs ├── LockOnTarget.cs ├── LookAtTarget.cs ├── MapBuilderVertical.cs ├── MapGenerator.cs ├── MaterialChanger.cs ├── MaterialPropertyBlock.cs ├── Math.cs ├── MathX.cs ├── MatthiasWindZone.cs ├── MeshCombineWizard.cs ├── MeshExtensions.cs ├── MilesPerHour.cs ├── MinToAttribute.cs ├── MonoBehaviourBase.cs ├── MovingEnemy.cs ├── MovingPlatform.cs ├── MultiScreenshotCapture.cs ├── NeighborsDirectionExtensions.cs ├── OffsetUVs.cs ├── OnParticleCollision.cs ├── Orbit.cs ├── PainterScript.cs ├── ParseINT.cs ├── PathScript.cs ├── PauseWaitResume.cs ├── PerlinNoise.cs ├── Player.cs ├── Proximity_Sensor.cs ├── README.md ├── RandomColor.cs ├── RandomPointOnMesh.cs ├── RandomRotation.cs ├── RandomSeed.cs ├── RandomSpawner.cs ├── RaycastPlayerDoorOpen.cs ├── Raycasting.cs ├── RigidbodyExtensions.cs ├── Rolling.shader ├── RollingaCube.cs ├── Rope.cs ├── RopeControllerRealistic.cs ├── RopeSection.cs ├── RotatedBounds.cs ├── Rotater.cs ├── Rotation.cs ├── Rotator.cs ├── Save.cs ├── SaveGame.cs ├── ScaleLerper.cs ├── ScaleToView.cs ├── SceneBuilder.cs ├── ScoreCounter.cs ├── ScreenShotter.cs ├── ScreenshotWindow.cs ├── ScriptableData.txt ├── ScrollAndPinch.cs ├── ScrollUVs.cs ├── SeedFactory.cs ├── SelectVertex.cs ├── SetScreenSize.cs ├── SigletonScriptableObject.cs ├── SimpleCameraController.cs ├── SimulateProjectileCR.cs ├── Singleton.cs ├── Slerper.cs ├── SliderFill.cs ├── SmoothCameraFollow.cs ├── SpawnRadial.cs ├── Spin.cs ├── SteppedCameraZoom.cs ├── StringExtensions.cs ├── SuperRandomSpawner.cs ├── SwipeAndHold4Directions.cs ├── SwipeDetector.cs ├── SwipeManager.cs ├── TentacleRope.cs ├── TextureAnimation.shader ├── TimedSpawn.cs ├── ToonLitEnvironmentDetail.shader ├── Touch.txt ├── TouchManager.cs ├── TouchToShoot.cs ├── TrajectoryBall.cs ├── TransformTemp.txt ├── TransformandMoveObjectVertices.cs ├── UnbreakableCollider.cs ├── Unique.cs ├── WaitTimeSamples.cs ├── WavingGrass.shader ├── WindArea.cs ├── WorldPosition.cs ├── _BlockSpawnPointChecker.cs ├── _DataManager.cs ├── _EnemyBlockSpawner.cs ├── _PlankRotationController.cs ├── calcCenterPoint.cs ├── countdownTimer.cs ├── dash.cs ├── destroyer.cs ├── foreachReverse.cs ├── gametime.cs ├── leftRightTouch.cs ├── luckCalculator.cs ├── moveRect.cs ├── newArray.cs ├── shakeDetect.cs ├── smoothColorChange.cs ├── spawner.cs ├── steeringWheelControl.cs └── walkback.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.videoRecordSizes.txt: -------------------------------------------------------------------------------- 1 | Target FPS : 30 / 60 (recommended) 2 | 3 | Game View 4 | FHD - 1080 5 | Custom 6 | 4:5 (0,8) 7 | 8 | Game 9 | 864x1080 10 | -------------------------------------------------------------------------------- /ActivateManager.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | 6 | public class ActivateManager : MonoBehaviour 7 | { 8 | GameObject[] array; 9 | public float distance; 10 | 11 | // Update is called once per frame 12 | void Update() 13 | { 14 | GetInactiveInRadius(); 15 | } 16 | 17 | 18 | void GetInactiveInRadius() 19 | { 20 | foreach (GameObject obj in array) 21 | { 22 | if (obj) //destroyed? 23 | { 24 | if (Vector3.Distance(transform.position, obj.transform.position) < distance) 25 | { 26 | if (obj) //destroyed? 27 | { 28 | obj.SetActive(true); 29 | } 30 | } 31 | } 32 | } 33 | } 34 | 35 | private void OnDrawGizmos() 36 | { 37 | Gizmos.color = new Color32(183,0,0,32); 38 | Gizmos.DrawSphere(transform.position, distance); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Aiming.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class Aiming : MonoBehaviour 6 | { 7 | private Transform player; 8 | public float offset; 9 | 10 | // Start is called before the first frame update 11 | void Start() 12 | { 13 | player = GameObject.FindGameObjectWithTag("Player").transform; 14 | } 15 | 16 | // Update is called once per frame 17 | void Update() 18 | { 19 | Vector3 direction = player.position - transform.position; 20 | float rotZ = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; 21 | transform.rotation = Quaternion.Euler(0f, 0f, rotZ+offset); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /AlphaHitTest.cs: -------------------------------------------------------------------------------- 1 | public Image image; 2 | 3 | void Start() 4 | { 5 | //Any desired value between 0 and 1. 6 | image.alphaHitTestMinimumThreshold = 0.5f; 7 | } 8 | -------------------------------------------------------------------------------- /AlphaShader.shader: -------------------------------------------------------------------------------- 1 | Shader "AlphaShader" 2 | { 3 | Properties 4 | { 5 | _Distance ("Distance", Float) = 0 6 | _FadeStartDistance ("FadeStartDistance", Float) = 8 7 | _FadeCompleteDistance ("FadeCompleteDistance", Float) = 3 8 | } 9 | 10 | SubShader 11 | { 12 | Pass 13 | { 14 | AlphaToMask On 15 | 16 | CGPROGRAM 17 | #pragma vertex vert 18 | #pragma fragment frag 19 | 20 | #include "UnityCG.cginc" 21 | 22 | float _Distance; 23 | float _FadeStartDistance; 24 | float _FadeCompleteDistance; 25 | 26 | struct appdata 27 | { 28 | float4 vertex : POSITION; 29 | float2 uv : TEXCOORD0; 30 | }; 31 | 32 | struct v2f 33 | { 34 | float2 uv : TEXCOORD0; 35 | float4 vertex : SV_POSITION; 36 | }; 37 | 38 | v2f vert (appdata v) 39 | { 40 | v2f o; 41 | o.vertex = UnityObjectToClipPos(v.vertex); 42 | o.uv = v.uv; 43 | return o; 44 | } 45 | 46 | fixed4 frag (v2f i) : SV_Target 47 | { 48 | if (_Distance > _FadeStartDistance) { 49 | return fixed4(1, 1, 1, 1); // no change 50 | } 51 | if (_Distance > _FadeCompleteDistance) { 52 | return fixed4(1, 1, 1, (_Distance - _FadeCompleteDistance) / (_FadeStartDistance - _FadeCompleteDistance)); // fading out 53 | } 54 | return fixed4(1, 1, 1, 0); // faded out. Opacity = 0 55 | } 56 | ENDCG 57 | } 58 | } 59 | } 60 | 61 | -------------------------------------------------------------------------------- /ArrayResize.cs: -------------------------------------------------------------------------------- 1 | public void GroupResize (int Size, ref GameObject[] Group) 2 | { 3 | 4 | GameObject[] temp = new GameObject[Size]; 5 | for (int c = 1; c < Mathf.Min(Size, Group.Length); c++ ) { 6 | temp [c] = Group [c]; 7 | } 8 | Group = temp; 9 | } 10 | 11 | void Start () 12 | { 13 | GameObject[] Test = new GameObject[5]; 14 | Debug.Log (Test.Length); 15 | GroupResize (15, ref Test); 16 | Debug.Log (Test.Length); 17 | } 18 | -------------------------------------------------------------------------------- /AutoFov.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace gameOfName 6 | { 7 | public class ScreenSize : MonoBehaviour 8 | { 9 | public float aspectRatio; 10 | public float w = 9; 11 | public float h = 16; 12 | public float dFactor = 1; 13 | void Start() 14 | { 15 | aspectRatio = Camera.main.aspect; 16 | Camera.main.fieldOfView = (((60 * (w / h)) / dFactor) / aspectRatio); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /BackgroundAnimationRepeat.cs: -------------------------------------------------------------------------------- 1 | // Image Component have Unlit/Transparent material 2 | 3 | public float speedModDiv; 4 | public float dTime = 0; 5 | 6 | void Update() 7 | { 8 | dTime += Time.deltaTime / speedModDiv; 9 | GetComponent().materialForRendering.SetTextureOffset("_MainTex", new Vector2(dTime, 0)); 10 | } 11 | -------------------------------------------------------------------------------- /Ball.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class Ball : MonoBehaviour { 6 | 7 | public float lifeTime = 10f; 8 | public bool inWindZone = false; 9 | public GameObject windZone; 10 | 11 | Rigidbody rb; 12 | 13 | private void Start() 14 | { 15 | rb = GetComponent(); 16 | } 17 | 18 | // Update is called once per frame 19 | void Update() 20 | { 21 | if (lifeTime > 0) 22 | { 23 | lifeTime -= Time.deltaTime; 24 | if (lifeTime <= 0) 25 | { 26 | Destruction(); 27 | } 28 | } 29 | 30 | if (transform.position.y <= -20) 31 | { 32 | Destruction(); 33 | } 34 | } 35 | 36 | //private void FixedUpdate() 37 | //{ 38 | // if(inWindZone) { 39 | // rb.AddForce(windZone.GetComponent().direction * windZone.GetComponent().strength); 40 | // } 41 | //} 42 | 43 | //void OnTriggerEnter(Collider coll) { 44 | // if(coll.gameObject.tag == "windArea") { 45 | // windZone = coll.gameObject; 46 | // inWindZone = true; 47 | // } 48 | //} 49 | 50 | //void OnTriggerExit(Collider coll) { 51 | // if(coll.gameObject.tag == "windArea") { 52 | // inWindZone = false; 53 | // } 54 | //} 55 | 56 | void OnCollisionEnter(Collision coll) 57 | { 58 | if (coll.gameObject.name == "destroyer") 59 | { 60 | Destruction(); 61 | } 62 | } 63 | 64 | void Destruction() 65 | { 66 | Destroy(this.gameObject); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /BasicCameraZoom.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class BasicCameraZoom : MonoBehaviour { 6 | 7 | public float maxCamDistance = 10f; 8 | public float minCamFOV = 5f; 9 | public float fovSpeed = 1f; 10 | 11 | public Transform target; 12 | public Camera myCam; 13 | 14 | float initialFOV; 15 | 16 | // Use this for initialization 17 | void Start () { 18 | myCam = this.GetComponent(); 19 | initialFOV = myCam.fieldOfView; 20 | } 21 | 22 | void ResetFOV() { 23 | myCam.fieldOfView = initialFOV; 24 | } 25 | 26 | // Update is called once per frame 27 | void LateUpdate () { 28 | if (target == null) { 29 | ResetFOV(); 30 | } else { 31 | myCam.transform.LookAt(target); 32 | if (Vector3.Distance(transform.position, target.position) > maxCamDistance) { 33 | if (myCam.fieldOfView <= minCamFOV) { 34 | myCam.fieldOfView = minCamFOV; 35 | } else { 36 | myCam.fieldOfView -= fovSpeed; 37 | } 38 | } else if (Vector3.Distance(transform.position, target.position) < maxCamDistance) { 39 | myCam.fieldOfView += fovSpeed; 40 | if (myCam.fieldOfView >= initialFOV) { 41 | ResetFOV(); 42 | } 43 | } 44 | } 45 | } 46 | } 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /BehindLeftRightControl.cs: -------------------------------------------------------------------------------- 1 | var directionToEnemy = transform.position - player.transform.position; 2 | var projectionOnRight = Vector3.Dot(directionToEnemy, player.transform.right); 3 | if (projectionOnRight < 0) 4 | { 5 | Debug.Log("LEFT"); 6 | 7 | } 8 | else if (projectionOnRight > 0) 9 | { 10 | Debug.Log("RIGHT"); 11 | } 12 | -------------------------------------------------------------------------------- /BetterWaitForSeconds.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using UnityEngine; 3 | 4 | public static class BetterWaitForSeconds 5 | { 6 | private class WaitForSeconds : CustomYieldInstruction 7 | { 8 | private float waitUntil; 9 | public override bool keepWaiting 10 | { 11 | get 12 | { 13 | if( Time.time < waitUntil ) 14 | return true; 15 | 16 | Pool( this ); 17 | return false; 18 | } 19 | } 20 | 21 | public void Initialize( float seconds ) 22 | { 23 | waitUntil = Time.time + seconds; 24 | } 25 | } 26 | 27 | private class WaitForSecondsRealtime : CustomYieldInstruction 28 | { 29 | private float waitUntil; 30 | public override bool keepWaiting 31 | { 32 | get 33 | { 34 | if( Time.realtimeSinceStartup < waitUntil ) 35 | return true; 36 | 37 | Pool( this ); 38 | return false; 39 | } 40 | } 41 | 42 | public void Initialize( float seconds ) 43 | { 44 | waitUntil = Time.realtimeSinceStartup + seconds; 45 | } 46 | } 47 | 48 | private const int POOL_INITIAL_SIZE = 4; 49 | 50 | private static readonly Stack waitForSecondsPool; 51 | private static readonly Stack waitForSecondsRealtimePool; 52 | 53 | static BetterWaitForSeconds() 54 | { 55 | waitForSecondsPool = new Stack( POOL_INITIAL_SIZE ); 56 | waitForSecondsRealtimePool = new Stack( POOL_INITIAL_SIZE ); 57 | 58 | for( int i = 0; i < POOL_INITIAL_SIZE; i++ ) 59 | { 60 | waitForSecondsPool.Push( new WaitForSeconds() ); 61 | waitForSecondsRealtimePool.Push( new WaitForSecondsRealtime() ); 62 | } 63 | } 64 | 65 | public static CustomYieldInstruction Wait( float seconds ) 66 | { 67 | WaitForSeconds instance; 68 | if( waitForSecondsPool.Count > 0 ) 69 | instance = waitForSecondsPool.Pop(); 70 | else 71 | instance = new WaitForSeconds(); 72 | 73 | instance.Initialize( seconds ); 74 | return instance; 75 | } 76 | 77 | public static CustomYieldInstruction WaitRealtime( float seconds ) 78 | { 79 | WaitForSecondsRealtime instance; 80 | if( waitForSecondsRealtimePool.Count > 0 ) 81 | instance = waitForSecondsRealtimePool.Pop(); 82 | else 83 | instance = new WaitForSecondsRealtime(); 84 | 85 | instance.Initialize( seconds ); 86 | return instance; 87 | } 88 | 89 | private static void Pool( WaitForSeconds instance ) 90 | { 91 | waitForSecondsPool.Push( instance ); 92 | } 93 | 94 | private static void Pool( WaitForSecondsRealtime instance ) 95 | { 96 | waitForSecondsRealtimePool.Push( instance ); 97 | } 98 | } 99 | 100 | /* 101 | How To 102 | yield return BetterWaitForSeconds.Wait( 1f ); 103 | // or 104 | yield return BetterWaitForSeconds.WaitRealtime( 1f ); 105 | */ 106 | -------------------------------------------------------------------------------- /Blinker.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public class Blinker : MonoBehaviour { 4 | 5 | public Color highlightColor; 6 | 7 | private Renderer rend; 8 | private Color original; 9 | 10 | void Awake(){ 11 | rend = GetComponent(); 12 | original = rend.material.color; 13 | } 14 | 15 | public void Blink(){ 16 | rend.material.color = highlightColor; 17 | } 18 | 19 | void LateUpdate(){ 20 | rend.material.color += (original - rend.material.color)*Time.deltaTime*5; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Boomerang.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | public class Boomerang : MonoBehaviour 4 | { 5 | 6 | void Update() 7 | { 8 | if (Input.GetKeyDown(KeyCode.Space)) 9 | { 10 | StartCoroutine(Throw(28.0f, 11.0f, Camera.main.transform.forward, 4.0f)); 11 | } 12 | } 13 | 14 | IEnumerator Throw(float dist, float width, Vector3 direction, float time) 15 | { 16 | Vector3 pos = transform.position; 17 | float height = transform.position.y; 18 | Quaternion q = Quaternion.FromToRotation(Vector3.forward, direction); 19 | float timer = 0.0f; 20 | GetComponent().AddTorque(0.0f, 400.0f, 0.0f); 21 | while (timer < time) 22 | { 23 | float t = Mathf.PI * 2.0f * timer / time - Mathf.PI / 2.0f; 24 | float x = width * Mathf.Cos(t); 25 | float z = dist * Mathf.Sin(t); 26 | Vector3 v = new Vector3(x, height, z + dist); 27 | GetComponent().MovePosition(pos + (q * v)); 28 | timer += Time.deltaTime; 29 | yield return null; 30 | } 31 | 32 | GetComponent().angularVelocity = Vector3.zero; 33 | GetComponent().velocity = Vector3.zero; 34 | GetComponent().rotation = Quaternion.identity; 35 | GetComponent().MovePosition(pos); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /BoomerangEffect.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class BoomerangEffect : MonoBehaviour 5 | { 6 | public float duration = 1; // in seconds 7 | 8 | public Vector3 beginPoint = new Vector3(0, 0, 0); 9 | public Vector3 finalPoint = new Vector3(0, 0, 30); 10 | public Vector3 farPoint = new Vector3(0, 0, 0); 11 | 12 | public bool startAgain = false; 13 | 14 | private float startTime; 15 | 16 | void Start() 17 | { 18 | startTime = Time.time; 19 | } 20 | 21 | void Update() 22 | { 23 | if (startAgain) Start(); 24 | 25 | Vector3 center = (beginPoint + finalPoint) * 0.5F; 26 | center -= farPoint; 27 | 28 | Vector3 riseRelCenter = beginPoint - center; 29 | Vector3 setRelCenter = finalPoint - center; 30 | 31 | transform.position = Vector3.Slerp(riseRelCenter, setRelCenter, (Time.time - startTime) / duration); 32 | transform.position += center; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Bot.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | using UnityEngine.AI; //for NavMeshAgent 5 | 6 | [RequireComponent(typeof(NavMeshAgent))] 7 | public class Bot : MonoBehaviour 8 | { 9 | public float MinTime = 2; 10 | public float MaxTime = 5; 11 | public GameObject Ground = null; 12 | private NavMeshAgent nma = null; 13 | private Bounds bounds; 14 | 15 | private void Start() 16 | { 17 | nma = this.GetComponent(); 18 | bounds = Ground.GetComponent().bounds; 19 | } 20 | private void Update() 21 | { 22 | if (nma.hasPath == false || nma.remainingDistance < 1.0f) 23 | { 24 | float wait = Random.Range(MinTime, MaxTime); 25 | this.GetComponent().material.color = Color.red; 26 | Invoke("PickRandomDestination", wait); 27 | } 28 | } 29 | private void PickRandomDestination() 30 | { 31 | float rx = Random.Range(bounds.min.x, bounds.max.x); 32 | float rz = Random.Range(bounds.min.z, bounds.max.z); 33 | Vector3 rpos = new Vector3(rx, this.transform.position.y, rz); 34 | nma.SetDestination(rpos); 35 | this.GetComponent().material.color = Color.green; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /BounceObject.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class BounceObject : MonoBehaviour 5 | { 6 | public bool Move = true; ///gives you control in inspector to trigger it or not 7 | public Vector3 MoveVector = Vector3.up; //unity already supplies us with a readonly vector representing up and we are just chaching that into MoveVector 8 | public float MoveRange = 2.0f; //change this to increase/decrease the distance between the highest and lowest points of the bounce 9 | public float MoveSpeed = 0.5f; //change this to make it faster or slower 10 | 11 | private BounceObject bounceObject; //for caching this transform 12 | 13 | Vector3 startPosition; //used to cache the start position of the transform 14 | void Start() 15 | { 16 | bounceObject = this; 17 | startPosition = bounceObject.transform.position; 18 | } 19 | void Update() 20 | { 21 | if(Move) //bool is checked 22 | //See if you can work out whats going on here, for your own enjoyment 23 | bounceObject.transform.position = startPosition + MoveVector * (MoveRange * Mathf.Sin(Time.timeSinceLevelLoad * MoveSpeed)); 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /BoundsExtensions.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public static class BoundsExtensions 4 | { 5 | /// 6 | /// Calculates all corner positions of a bounding box 7 | /// 8 | /// Bounds input 9 | /// The corners in an array, the numeration starts at the bottom 10 | /// Indices of the corners 11 | /// 7-------6 12 | /// /| /| 13 | /// / | / | 14 | /// 4--|----5 | 15 | /// | 3----|--2 16 | /// | / | / 17 | /// 0-------1 18 | /// 19 | public static Vector3[] GetCorners(this Bounds bounds) 20 | { 21 | Vector3[] corners = new Vector3[8]; 22 | var center = bounds.center; 23 | var extents = bounds.extents; 24 | 25 | // Bottom 26 | corners[0] = center + new Vector3(-extents.x, -extents.y, -extents.z); 27 | corners[1] = center + new Vector3(+extents.x, -extents.y, -extents.z); 28 | corners[2] = center + new Vector3(+extents.x, -extents.y, +extents.z); 29 | corners[3] = center + new Vector3(-extents.x, -extents.y, +extents.z); 30 | // Top 31 | corners[4] = center + new Vector3(-extents.x, +extents.y, -extents.z); 32 | corners[5] = center + new Vector3(+extents.x, +extents.y, -extents.z); 33 | corners[6] = center + new Vector3(+extents.x, +extents.y, +extents.z); 34 | corners[7] = center + new Vector3(-extents.x, +extents.y, +extents.z); 35 | 36 | return corners; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Break.cs: -------------------------------------------------------------------------------- 1 | public class Break : MonoBehaviour { 2 | public GameObject fractured; 3 | public float breakForce; 4 | 5 | void Update(){ 6 | if (Input.GetKeyDown("f")) 7 | BreakTheThing(); 8 | } 9 | 10 | public void BreakTheThing(){ 11 | GameObject frac = Instantiate(fractured, transform.position, transform.rotation); 12 | 13 | foreach(Rigidbody rb in frac.GetComponentsInChildren()){ 14 | Vector3 force = (rb.transform.position - transform.position).normalized * breakForce; 15 | rb.AddForce(force); 16 | } 17 | Destroy(gameObject); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /BridgeBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | /* 6 | * Construct a bridge as a tracked object moves across it. 7 | * Created as a part of World of Zero 8 | * See it in action here: https://youtu.be/GaQBLD7bGCM 9 | */ 10 | public class BridgeBuilder : MonoBehaviour 11 | { 12 | public Transform trackedObject; 13 | 14 | public Transform startPoint; 15 | public Transform endPoint; 16 | 17 | public GameObject bridgePrefab; 18 | public float length = 1; 19 | public float width = 1; 20 | public int columnWidth = 1; 21 | 22 | private Vector3 forwardVector; 23 | private Vector3 lastPoint; 24 | 25 | // Use this for initialization 26 | void Start () 27 | { 28 | lastPoint = startPoint.position; 29 | forwardVector = (endPoint.position - startPoint.position).normalized; 30 | 31 | //for (var point = startPoint.position; 32 | // Vector3.Dot(forwardVector, endPoint.position - point) >= 0; 33 | // point += forwardVector * length) 34 | //{ 35 | // Instantiate(bridgePrefab, point, Quaternion.LookRotation(forwardVector)); 36 | //} 37 | } 38 | 39 | // Update is called once per frame 40 | void Update () { 41 | //if (Vector3.Dot(forwardVector, endPoint.position - lastPoint) >= 0) 42 | //{ 43 | // Destroy(this); 44 | //} 45 | 46 | var point = lastPoint - forwardVector; 47 | var endToPoint = point - endPoint.position; 48 | var playerToPoint = point - trackedObject.position; 49 | 50 | if (Vector3.Dot(endToPoint, playerToPoint) > 0) 51 | { 52 | Instantiate(bridgePrefab, lastPoint, Quaternion.LookRotation(forwardVector)); 53 | lastPoint += forwardVector * length; 54 | } 55 | } 56 | 57 | void OnDrawGizmos() 58 | { 59 | Gizmos.color = Color.green; 60 | Gizmos.DrawWireSphere(startPoint.position, 0.25f); 61 | Gizmos.color = Color.red; 62 | Gizmos.DrawWireSphere(endPoint.position, 0.25f); 63 | 64 | Gizmos.color = Color.white; 65 | Gizmos.DrawLine(startPoint.position, endPoint.position); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /BulletMLPoolLink.cs: -------------------------------------------------------------------------------- 1 | public class BulletPoolScript : MonoBehaviour 2 | { 3 | void Start() 4 | { 5 | var bulletManager = FindObjectOfType(); 6 | if (bulletManager != null) 7 | { 8 | bulletManager.OnBulletSpawned += OnBulletSpawned; 9 | bulletManager.OnBulletDestroyed += OnBulletDestroyed; 10 | } 11 | } 12 | 13 | BulletScript OnBulletSpawned(BulletObject bullet, string bulletName) 14 | { 15 | // Get a GameObject from the pool 16 | // bulletName and bullet can help you identify the bullet you want 17 | // TODO: Your pool here 18 | GameObject go = MyPool.Get(); 19 | 20 | // Make sure this GameObject has a BulletScript and return it 21 | // BulletScript can be added on the fly, there is no special parameter to pass 22 | 23 | BulletScript bulletScript = go.GetComponent(); 24 | if(bulletScript == null) 25 | { 26 | bulletScript = go.AddComponent(); 27 | } 28 | 29 | return bulletScript; 30 | } 31 | 32 | void OnBulletDestroyed(GameObject bullet) 33 | { 34 | // Recycle your GameObject 35 | // 1/ If you need the label, you can retrieve it this way 36 | BulletScript bulletScript = bullet.GetComponent(); 37 | if (bulletScript != null) 38 | { 39 | BulletPool pool = null; 40 | string bulletName = bulletScript.Bullet.Label.ToLower(); 41 | 42 | // TODO: Your pool here 43 | MyPool.Recycle(bulletScript); 44 | } 45 | 46 | // 2/ Otherwise you have a direct reference to the bullet's GameObject 47 | // TODO: Your pool here 48 | MyPool.Recycle(bullet); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /CamFollow.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class CamFollow : MonoBehaviour 6 | { 7 | public Transform target; 8 | public Vector3 followOffset; 9 | public float lookAheadDst = 10; 10 | public float smoothTime = .1f; 11 | public float rotSmoothSpeed = 3; 12 | 13 | Vector3 smoothV; 14 | 15 | 16 | void LateUpdate() 17 | { 18 | Vector3 targetPos = target.position + target.forward * followOffset.z + target.up * followOffset.y + target.right * followOffset.x; 19 | transform.position = Vector3.SmoothDamp(transform.position, targetPos, ref smoothV, smoothTime); 20 | 21 | Quaternion rot = transform.rotation; 22 | transform.LookAt(target.position + target.forward * lookAheadDst); 23 | Quaternion targetRot = transform.rotation; 24 | 25 | transform.rotation = Quaternion.Slerp(rot,targetRot,Time.deltaTime * rotSmoothSpeed); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CameraMovement.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public class CameraMovement : MonoBehaviour { 4 | 5 | public float followSpeed; 6 | 7 | public Vector3 offset; 8 | private Vector3 refVelocity; 9 | 10 | public Transform target; 11 | 12 | void FixedUpdate() { 13 | 14 | Vector3 desiredPos = target.position + offset; 15 | Vector3 smoothedPos = Vector3.SmoothDamp( 16 | 17 | transform.position, desiredPos, ref refVelocity, 18 | followSpeed * Time.deltaTime 19 | 20 | ); 21 | 22 | transform.position = smoothedPos; 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /CameraShaker.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class CameraShaker : MonoBehaviour { 6 | 7 | public float power = 0.7f; 8 | public float duration = 1.0f; 9 | public Transform camera; 10 | public float slowDownAmount = 1.0f; 11 | public bool shouldShake; 12 | 13 | Vector3 startPosition; 14 | float initialDuration; 15 | 16 | // Use this for initialization 17 | void Start () { 18 | camera = Camera.main.transform; 19 | startPosition = camera.localPosition; 20 | initialDuration = duration; 21 | } 22 | 23 | // Update is called once per frame 24 | void Update () { 25 | if(shouldShake) 26 | { 27 | if(duration > 0) 28 | { 29 | camera.localPosition = startPosition + Random.insideUnitSphere * power; 30 | duration -= Time.deltaTime * slowDownAmount; 31 | } 32 | else 33 | { 34 | shouldShake = false; 35 | duration = initialDuration; 36 | camera.localPosition = startPosition; 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /CenterOfMass.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | [RequireComponent(typeof(Rigidbody))] 4 | public class CenterOfMass : MonoBehaviour 5 | { 6 | public Vector3 _localCenterOfMass; 7 | 8 | private void Awake() 9 | { 10 | SetCenterOfMass(); 11 | Destroy(this); 12 | } 13 | 14 | void SetCenterOfMass() 15 | { 16 | gameObject.GetComponent().centerOfMass = _localCenterOfMass; 17 | } 18 | 19 | private void OnDrawGizmosSelected() 20 | { 21 | Vector3 worldCenterOfMass = transform.TransformPoint(_localCenterOfMass); 22 | Gizmos.color = Color.cyan; 23 | Gizmos.DrawSphere(transform.TransformPoint(_localCenterOfMass), 0.1f); 24 | Gizmos.DrawLine(worldCenterOfMass + Vector3.up, worldCenterOfMass - Vector3.up); 25 | Gizmos.DrawLine(worldCenterOfMass + Vector3.forward, worldCenterOfMass - Vector3.forward); 26 | Gizmos.DrawLine(worldCenterOfMass + Vector3.right, worldCenterOfMass - Vector3.right); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ChangeCameraTargets.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class ChangeCameraTargets : MonoBehaviour { 6 | 7 | public Transform target; 8 | public float speed = 1f; 9 | 10 | int randomTarget; 11 | Quaternion newRot; 12 | Vector3 relPos; 13 | 14 | // Update is called once per frame 15 | void Update () { 16 | if (target == null) { 17 | GetNewTarget(); 18 | } else { 19 | relPos = target.position - transform.position; 20 | newRot = Quaternion.LookRotation(relPos); 21 | transform.rotation = Quaternion.RotateTowards(transform.rotation, newRot, Time.time * speed); 22 | } 23 | } 24 | 25 | void GetNewTarget() { 26 | GameObject[] possibleTargets; 27 | possibleTargets = GameObject.FindGameObjectsWithTag("ball"); 28 | if(possibleTargets.Length > 0) { 29 | randomTarget = Random.Range(0, possibleTargets.Length); 30 | target = possibleTargets[randomTarget].transform; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /CinemachinePathShape.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using Cinemachine; 3 | using Waypoint = Cinemachine.CinemachineSmoothPath.Waypoint; 4 | 5 | public class CinemachinePathShape : MonoBehaviour 6 | { 7 | public CinemachineSmoothPath path; 8 | 9 | [Space] 10 | 11 | [Range(2, 32)] 12 | public int points = 16; 13 | [Range(1f, 50f)] 14 | public float radius = 5f; 15 | [Range(0f, 360f)] 16 | public float startAngle = 0; 17 | [Range(15f, 360f)] 18 | public float endAngle = 360f; 19 | [Range(0f, 30f)] 20 | public float elevation = 0f; 21 | 22 | private Waypoint[] m_Waypoints = new Waypoint[0]; 23 | 24 | private void OnValidate() 25 | { 26 | if (!path) path = this.GetComponent(); 27 | if (!path) return; 28 | 29 | Apply(); 30 | } 31 | 32 | public void Apply() 33 | { 34 | m_Waypoints = new Waypoint[points]; 35 | 36 | float angle = startAngle; 37 | float length = endAngle - startAngle; 38 | for (int i = 0; i < points; i++) 39 | { 40 | float t = (float)i / (float)points; 41 | 42 | m_Waypoints[i].position = new Vector3( 43 | Mathf.Sin(Mathf.Deg2Rad * angle) * (radius * 0.5f), 44 | t * (elevation * 0.5f), 45 | Mathf.Cos(Mathf.Deg2Rad * angle) * (radius * 0.5f)); 46 | 47 | angle += (length / (float)points); 48 | } 49 | 50 | path.m_Waypoints = m_Waypoints; 51 | path.InvalidateDistanceCache(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /CircularLoadingDash.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using UnityEngine.UI; 4 | 5 | public class CircularLoadingDash : MonoBehaviour { 6 | 7 | public Image circularSilder; //Drag the circular image i.e Slider in our case 8 | public float time; //In how much time the progress bar will fill/empty 9 | 10 | public static bool resetTimer = false; 11 | public static bool dashAvailable = false; 12 | 13 | void Start() 14 | { 15 | circularSilder.fillAmount = 0f; // Initally progress bar is empty 16 | } 17 | void Update() 18 | { 19 | circularSilder.fillAmount += Time.deltaTime / time; 20 | 21 | if (resetTimer) 22 | { 23 | dashAvailable = false; 24 | circularSilder.fillAmount = 0f; 25 | resetTimer = false; 26 | } 27 | 28 | if(circularSilder.fillAmount.Equals(1f)) 29 | { 30 | dashAvailable = true; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /ClickerRunner.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using uClicker; 3 | using UnityEngine; 4 | 5 | public class ClickerRunner : MonoBehaviour 6 | { 7 | public ClickerManager Manager; 8 | 9 | // Use this for initialization 10 | IEnumerator Start() 11 | { 12 | Manager.LoadProgress(); 13 | while (Application.isPlaying) 14 | { 15 | yield return new WaitForSecondsRealtime(1); 16 | Manager.Tick(); 17 | Manager.SaveProgress(); 18 | PlayerPrefs.Save(); 19 | } 20 | } 21 | 22 | private void OnDestroy() 23 | { 24 | Manager.SaveProgress(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /CoinK.cs: -------------------------------------------------------------------------------- 1 | if (money >= 1000) 2 | { 3 | moneyText.text = "+ " + (money/1000).ToString("0.0") + "k $"; 4 | } 5 | else 6 | { 7 | moneyText.text = "+ " + money.ToString() + " $"; 8 | } 9 | -------------------------------------------------------------------------------- /ColliderToFit.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using UnityEditor; 3 | 4 | 5 | public class ColliderToFit : MonoBehaviour 6 | { 7 | [MenuItem("My Tools/Collider/Fit to Children")] 8 | static void FitToChildren() 9 | { 10 | foreach (GameObject rootGameObject in Selection.gameObjects) 11 | { 12 | if (!(rootGameObject.GetComponent() is BoxCollider)) 13 | continue; 14 | 15 | bool hasBounds = false; 16 | Bounds bounds = new Bounds(Vector3.zero, Vector3.zero); 17 | 18 | for (int i = 0; i < rootGameObject.transform.childCount; ++i) 19 | { 20 | Renderer childRenderer = rootGameObject.transform.GetChild(i).GetComponent(); 21 | if (childRenderer != null) 22 | { 23 | if (hasBounds) 24 | { 25 | bounds.Encapsulate(childRenderer.bounds); 26 | } 27 | else 28 | { 29 | bounds = childRenderer.bounds; 30 | hasBounds = true; 31 | } 32 | } 33 | } 34 | 35 | BoxCollider collider = (BoxCollider)rootGameObject.GetComponent(); 36 | collider.center = bounds.center - rootGameObject.transform.position; 37 | collider.size = bounds.size; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /ColorLerper.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class ColorLerper : MonoBehaviour { 6 | 7 | public float speed = 1.0f; 8 | public Color startColor; 9 | public Color endColor; 10 | public bool repeatable = false; 11 | float startTime; 12 | 13 | // Use this for initialization 14 | void Start () { 15 | startTime = Time.time; 16 | } 17 | 18 | // Update is called once per frame 19 | void Update () { 20 | if (!repeatable) 21 | { 22 | float t = (Time.time - startTime) * speed; 23 | GetComponent().material.color = Color.Lerp(startColor, endColor, t); 24 | } 25 | else 26 | { 27 | float t = (Mathf.Sin(Time.time - startTime) * speed); 28 | GetComponent().material.color = Color.Lerp(startColor, endColor, t); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /CompareLists.cs: -------------------------------------------------------------------------------- 1 | public static bool CompareLists(List aListA, List aListB) 2 | { 3 | if (aListA == null || aListB == null || aListA.Count != aListB.Count) 4 | return false; 5 | if (aListA.Count == 0) 6 | return true; 7 | Dictionary lookUp = new Dictionary(); 8 | for (int i = 0; i < aListA.Count; i++) 9 | { 10 | int count = 0; 11 | if (!lookUp.TryGetValue(aListA[i], out count)) 12 | { 13 | lookUp.Add(aListA[i], 1); 14 | continue; 15 | } 16 | lookUp[aListA[i]] = count + 1; 17 | } 18 | for (int i = 0; i < aListB.Count; i++) 19 | { 20 | int count = 0; 21 | if (!lookUp.TryGetValue(aListB[i], out count)) 22 | { 23 | return false; 24 | } 25 | count--; 26 | if (count <= 0) 27 | lookUp.Remove(aListB[i]); 28 | else 29 | lookUp[aListB[i]] = count; 30 | } 31 | return lookUp.Count == 0; 32 | } 33 | -------------------------------------------------------------------------------- /ComponentUtil.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections; 4 | using System.Collections.Generic; 5 | using System.Reflection; 6 | 7 | using UnityEngine; 8 | 9 | namespace Utils 10 | { 11 | 12 | // http://answers.unity3d.com/questions/458207/copy-a-component-at-runtime.html 13 | // http://stackoverflow.com/questions/10261824/how-can-i-get-all-constants-of-a-type-by-reflection 14 | public class ComponentUtil 15 | { 16 | 17 | public static T CopyComponent(T original, GameObject destination) where T : Component 18 | { 19 | System.Type type = original.GetType(); 20 | 21 | var dst = destination.GetComponent(type) as T; 22 | if (!dst) dst = destination.AddComponent(type) as T; 23 | 24 | var fields = GetAllFields(type); 25 | foreach (var field in fields) 26 | { 27 | if (field.IsStatic) continue; 28 | field.SetValue(dst, field.GetValue(original)); 29 | } 30 | 31 | var props = type.GetProperties(); 32 | foreach (var prop in props) 33 | { 34 | if (!prop.CanWrite || !prop.CanWrite || prop.Name == "name") continue; 35 | prop.SetValue(dst, prop.GetValue(original, null), null); 36 | } 37 | 38 | return dst as T; 39 | } 40 | 41 | public static IEnumerable GetAllFields(System.Type t) 42 | { 43 | if (t == null) 44 | { 45 | return Enumerable.Empty(); 46 | } 47 | 48 | BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | 49 | BindingFlags.Static | BindingFlags.Instance | 50 | BindingFlags.DeclaredOnly; 51 | return t.GetFields(flags).Concat(GetAllFields(t.BaseType)); 52 | } 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /ContinueCoroutine.cs: -------------------------------------------------------------------------------- 1 | // example script for restarting Coroutine after gameobject was disabled (and continue from previous timer value) 2 | 3 | 4 | using System.Collections; 5 | using UnityEngine; 6 | using UnityEngine.UI; 7 | 8 | public class ContinueCoroutine : MonoBehaviour 9 | { 10 | public float duration = 5f; 11 | 12 | Image image; 13 | 14 | bool isRunning = true; 15 | 16 | float timer = 0; 17 | float oldtimer = 0; 18 | 19 | private void Awake() 20 | { 21 | image = GetComponent(); 22 | } 23 | 24 | // keep timer values on disable 25 | private void OnDisable() 26 | { 27 | oldtimer = timer; 28 | isRunning = false; 29 | } 30 | 31 | // start coroutine on enable 32 | private void OnEnable() 33 | { 34 | timer = oldtimer; 35 | isRunning = true; 36 | StartCoroutine(CustomUpdater()); 37 | } 38 | 39 | // coroutine loop 40 | IEnumerator CustomUpdater() 41 | { 42 | while (true) 43 | { 44 | for (timer = oldtimer; timer < duration; timer += Time.deltaTime) // this works, since we keep reference to old timer 45 | // for (float timer = 0; timer < duration; timer += Time.deltaTime) // this doesnt work, because restarting coroutine would reset timer value 46 | { 47 | image.color = Color.Lerp(Color.red, Color.green, timer / duration); 48 | yield return 0; 49 | } 50 | oldtimer = 0; 51 | } 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /CreateCube.cs: -------------------------------------------------------------------------------- 1 | //modified from http://ilkinulas.github.io/development/unity/2016/04/30/cube-mesh-in-unity3d.html 2 | //modification adds the ability to specify an offset and size 3 | void CreateCube(Vector3 offset, Vector3 size) { 4 | 5 | Vector3[] vertices = { 6 | new Vector3 (0, 0, 0), 7 | new Vector3 (1, 0, 0), 8 | new Vector3 (1, 1, 0), 9 | new Vector3 (0, 1, 0), 10 | new Vector3 (0, 1, 1), 11 | new Vector3 (1, 1, 1), 12 | new Vector3 (1, 0, 1), 13 | new Vector3 (0, 0, 1), 14 | }; 15 | 16 | for(int i=0; i < vertices.Length; i++) { 17 | vertices[i].Scale(size); 18 | vertices[i] += offset; 19 | } 20 | 21 | int[] triangles = { 22 | 0, 2, 1, //face front 23 | 0, 3, 2, 24 | 2, 3, 4, //face top 25 | 2, 4, 5, 26 | 1, 2, 5, //face right 27 | 1, 5, 6, 28 | 0, 7, 4, //face left 29 | 0, 4, 3, 30 | 5, 4, 7, //face back 31 | 5, 7, 6, 32 | 0, 6, 7, //face bottom 33 | 0, 1, 6 34 | }; 35 | 36 | Mesh mesh = GetComponent().mesh; 37 | 38 | mesh.Clear(); 39 | 40 | mesh.vertices = vertices; 41 | mesh.triangles = triangles; 42 | 43 | mesh.RecalculateNormals(); 44 | } 45 | -------------------------------------------------------------------------------- /CreateEnemiesAroundPoint.cs: -------------------------------------------------------------------------------- 1 | public int groupCount = 1; 2 | public float spawnRadius = 1f; 3 | 4 | usage: CreateEnemiesAroundPoint(groupCount, gameObject.transform.position, spawnRadius); 5 | 6 | public void CreateEnemiesAroundPoint(int num, Vector3 point, float radius) 7 | { 8 | for (int i = 0; i < num; i++) 9 | { 10 | 11 | /* Distance around the circle */ 12 | var radians = 2 * Mathf.PI / num * i; 13 | 14 | /* Get the vector direction */ 15 | var vertrical = Mathf.Sin(radians); 16 | var horizontal = Mathf.Cos(radians); 17 | 18 | var spawnDir = new Vector3(horizontal, 0, vertrical); 19 | 20 | /* Get the spawn position */ 21 | var spawnPos = point + spawnDir * radius; // Radius is just the distance away from the point 22 | 23 | /* Now spawn */ 24 | var enemy = Instantiate(runnerMan, spawnPos, Quaternion.Euler(0f, 90f, 0f)) as GameObject; 25 | enemy.transform.SetParent(gameObject.transform); 26 | 27 | /* Rotate the enemy to face towards player */ 28 | //enemy.transform.LookAt(point); 29 | 30 | /* Adjust height */ 31 | //enemy.transform.Translate(new Vector3(0, enemy.transform.localScale.y / 2, 0)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /CubeCut.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public class CubeCut : MonoBehaviour { 4 | public static bool Cut(Transform victim,Vector3 _pos) 5 | { 6 | Vector3 pos = new Vector3(_pos.x, victim.position.y, victim.position.z); 7 | Vector3 victimScale = victim.localScale; 8 | float distance = Vector3.Distance(victim.position, pos); 9 | if (distance >= victimScale.x/2) return false; 10 | 11 | Vector3 leftPoint = victim.position - Vector3.right * victimScale.x/2; 12 | Vector3 rightPoint = victim.position + Vector3.right * victimScale.x/2; 13 | Material mat = victim.GetComponent().material; 14 | Destroy(victim.gameObject); 15 | 16 | GameObject rightSideObj = GameObject.CreatePrimitive(PrimitiveType.Cube); 17 | rightSideObj.transform.position = (rightPoint + pos) /2; 18 | float rightWidth = Vector3.Distance(pos,rightPoint); 19 | rightSideObj.transform.localScale = new Vector3( rightWidth ,victimScale.y ,victimScale.z ); 20 | rightSideObj.AddComponent().mass = 100f; 21 | rightSideObj.GetComponent().material = mat; 22 | 23 | GameObject leftSideObj = GameObject.CreatePrimitive(PrimitiveType.Cube); 24 | leftSideObj.transform.position = (leftPoint + pos)/2; 25 | float leftWidth = Vector3.Distance(pos,leftPoint); 26 | leftSideObj.transform.localScale = new Vector3( leftWidth ,victimScale.y ,victimScale.z ); 27 | leftSideObj.AddComponent().mass = 100f; 28 | leftSideObj.GetComponent().material = mat; 29 | 30 | return true; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /DeleteAllChildObjects.cs: -------------------------------------------------------------------------------- 1 | public IEnumerator DoDeleteAll() 2 | { 3 | while (Holder.transform.childCount > 0) 4 | { 5 | var items = GameObject.FindGameObjectsWithTag("YOUR_TAG"); 6 | foreach (var item in items) 7 | { 8 | Destroy(item ); 9 | } 10 | yield return new WaitForSeconds(0.001f); 11 | } 12 | } 13 | 14 | #################### 15 | 16 | public static class TransformEx { 17 | public static Transform Clear(this Transform transform) 18 | { 19 | foreach (Transform child in transform) { 20 | GameObject.Destroy(child.gameObject); 21 | } 22 | return transform; 23 | } 24 | } 25 | 26 | ##################### 27 | 28 | var children = new List(); 29 | foreach (Transform child in transform) children.Add(child.gameObject); 30 | children.ForEach(child => Destroy(child)); 31 | 32 | ###################### /* use this! */ 33 | 34 | foreach (Transform child in TextHolder.transform) { 35 | GameObject.Destroy(child.gameObject); 36 | } 37 | -------------------------------------------------------------------------------- /DestroyAfterTime.cs: -------------------------------------------------------------------------------- 1 | public class DestroyAfterTime : MonoBehaviour 2 | { 3 | [SerializeField] private float duration = 5f; 4 | 5 | private void Start() => Destroy(gameObject, duration); 6 | } 7 | -------------------------------------------------------------------------------- /DrawCapsule.cs: -------------------------------------------------------------------------------- 1 | /* DRAW CAPSULE BETWEEN TWO POINTS */ 2 | 3 | using UnityEngine; 4 | 5 | public class DrawCapsule : MonoBehaviour { 6 | public Transform CapsuleStart; 7 | public Transform CapsuleEnd; 8 | public float RadiusStart = 1f, RadiusEnd = 1f; //Differing starting/ending radii is experimental 9 | public Mesh SphereMesh; 10 | public Material CapsuleMaterial; 11 | 12 | private Mesh capsuleMesh; 13 | private Vector3[] sphereVerts; 14 | private Vector3[] capsuleVerts; 15 | private Vector3[] capsuleNormals; 16 | private Vector3 midPoint; 17 | private float scale; 18 | private float prevRadiusStart = 1f, prevRadiusEnd = 1f; 19 | 20 | void Start() { 21 | capsuleMesh = Instantiate(SphereMesh); 22 | capsuleMesh.MarkDynamic(); 23 | sphereVerts = SphereMesh.vertices; 24 | capsuleVerts = new Vector3[sphereVerts.Length]; 25 | capsuleNormals = new Vector3[sphereVerts.Length]; 26 | } 27 | 28 | void Update() { 29 | if (CapsuleStart.hasChanged || CapsuleEnd.hasChanged || RadiusStart != prevRadiusStart || RadiusEnd != prevRadiusEnd) { 30 | UpdateCapsuleMesh(); 31 | prevRadiusStart = RadiusStart; 32 | prevRadiusEnd = RadiusEnd; 33 | CapsuleStart.hasChanged = false; 34 | CapsuleEnd.hasChanged = false; 35 | } 36 | 37 | Graphics.DrawMesh(capsuleMesh, Matrix4x4.TRS(midPoint, Quaternion.identity, Vector3.one * scale), CapsuleMaterial, 0); 38 | } 39 | 40 | void UpdateCapsuleMesh() { 41 | scale = ((CapsuleStart.position - CapsuleEnd.position).magnitude + (Mathf.Max(RadiusStart, RadiusEnd) * 10f)); //2f is minimum, but 10f gets better vertex distribution on the Caps 42 | midPoint = (CapsuleStart.position + CapsuleEnd.position) * 0.5f; 43 | 44 | float invScale = 1f / scale; 45 | Vector3 localStart = (CapsuleStart.position - midPoint) * invScale; 46 | Vector3 localEnd = (CapsuleEnd.position - midPoint) * invScale; 47 | 48 | for (int i = 0; i < sphereVerts.Length; i++) { 49 | float bicapsuleTime = 0f; 50 | capsuleVerts[i] = sphereVerts[i].closestPointToBiCapsule(localStart, localEnd, RadiusStart * invScale, RadiusEnd * invScale, out bicapsuleTime); 51 | capsuleNormals[i] = sphereVerts[i] - Vector3.Lerp(localStart, localEnd, bicapsuleTime); 52 | } 53 | 54 | capsuleMesh.vertices = capsuleVerts; 55 | capsuleMesh.normals = capsuleNormals; 56 | capsuleMesh.UploadMeshData(false); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Enlarger.cs: -------------------------------------------------------------------------------- 1 | public class Enlarger : MonoBehaviour { 2 | 3 | public GameObject Player; 4 | 5 | void OnTriggerEnter(Collider other) 6 | { 7 | print("Collision detected with trigger object " + other.name); 8 | PlayerComponent playerComponent = other.gameObject.GetComponent (); 9 | 10 | //checking if collided with player 11 | if (playerComponent) { 12 | StartCoroutine(ScaleOverTime(1)); 13 | } 14 | } 15 | 16 | IEnumerator ScaleOverTime(float time) 17 | { 18 | Vector3 originalScale = Player.transform.localScale; 19 | Vector3 destinationScale = new Vector3(2.0f, 2.0f, 2.0f); 20 | 21 | float currentTime = 0.0f; 22 | 23 | do 24 | { 25 | Player.transform.localScale = Vector3.Lerp(originalScale, destinationScale, currentTime / time); 26 | currentTime += Time.deltaTime; 27 | yield return null; 28 | } while (currentTime <= time); 29 | 30 | Destroy(gameObject); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /EnumRandom.cs: -------------------------------------------------------------------------------- 1 | //GameManager => 2 | // [Header("Color Settings")] 3 | // public Color32[] itemColors; 4 | 5 | using System.Collections; 6 | using System.Collections.Generic; 7 | using UnityEngine; 8 | 9 | public class CubeItem : MonoBehaviour 10 | { 11 | public enum CubeColor 12 | { 13 | Color0 = 0, 14 | Color1 = 1, 15 | Color2 = 2, 16 | Color3 = 3 17 | } 18 | [Header("Color Settings")] 19 | public CubeColor m_CubeColorType = CubeColor.Color1; 20 | public MeshRenderer m_meshRenderer; 21 | 22 | void Start() 23 | { 24 | m_CubeColorType = (CubeColor)Random.Range(0, Enum.GetValues(typeof(CubeColor)).Length); 25 | Debug.Log(m_CubeColorType); 26 | 27 | switch (m_CubeColorType) 28 | { 29 | case CubeColor.Color0: 30 | m_meshRenderer.material.SetColor("_Color", GameManager.instance.itemColors[0]); 31 | break; 32 | case CubeColor.Color1: 33 | m_meshRenderer.material.SetColor("_Color", GameManager.instance.itemColors[1]); 34 | break; 35 | case CubeColor.Color2: 36 | m_meshRenderer.material.SetColor("_Color", GameManager.instance.itemColors[2]); 37 | break; 38 | case CubeColor.Color3: 39 | m_meshRenderer.material.SetColor("_Color", GameManager.instance.itemColors[3]); 40 | break; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /EnumVal.cs: -------------------------------------------------------------------------------- 1 | public class MagicEffect 2 | { 3 | public string Name {get;set;} 4 | public int SpellPower {get;set;} 5 | public float Duration {get;set;} 6 | // Damagetype ...etc ... 7 | 8 | public MagicEffect(string name, int spellpower, float duration) 9 | { 10 | Name = name; 11 | SpellPower = spellpower; 12 | Duration = duration; 13 | } 14 | 15 | public static MagicEffect Ignite = new MagicEffect("Ignite", 30, 0.5); 16 | public static MagicEffect Shock = new MagicEffect("Shock", 40, 1.5); 17 | public static MagicEffect AcidSpray = new MagicEffect("AcidSpray", 30, 0.5); 18 | } 19 | 20 | 21 | 22 | public void LoseHP() 23 | { 24 | _health -= MagicEffect.Ignite.SpellPower; 25 | 26 | 27 | if(_health <= 0) 28 | { 29 | _health = 0; 30 | 31 | Debug.Log ("Player_2 has died."); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /EventsUnityEvents.cs: -------------------------------------------------------------------------------- 1 | Collectible.cs 2 | 3 | using System; 4 | using UnityEngine; 5 | 6 | public class Collectible : MonoBehaviour 7 | { 8 | public event Action OnPickup; 9 | 10 | void OnTriggerEnter2D(Collider2D other) 11 | { 12 | var player = other.GetComponent(); 13 | if (player != null) 14 | { 15 | OnPickup?.Invoke(this); 16 | 17 | gameObject.SetActive(false); 18 | } 19 | } 20 | } 21 | 22 | Collector.cs 23 | 24 | using System.Collections.Generic; 25 | using System.Linq; 26 | using TMPro; 27 | using UnityEngine; 28 | using UnityEngine.Events; 29 | 30 | public class Collector : MonoBehaviour 31 | { 32 | [SerializeField] TMP_Text _text; 33 | [SerializeField] List _gatherables; 34 | 35 | [SerializeField] UnityEvent OnCompleteEvent; 36 | 37 | List _collectiblesRemaining; 38 | 39 | 40 | void OnEnable() 41 | { 42 | _collectiblesRemaining = new List(_gatherables); 43 | 44 | foreach (var collectible in _collectiblesRemaining) 45 | collectible.OnPickup += HandlePickup; // Registering for the OnPickup event on Collectible 46 | 47 | UpdateText(); 48 | } 49 | 50 | void HandlePickup(Collectible collectible) 51 | { 52 | _collectiblesRemaining.Remove(collectible); 53 | UpdateText(); 54 | 55 | if (_collectiblesRemaining.Count == 0) 56 | OnCompleteEvent.Invoke(); 57 | } 58 | 59 | void UpdateText() 60 | { 61 | _text.SetText($"{_collectiblesRemaining.Count} more..."); 62 | if (_collectiblesRemaining.Count == 0 || _collectiblesRemaining.Count == _gatherables.Count) 63 | _text.enabled = false; 64 | else 65 | _text.enabled = true; 66 | } 67 | 68 | [ContextMenu("AutoFill Collectibles")] 69 | void AutoFillCollectibles() 70 | { 71 | _gatherables = GetComponentsInChildren() 72 | .Where(t=> t.name.ToLower().Contains("red")) 73 | .ToList(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Explosion.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class Explosion : MonoBehaviour { 6 | 7 | public float cubeSize = 0.2f; 8 | public int cubesInRow = 5; 9 | 10 | float cubesPivotDistance; 11 | Vector3 cubesPivot; 12 | 13 | public float explosionForce = 50f; 14 | public float explosionRadius = 4f; 15 | public float explosionUpward = 0.4f; 16 | 17 | // Use this for initialization 18 | void Start() { 19 | 20 | 21 | //calculate pivot distance 22 | cubesPivotDistance = cubeSize * cubesInRow / 2; 23 | //use this value to create pivot vector) 24 | cubesPivot = new Vector3(cubesPivotDistance, cubesPivotDistance, cubesPivotDistance); 25 | 26 | } 27 | 28 | // Update is called once per frame 29 | void Update() { 30 | 31 | } 32 | 33 | private void OnTriggerEnter(Collider other) { 34 | if (other.gameObject.name == "Floor") { 35 | explode(); 36 | } 37 | 38 | } 39 | 40 | public void explode() { 41 | //make object disappear 42 | gameObject.SetActive(false); 43 | 44 | //loop 3 times to create 5x5x5 pieces in x,y,z coordinates 45 | for (int x = 0; x < cubesInRow; x++) { 46 | for (int y = 0; y < cubesInRow; y++) { 47 | for (int z = 0; z < cubesInRow; z++) { 48 | createPiece(x, y, z); 49 | } 50 | } 51 | } 52 | 53 | //get explosion position 54 | Vector3 explosionPos = transform.position; 55 | //get colliders in that position and radius 56 | Collider[] colliders = Physics.OverlapSphere(explosionPos, explosionRadius); 57 | //add explosion force to all colliders in that overlap sphere 58 | foreach (Collider hit in colliders) { 59 | //get rigidbody from collider object 60 | Rigidbody rb = hit.GetComponent(); 61 | if (rb != null) { 62 | //add explosion force to this body with given parameters 63 | rb.AddExplosionForce(explosionForce, transform.position, explosionRadius, explosionUpward); 64 | } 65 | } 66 | 67 | } 68 | 69 | void createPiece(int x, int y, int z) { 70 | 71 | //create piece 72 | GameObject piece; 73 | piece = GameObject.CreatePrimitive(PrimitiveType.Cube); 74 | 75 | //set piece position and scale 76 | piece.transform.position = transform.position + new Vector3(cubeSize * x, cubeSize * y, cubeSize * z) - cubesPivot; 77 | piece.transform.localScale = new Vector3(cubeSize, cubeSize, cubeSize); 78 | 79 | //add rigidbody and set mass 80 | piece.AddComponent(); 81 | piece.GetComponent().mass = cubeSize; 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /FacebookLogin.cs: -------------------------------------------------------------------------------- 1 | private void CallFBInit() 2 | { 3 | FB.Init(OnInitComplete, OnHideUnity); 4 | 5 | } 6 | 7 | private void OnInitComplete() 8 | { 9 | if (FB.IsLoggedIn) 10 | { 11 | Debug.Log ("Loggedin userid: " + FB.UserId); 12 | return; 13 | } 14 | 15 | } 16 | 17 | private void OnHideUnity(bool isGameShown) 18 | { 19 | if (!isGameShown) 20 | { 21 | // pause the game - we will need to hide 22 | Time.timeScale = 0; 23 | } 24 | else 25 | { 26 | // start the game back up - we're getting focus again 27 | Time.timeScale = 1; 28 | } 29 | } 30 | 31 | private void LoginFB() 32 | { 33 | FB.Login("email,public_profile, user_friends", LoginCallback); 34 | } 35 | 36 | private void LogoutFB() 37 | { 38 | if (FB.IsLoggedIn) 39 | { 40 | FB.Logout(); 41 | 42 | } 43 | } 44 | 45 | 46 | private void LoginCallback(FBResult result) 47 | { 48 | // Call Cognito Login for FB as well 49 | AWSManager.FacebookLoginCallback (result); 50 | 51 | if (result.Error != null) 52 | { 53 | 54 | } 55 | else if (!FB.IsLoggedIn) 56 | { 57 | 58 | } 59 | else if(FB.IsLoggedIn) 60 | { 61 | 62 | 63 | } 64 | 65 | } 66 | 67 | public void OnClickedOnFBButton() 68 | { 69 | //Debug.Log ("clicked on facebook button"); 70 | if(FB.IsLoggedIn) 71 | { 72 | return; 73 | } 74 | 75 | LoginFB (); 76 | } 77 | -------------------------------------------------------------------------------- /FadeToBlueScript.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class FadeToBlueScript : MonoBehaviour { 6 | 7 | // Reference to game objects Sprite Renderer component 8 | SpriteRenderer rend; 9 | 10 | // Variable to hold value to fade down to. 11 | // Can be adjusted in inspector with slider 12 | [Range(0f, 1f)] 13 | public float fadeToBlueAmount = 0f; 14 | 15 | // Variable to hold fading speed 16 | public float fadingSpeed = 0.05f; 17 | 18 | // Use this for initialization 19 | void Start () { 20 | 21 | // Getting Sprite Renderer component 22 | rend = GetComponent (); 23 | 24 | // Getting access to Color options 25 | Color c = rend.material.color; 26 | 27 | // Setting initial values for Red and Green channels 28 | c.r = 1f; 29 | c.g = 1f; 30 | 31 | // Set sprite colors 32 | rend.material.color = c; 33 | 34 | } 35 | 36 | // Coroutine to slowly fade down to desireable color 37 | IEnumerator FadeToBlue() 38 | { 39 | 40 | // Loop that runs from 1 down to desirable Blue Channel Color amount 41 | for (float i = 1f; i >= fadeToBlueAmount; i -= 0.05f) 42 | { 43 | 44 | // Getting access to Color options 45 | Color c = rend.material.color; 46 | 47 | // Setting values for Red and Green channels 48 | c.r = i; 49 | c.g = i; 50 | 51 | // Set color to Sprite Renderer 52 | rend.material.color = c; 53 | 54 | // Pause to make color be changed slowly 55 | yield return new WaitForSeconds (fadingSpeed); 56 | } 57 | } 58 | 59 | // Method that starts fading coroutine when UI button is pressed 60 | public void StartFadeToBlue() 61 | { 62 | StartCoroutine ("FadeToBlue"); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /FadeToGreenScript.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class FadeToGreenScript : MonoBehaviour { 6 | 7 | 8 | // Reference to game objects Sprite Renderer component 9 | SpriteRenderer rend; 10 | 11 | // Variable to hold value to fade down to. 12 | // Can be adjusted in inspector with slider 13 | [Range(0f, 1f)] 14 | public float fadeToGreenAmount = 0f; 15 | 16 | // Variable to hold fading speed 17 | public float fadingSpeed = 0.05f; 18 | 19 | // Use this for initialization 20 | void Start () { 21 | 22 | // Getting Sprite Renderer component 23 | rend = GetComponent (); 24 | 25 | // Getting access to Color options 26 | Color c = rend.material.color; 27 | 28 | // Setting initial values for Red and Blue channels 29 | c.r = 1f; 30 | c.b = 1f; 31 | 32 | // Set sprite colors 33 | rend.material.color = c; 34 | 35 | } 36 | 37 | // Coroutine to slowly fade down to desireable color 38 | IEnumerator FadeToGreen() 39 | { 40 | 41 | // Loop that runs from 1 down to desirable Green Channel Color amount 42 | for (float i = 1f; i >= fadeToGreenAmount; i -= 0.05f) 43 | { 44 | 45 | // Getting access to Color options 46 | Color c = rend.material.color; 47 | 48 | // Setting values for Red and Blue channels 49 | c.r = i; 50 | c.b = i; 51 | 52 | // Set color to Sprite Renderer 53 | rend.material.color = c; 54 | 55 | // Pause to make color be changed slowly 56 | yield return new WaitForSeconds (fadingSpeed); 57 | } 58 | } 59 | 60 | // Method that starts fading coroutine when UI button is pressed 61 | public void StartFadeToGreen() 62 | { 63 | StartCoroutine ("FadeToGreen"); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /FadeToRedScript.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class FadeToRedScript : MonoBehaviour { 6 | 7 | // Reference to game objects Sprite Renderer component 8 | SpriteRenderer rend; 9 | 10 | // Variable to hold value to fade down to. 11 | // Can be adjusted in inspector with slider 12 | [Range(0f, 1f)] 13 | public float fadeToRedAmount = 0f; 14 | 15 | // Variable to hold fading speed 16 | public float fadingSpeed = 0.05f; 17 | 18 | // Use this for initialization 19 | void Start () { 20 | 21 | // Getting Sprite Renderer component 22 | rend = GetComponent (); 23 | 24 | // Getting access to Color options 25 | Color c = rend.material.color; 26 | 27 | // Setting initial values for Green and Blue channels 28 | c.g = 1f; 29 | c.b = 1f; 30 | 31 | // Set sprite colors 32 | rend.material.color = c; 33 | 34 | } 35 | 36 | // Coroutine to slowly fade down to desireable color 37 | IEnumerator FadeToRed() 38 | { 39 | 40 | // Loop that runs from 1 down to desirable Red Channel Color amount 41 | for (float i = 1f; i >= fadeToRedAmount; i -= 0.05f) 42 | { 43 | // Getting access to Color options 44 | Color c = rend.material.color; 45 | 46 | // Setting values for Green and Blue channels 47 | c.g = i; 48 | c.b = i; 49 | 50 | // Set color to Sprite Renderer 51 | rend.material.color = c; 52 | 53 | // Pause to make color be changed slowly 54 | yield return new WaitForSeconds (fadingSpeed); 55 | } 56 | } 57 | 58 | 59 | // Method that starts fading coroutine when UI button is pressed 60 | public void StartFadeToRed() 61 | { 62 | StartCoroutine ("FadeToRed"); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /FindAllChilds.cs: -------------------------------------------------------------------------------- 1 | private List AllChilds(GameObject root) 2 | { 3 | List result = new List(); 4 | if (root.transform.childCount > 0) 5 | { 6 | foreach (Transform VARIABLE in root.transform) 7 | { 8 | Searcher(result,VARIABLE.gameObject); 9 | } 10 | } 11 | return result; 12 | } 13 | 14 | private void Searcher(List list,GameObject root) 15 | { 16 | list.Add(root); 17 | if (root.transform.childCount > 0) 18 | { 19 | foreach (Transform VARIABLE in root.transform) 20 | { 21 | Searcher(list,VARIABLE.gameObject); 22 | } 23 | } 24 | } 25 | 26 | 27 | 28 | /* OTHER */ 29 | USE : gameobjet.GetAllChilds() 30 | 31 | List GetAllChilds(Transform _t) 32 | { 33 | List ts = new List(); 34 | 35 | foreach (Transform t in _t) 36 | { 37 | ts.Add(t); 38 | if (t.childCount > 0) 39 | ts.AddRange(GetAllChilds(t)); 40 | } 41 | 42 | return ts; 43 | } 44 | 45 | 46 | /* EXTENSION */ 47 | 48 | public static class TransformExtension { 49 | public static List GetAllChildren(this Transform parent, List transformList = null) 50 | { 51 | if (transformList == null) transformList = new List(); 52 | 53 | foreach (Transform child in parent) { 54 | transformList.Add(child); 55 | child.GetAllChildren(transformList); 56 | } 57 | return transformList; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /FindDeepChild.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public static class TransformDeepChildExtension 5 | { 6 | public static Transform FindDeepChild(this Transform aParent, string aName) 7 | { 8 | var result = aParent.Find(aName); 9 | if (result != null) 10 | return result; 11 | foreach (Transform child in aParent) 12 | { 13 | result = child.FindDeepChild(aName); 14 | if (result != null) 15 | return result; 16 | } 17 | return null; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /FindDescendentTransform.cs: -------------------------------------------------------------------------------- 1 | public static Transform FindDescendentTransform(Transform searchTransform, string descendantName) 2 | { 3 | Transform result = null; 4 | 5 | int childCount = searchTransform.childCount; 6 | for (int i = 0; i < childCount; i++) 7 | { 8 | Transform childTransform = searchTransform.GetChild(i); 9 | 10 | // Not it, but has children? Search the children. 11 | if (childTransform.name != descendantName 12 | && childTransform.childCount > 0) 13 | { 14 | Transform grandchildTransform = FindDescendentTransform(childTransform, descendantName); 15 | if (grandchildTransform == null) 16 | continue; 17 | 18 | result = grandchildTransform; 19 | break; 20 | } 21 | // Not it, but has no children? Go on to the next sibling. 22 | else if (childTransform.name != descendantName 23 | && childTransform.childCount == 0) 24 | { 25 | continue; 26 | } 27 | 28 | // Found it. 29 | result = childTransform; 30 | break; 31 | } 32 | 33 | return result; 34 | } 35 | -------------------------------------------------------------------------------- /FindNearest.cs: -------------------------------------------------------------------------------- 1 | void findNearEnemy() 2 | { 3 | fenemy = GameObject.FindGameObjectsWithTag("EnemyAi"); 4 | Vector3 shortestDistaceToEnemy = new Vector3(1000, 1000, 1000); 5 | for (int i = 0; i < fenemy.Length; i++) 6 | { 7 | Vector3 distanceToEnemy = transform.position - fenemy[i].transform.position; 8 | if (distanceToEnemy.magnitude < shortestDistaceToEnemy.magnitude) 9 | { 10 | shortestDistaceToEnemy = transform.position - fenemy[i].transform.position; 11 | enemy = fenemy[i]; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /FindSamples.cs: -------------------------------------------------------------------------------- 1 | void Start() 2 | { 3 | foreach (Transform t in transform) 4 | { 5 | if (t.name == "GATE") 6 | { 7 | floorGatesCollider = t.gameObject; 8 | //floorGates.Add(t.gameObject); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /FindWithTag.cs: -------------------------------------------------------------------------------- 1 | GameObject[] npcs = GameObject.FindGameObjectsWithTag("NPC"); 2 | foreach(GameObject npc in npcs) 3 | { 4 | npc.GetComponent().run = false; // Or true 5 | } 6 | -------------------------------------------------------------------------------- /FishAnimation.shader: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Alberto Mellado Cruz 3 | Date: 09/11/2017 4 | 5 | Comments: 6 | This is just a test that would depend on the 3D Model used. 7 | Vertex animations would allow the use of GPU Instancing, 8 | enabling the use of a dense amount of animated fish. 9 | The code may not be optimized but it was just a test 10 | */ 11 | 12 | Shader "Custom/FishAnimation" { 13 | Properties{ 14 | _MainTex("Albedo (RGB)", 2D) = "white" {} 15 | _SpeedX("SpeedX", Range(0, 10)) = 1 16 | _FrequencyX("FrequencyX", Range(0, 10)) = 1 17 | _AmplitudeX("AmplitudeX", Range(0, 0.2)) = 1 18 | _SpeedY("SpeedY", Range(0, 10)) = 1 19 | _FrequencyY("FrequencyY", Range(0, 10)) = 1 20 | _AmplitudeY("AmplitudeY", Range(0, 0.2)) = 1 21 | _SpeedZ("SpeedZ", Range(0, 10)) = 1 22 | _FrequencyZ("FrequencyZ", Range(0, 10)) = 1 23 | _AmplitudeZ("AmplitudeZ", Range(0, 2)) = 1 24 | _HeadLimit("HeadLimit", Range(-2, 2)) = 0.05 25 | } 26 | SubShader{ 27 | Tags{ "RenderType" = "Opaque" } 28 | Cull off 29 | 30 | Pass{ 31 | 32 | CGPROGRAM 33 | #pragma vertex vert 34 | #pragma fragment frag 35 | #include "UnityCG.cginc" 36 | 37 | sampler2D _MainTex; 38 | float4 _MainTex_ST; 39 | 40 | struct v2f { 41 | float4 pos : SV_POSITION; 42 | float2 uv : TEXCOORD0; 43 | }; 44 | 45 | // X AXIS 46 | 47 | float _SpeedX; 48 | float _FrequencyX; 49 | float _AmplitudeX; 50 | 51 | // Y AXIS 52 | 53 | float _SpeedY; 54 | float _FrequencyY; 55 | float _AmplitudeY; 56 | 57 | // Z AXIS 58 | 59 | float _SpeedZ; 60 | float _FrequencyZ; 61 | float _AmplitudeZ; 62 | 63 | // Head Limit (Head wont shake so much) 64 | 65 | float _HeadLimit; 66 | 67 | v2f vert(appdata_base v) 68 | { 69 | v2f o; 70 | 71 | //Z AXIS 72 | 73 | v.vertex.z += sin((v.vertex.z + _Time.y * _SpeedX) * _FrequencyX)* _AmplitudeX; 74 | 75 | //Y AXIS 76 | 77 | v.vertex.y += sin((v.vertex.z + _Time.y * _SpeedY) * _FrequencyY)* _AmplitudeY; 78 | 79 | //X AXIS 80 | 81 | if (v.vertex.z > _HeadLimit) 82 | { 83 | v.vertex.x += sin((0.05 + _Time.y * _SpeedZ) * _FrequencyZ)* _AmplitudeZ * _HeadLimit; 84 | } 85 | else 86 | { 87 | v.vertex.x += sin((v.vertex.z + _Time.y * _SpeedZ) * _FrequencyZ)* _AmplitudeZ * v.vertex.z; 88 | } 89 | 90 | 91 | o.pos = UnityObjectToClipPos(v.vertex); 92 | o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); 93 | return o; 94 | 95 | } 96 | 97 | fixed4 frag(v2f i) : SV_Target 98 | { 99 | return tex2D(_MainTex, i.uv); 100 | } 101 | 102 | ENDCG 103 | 104 | } 105 | } 106 | FallBack "Diffuse" 107 | } 108 | -------------------------------------------------------------------------------- /FitCamera.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class FitCamera : MonoBehaviour { 6 | 7 | public Camera targetCamera; 8 | 9 | void Fit() 10 | { 11 | var posViewport = new Vector3(0.5f, 0.5f, targetCamera.farClipPlane - targetCamera.nearClipPlane); 12 | transform.position = targetCamera.ViewportToWorldPoint(posViewport); 13 | transform.rotation = targetCamera.transform.rotation; 14 | var size = 2f * targetCamera.orthographicSize; 15 | transform.localScale = new Vector3(size * targetCamera.aspect, size, 1f); 16 | } 17 | 18 | // Use this for initialization 19 | void Start () { 20 | 21 | } 22 | 23 | // Update is called once per frame 24 | void Update () { 25 | Fit(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Floater.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | // Makes objects float up & down while gently spinning. 5 | public class Floater : MonoBehaviour { 6 | // User Inputs 7 | public float degreesPerSecond = 15.0f; 8 | public float amplitude = 0.5f; 9 | public float frequency = 1f; 10 | 11 | // Position Storage Variables 12 | Vector3 posOffset = new Vector3 (); 13 | Vector3 tempPos = new Vector3 (); 14 | 15 | // Use this for initialization 16 | void Start () { 17 | // Store the starting position & rotation of the object 18 | posOffset = transform.position; 19 | } 20 | 21 | // Update is called once per frame 22 | void Update () { 23 | // Spin object around Y-Axis 24 | transform.Rotate(new Vector3(0f, Time.deltaTime * degreesPerSecond, 0f), Space.World); 25 | 26 | // Float up/down with a Sin() 27 | tempPos = posOffset; 28 | tempPos.y += Mathf.Sin (Time.fixedTime * Mathf.PI * frequency) * amplitude; 29 | 30 | transform.position = tempPos; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /FlyweightPattern.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | 5 | //Flyweight pattern main classı 6 | namespace FlyweightPattern 7 | { 8 | public class Flyweight : MonoBehaviour 9 | { 10 | //Tüm uzaylıları tutan liste 11 | List allAliens = new List(); 12 | 13 | List eyePositions; 14 | List legPositions; 15 | List armPositions; 16 | 17 | 18 | void Start() 19 | { 20 | //Flyweight etkinleştirildiğinde kullanılan liste 21 | eyePositions = GetBodyPartPositions(); 22 | legPositions = GetBodyPartPositions(); 23 | armPositions = GetBodyPartPositions(); 24 | 25 | //Tüm uzaylıları oluşturuyoruz 26 | for (int i = 0; i < 10000; i++) 27 | { 28 | Alien newAlien = new Alien(); 29 | 30 | //göz ve bacak pozisyonları 31 | //Flyweight olmadan!! 32 | newAlien.eyePositions = GetBodyPartPositions(); 33 | newAlien.armPositions = GetBodyPartPositions(); 34 | newAlien.legPositions = GetBodyPartPositions(); 35 | 36 | //Flyweight ile!! 37 | //newAlien.eyePositions = eyePositions; 38 | //newAlien.armPositions = legPositions; 39 | //newAlien.legPositions = armPositions; 40 | 41 | allAliens.Add(newAlien); 42 | } 43 | } 44 | 45 | 46 | //listeyı generate ediyoruz 47 | List GetBodyPartPositions(){//Yenı list oluşturuyoruz 48 | List bodyPartPositions = new List(); 49 | 50 | //vücut parçalarını listeye ekliyoruz 51 | for (int i = 0; i < 1000; i++) 52 | { 53 | bodyPartPositions.Add(new Vector3()); 54 | } 55 | 56 | return bodyPartPositions; 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /GameManagerInstanceSample.cs: -------------------------------------------------------------------------------- 1 | public class GameManager : MonoBehaviour { 2 | 3 | #region Instance 4 | private static GameManager _instance; 5 | public static GameManager Instance => _instance; 6 | #endregion 7 | 8 | private void Awake() { 9 | if(_instance != null && _instance != this) Destroy(gameObject); 10 | _instance = this; 11 | } 12 | } 13 | 14 | /* 15 | #region Instance 16 | private static AudioManager _instance; 17 | public static AudioManager Instance 18 | { 19 | get 20 | { 21 | if (_instance == null) 22 | { 23 | _instance = GameObject.FindObjectOfType(); 24 | if (_instance == null) { 25 | 26 | _instance = new GameObject().AddComponent(); 27 | _instance.name = "AudioManager"; 28 | } 29 | } 30 | return _instance; 31 | } 32 | } 33 | #endregion 34 | */ 35 | -------------------------------------------------------------------------------- /GameobjectsinaCollider.txt: -------------------------------------------------------------------------------- 1 | Physics.OverlapBox It will Find all colliders touching or inside of the given box. so you can set the size of your box for your purpose 2 | 3 | Collider[] hitColliders = Physics.OverlapBox(gameObject.transform.position, transform.localScale / 2, Quaternion.identity, m_LayerMask); 4 | 5 | Collider.gameObject 6 | -------------------------------------------------------------------------------- /GetCenter.cs: -------------------------------------------------------------------------------- 1 | public static Vector3 GetCenter(Vector3[] points) 2 | { 3 | var center = Vector3.zero; 4 | for (int i = 0; i < points.Length; i++) 5 | center += points[i] / points.Length; 6 | return center; 7 | } 8 | -------------------------------------------------------------------------------- /GetCurveTimeForValue.cs: -------------------------------------------------------------------------------- 1 | public float GetCurveTimeForValue(AnimationCurve curveToCheck, float value, int accuracy) 2 | { 3 | 4 | float startTime = curveToCheck.keys[0].time; 5 | float endTime = curveToCheck.keys[curveToCheck.length - 1].time; 6 | float nearestTime = startTime; 7 | float step = endTime - startTime; 8 | 9 | for (int i = 0; i < accuracy; i++) 10 | { 11 | 12 | float valueAtNearestTime = curveToCheck.Evaluate(nearestTime); 13 | float distanceToValueAtNearestTime = Mathf.Abs(value - valueAtNearestTime); 14 | 15 | float timeToCompare = nearestTime + step; 16 | float valueAtTimeToCompare = curveToCheck.Evaluate(timeToCompare); 17 | float distanceToValueAtTimeToCompare = Mathf.Abs(value - valueAtTimeToCompare); 18 | 19 | if (distanceToValueAtTimeToCompare < distanceToValueAtNearestTime) 20 | { 21 | nearestTime = timeToCompare; 22 | valueAtNearestTime = valueAtTimeToCompare; 23 | } 24 | step = Mathf.Abs(step * 0.5f) * Mathf.Sign(value - valueAtNearestTime); 25 | } 26 | 27 | return nearestTime; 28 | } 29 | -------------------------------------------------------------------------------- /GetSetSample.cs: -------------------------------------------------------------------------------- 1 | public int playerLives 2 | { 3 | get 4 | { 5 | return _playerLives; 6 | } 7 | set 8 | { 9 | //updateUI(); 10 | if (value == 0) 11 | { 12 | EndGame(); 13 | } 14 | else 15 | { 16 | _playerLives = value; 17 | } 18 | } 19 | } 20 | private int _playerLives = 3; 21 | 22 | 23 | 24 | //GameManager.instance.playerLives--; 25 | -------------------------------------------------------------------------------- /Gradient_3Color.shader: -------------------------------------------------------------------------------- 1 | Shader "Custom/Gradient_3Color" { 2 | Properties { 3 | [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {} 4 | _ColorTop ("Top Color", Color) = (1,1,1,1) 5 | _ColorMid ("Mid Color", Color) = (1,1,1,1) 6 | _ColorBot ("Bot Color", Color) = (1,1,1,1) 7 | _Middle ("Middle", Range(0.001, 0.999)) = 1 8 | } 9 | 10 | SubShader { 11 | Tags {"Queue"="Background" "IgnoreProjector"="True"} 12 | LOD 100 13 | 14 | ZWrite On 15 | 16 | Pass { 17 | CGPROGRAM 18 | #pragma vertex vert 19 | #pragma fragment frag 20 | #include "UnityCG.cginc" 21 | 22 | fixed4 _ColorTop; 23 | fixed4 _ColorMid; 24 | fixed4 _ColorBot; 25 | float _Middle; 26 | 27 | struct v2f { 28 | float4 pos : SV_POSITION; 29 | float4 texcoord : TEXCOORD0; 30 | }; 31 | 32 | v2f vert (appdata_full v) { 33 | v2f o; 34 | o.pos = mul (UNITY_MATRIX_MVP, v.vertex); 35 | o.texcoord = v.texcoord; 36 | return o; 37 | } 38 | 39 | fixed4 frag (v2f i) : COLOR { 40 | fixed4 c = lerp(_ColorBot, _ColorMid, i.texcoord.y / _Middle) * step(i.texcoord.y, _Middle); 41 | c += lerp(_ColorMid, _ColorTop, (i.texcoord.y - _Middle) / (1 - _Middle)) * (1 - step(i.texcoord.y, _Middle)); 42 | c.a = 1; 43 | return c; 44 | } 45 | ENDCG 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /GrayscaleLayers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using UnityEngine; 3 | 4 | // Grayscale effect, with added ExcludeLayer option 5 | // Usage: Attach this script to camera, Select excludeLayers, Set your excluded objects to that layer 6 | 7 | 8 | #if !UNITY_5_3_OR_NEWER 9 | namespace UnityStandardAssets.ImageEffects 10 | { 11 | 12 | [ExecuteInEditMode] 13 | [AddComponentMenu("Image Effects/Color Adjustments/Grayscale")] 14 | public class GrayscaleLayers : ImageEffectBase 15 | { 16 | public Texture textureRamp; 17 | public LayerMask excludeLayers = 0; 18 | 19 | private GameObject tmpCam = null; 20 | private Camera _camera; 21 | 22 | [Range(-1.0f, 1.0f)] 23 | public float rampOffset; 24 | 25 | // Called by camera to apply image effect 26 | void OnRenderImage(RenderTexture source, RenderTexture destination) 27 | { 28 | material.SetTexture("_RampTex", textureRamp); 29 | material.SetFloat("_RampOffset", rampOffset); 30 | Graphics.Blit(source, destination, material); 31 | 32 | // exclude layers 33 | Camera cam = null; 34 | if (excludeLayers.value != 0) cam = GetTmpCam(); 35 | 36 | if (cam && excludeLayers.value != 0) 37 | { 38 | cam.targetTexture = destination; 39 | cam.cullingMask = excludeLayers; 40 | cam.Render(); 41 | } 42 | } 43 | 44 | 45 | // taken from CameraMotionBlur.cs 46 | Camera GetTmpCam() 47 | { 48 | if (tmpCam == null) 49 | { 50 | if (_camera == null) _camera = GetComponent(); 51 | 52 | string name = "_" + _camera.name + "_GrayScaleTmpCam"; 53 | GameObject go = GameObject.Find(name); 54 | 55 | if (null == go) // couldn't find, recreate 56 | { 57 | tmpCam = new GameObject(name, typeof(Camera)); 58 | } else 59 | { 60 | tmpCam = go; 61 | } 62 | } 63 | 64 | tmpCam.hideFlags = HideFlags.DontSave; 65 | tmpCam.transform.position = _camera.transform.position; 66 | tmpCam.transform.rotation = _camera.transform.rotation; 67 | tmpCam.transform.localScale = _camera.transform.localScale; 68 | tmpCam.GetComponent().CopyFrom(_camera); 69 | 70 | tmpCam.GetComponent().enabled = false; 71 | tmpCam.GetComponent().depthTextureMode = DepthTextureMode.None; 72 | tmpCam.GetComponent().clearFlags = CameraClearFlags.Nothing; 73 | 74 | return tmpCam.GetComponent(); 75 | } 76 | } 77 | } 78 | #endif 79 | -------------------------------------------------------------------------------- /GridShader.Shader: -------------------------------------------------------------------------------- 1 | Shader "Custom/XZGrid" 2 | { 3 | Properties 4 | { 5 | _Color ("Color", Color) = (1,1,1,1) 6 | _MainTex ("Albedo (RGB)", 2D) = "white" {} 7 | _Glossiness ("Smoothness", Range(0,1)) = 0.5 8 | _Metallic ("Metallic", Range(0,1)) = 0.0 9 | _GridStep ("Grid size", Float) = 10 10 | _GridWidth ("Grid width", Float) = 1 11 | } 12 | SubShader 13 | { 14 | Tags { "RenderType"="Opaque" } 15 | LOD 200 16 | 17 | CGPROGRAM 18 | // Physically based Standard lighting model, and enable shadows on all light types 19 | #pragma surface surf Standard fullforwardshadows 20 | 21 | // Use shader model 3.0 target, to get nicer looking lighting 22 | #pragma target 3.0 23 | 24 | sampler2D _MainTex; 25 | 26 | struct Input 27 | { 28 | float2 uv_MainTex; 29 | float3 worldPos; 30 | }; 31 | 32 | half _Glossiness; 33 | half _Metallic; 34 | fixed4 _Color; 35 | float _GridStep; 36 | float _GridWidth; 37 | 38 | void surf (Input IN, inout SurfaceOutputStandard o) { 39 | // Albedo comes from a texture tinted by color 40 | fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color; 41 | 42 | // grid overlay 43 | float2 pos = IN.worldPos.xz / _GridStep; 44 | float2 f = abs(frac(pos)-.5); 45 | float2 df = fwidth(pos) * _GridWidth; 46 | float2 g = smoothstep(-df ,df , f); 47 | float grid = 1.0 - saturate(g.x * g.y); 48 | c.rgb = lerp(c.rgb, float3(1,1,1), grid); 49 | 50 | o.Albedo = c.rgb; 51 | // Metallic and smoothness come from slider variables 52 | o.Metallic = _Metallic; 53 | o.Smoothness = _Glossiness; 54 | o.Alpha = c.a; 55 | } 56 | ENDCG 57 | } 58 | FallBack "Diffuse" 59 | } 60 | -------------------------------------------------------------------------------- /HandMove.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace weaponMaster 6 | { 7 | public class HandMove : MonoBehaviour 8 | { 9 | 10 | public Transform targetRight; 11 | public Transform targetLeft; 12 | public Transform lookTarget; 13 | Animator m_anim; 14 | [Range(0, 1)] 15 | public float weight = 1.0f; 16 | public float speed; 17 | 18 | public enum Part 19 | { 20 | RightHand, 21 | LeftHand, 22 | TwoHand, 23 | RightFoot, 24 | LeftFoot, 25 | TwoFoot 26 | } 27 | public Part part; 28 | 29 | void Start() 30 | { 31 | m_anim = GetComponent(); 32 | } 33 | 34 | private void OnAnimatorIK(int layerIndex) 35 | { 36 | if (part == Part.RightHand) { 37 | m_anim.SetIKPosition(AvatarIKGoal.RightHand, targetRight.position); 38 | m_anim.SetIKPositionWeight(AvatarIKGoal.RightHand, weight); 39 | 40 | m_anim.SetLookAtPosition(lookTarget.position); 41 | m_anim.SetLookAtWeight(weight); 42 | } 43 | else if (part == Part.LeftHand) 44 | { 45 | m_anim.SetIKPosition(AvatarIKGoal.LeftHand, targetLeft.position); 46 | m_anim.SetIKPositionWeight(AvatarIKGoal.LeftHand, weight); 47 | 48 | m_anim.SetLookAtPosition(lookTarget.position); 49 | m_anim.SetLookAtWeight(weight); 50 | } 51 | else if (part == Part.TwoHand) 52 | { 53 | m_anim.SetIKPosition(AvatarIKGoal.RightHand, targetRight.position); 54 | m_anim.SetIKPositionWeight(AvatarIKGoal.RightHand, weight); 55 | m_anim.SetIKPosition(AvatarIKGoal.LeftHand, targetLeft.position); 56 | m_anim.SetIKPositionWeight(AvatarIKGoal.LeftHand, weight); 57 | 58 | m_anim.SetLookAtPosition(lookTarget.position); 59 | m_anim.SetLookAtWeight(weight); 60 | } 61 | 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /HpRegeneration.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class HpRegeneration : MonoBehaviour 6 | { 7 | [SerializeField] 8 | private int maxHealth = 5; 9 | 10 | [SerializeField] 11 | private float healthRegenerationRate = 1; 12 | 13 | [SerializeField] 14 | private float regenerationDelay = 1; 15 | 16 | private int currentHealth; 17 | 18 | private float lastDamagesTime = -1; 19 | 20 | private float regeneratedHealth; 21 | 22 | public bool IsDead 23 | { 24 | get { return currentHealth == 0; } 25 | } 26 | 27 | private void Awake() 28 | { 29 | currentHealth = maxHealth; 30 | } 31 | 32 | void Update() 33 | { 34 | if ( lastDamagesTime >= 0 && Time.time - lastDamagesTime >= regenerationDelay ) 35 | { 36 | RegenerateHealth(); 37 | } 38 | } 39 | 40 | public void RegenerateHealth() 41 | { 42 | regeneratedHealth += healthRegenerationRate * Time.deltaTime; 43 | int flooredRegeneratedHealth = Mathf.FloorToInt( regeneratedHealth ); 44 | regeneratedHealth -= flooredRegeneratedHealth; 45 | Heal( flooredRegeneratedHealth ); 46 | } 47 | 48 | public void Hurt( int damages ) 49 | { 50 | if ( damages < 0 ) 51 | throw new System.ArgumentException( "Damages must be greater or equal to 0", nameof( damages ) ); 52 | 53 | if ( IsDead ) 54 | return; 55 | 56 | currentHealth = Mathf.Clamp( currentHealth - damages, 0, maxHealth ); 57 | regeneratedHealth = 0; 58 | lastDamagesTime = Time.time; 59 | 60 | if( IsDead ) 61 | { 62 | // Die 63 | } 64 | } 65 | 66 | public void Heal( int amount ) 67 | { 68 | if ( amount < 0 ) 69 | throw new System.ArgumentException( "Healed amount must be greater or equal to 0", nameof( amount ) ); 70 | 71 | currentHealth = Mathf.Clamp( currentHealth + amount, 0, maxHealth ); 72 | if( currentHealth == maxHealth ) 73 | { 74 | lastDamagesTime = -1; 75 | regeneratedHealth = 0; 76 | // Full health 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /ImageSlicer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public static class ImageSlicer { 6 | 7 | public static Texture2D[,] GetSlices(Texture2D image, int blocksPerLine) 8 | { 9 | int imageSize = Mathf.Min(image.width, image.height); 10 | int blockSize = imageSize / blocksPerLine; 11 | 12 | Texture2D[,] blocks = new Texture2D[blocksPerLine, blocksPerLine]; 13 | 14 | for (int y = 0; y < blocksPerLine; y++) 15 | { 16 | for (int x = 0; x < blocksPerLine; x++) 17 | { 18 | Texture2D block = new Texture2D(blockSize, blockSize); 19 | block.wrapMode = TextureWrapMode.Clamp; 20 | block.SetPixels(image.GetPixels(x * blockSize, y * blockSize, blockSize, blockSize)); 21 | block.Apply(); 22 | blocks[x, y] = block; 23 | } 24 | } 25 | 26 | return blocks; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ImpactReceiver.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | using System.Collections; 4 | 5 | public class ImpactReceiver : MonoBehaviour 6 | { 7 | float mass = 3.0F; // defines the character mass 8 | Vector3 impact = Vector3.zero; 9 | private CharacterController character; 10 | // Use this for initialization 11 | void Start() 12 | { 13 | character = GetComponent(); 14 | } 15 | 16 | // Update is called once per frame 17 | void Update() 18 | { 19 | // apply the impact force: 20 | if (impact.magnitude > 0.2F) character.Move(impact * Time.deltaTime); 21 | // consumes the impact energy each cycle: 22 | impact = Vector3.Lerp(impact, Vector3.zero, 5 * Time.deltaTime); 23 | } 24 | // call this function to add an impact force: 25 | public void AddImpact(Vector3 dir, float force) 26 | { 27 | dir.Normalize(); 28 | if (dir.y < 0) dir.y = -dir.y; // reflect down force on the ground 29 | impact += dir.normalized * force / mass; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /InfiniteRoadManager.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class InfiniteRoadManager : MonoBehaviour 6 | { 7 | 8 | public GameObject[] RoadPieces = new GameObject[2]; 9 | public float RoadLength = 100; //length of roads 10 | public float RoadSpeed = 15f; //speed to scroll roads at 11 | 12 | // Update is called once per frame 13 | void Update() 14 | { 15 | foreach (GameObject road in RoadPieces) 16 | { 17 | Vector3 newRoadPos = road.transform.position; 18 | newRoadPos.z -= RoadSpeed * Time.deltaTime; 19 | if (newRoadPos.z < -RoadLength / 2) 20 | { 21 | newRoadPos.z += RoadLength; 22 | } 23 | road.transform.position = newRoadPos; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /InterfaceSample.cs: -------------------------------------------------------------------------------- 1 | /* IController.cs file */ 2 | namespace MyGame 3 | { 4 | public interface IController 5 | { 6 | event System.Action OnStart; 7 | event System.Action OnStop; 8 | } 9 | } 10 | 11 | /* PlayerController.cs file */ 12 | using System; 13 | using System.Collections; 14 | using System.Collections.Generic; 15 | using UnityEngine; 16 | 17 | namespace MyGame 18 | { 19 | public class PlayerController : MonoBehaviour, IController 20 | { 21 | public event Action OnStart; 22 | public event Action OnStop; 23 | 24 | private bool _isTouched = false; 25 | 26 | private void Update() 27 | { 28 | #if UNITY_EDITOR 29 | if (Input.GetMouseButtonDown(0)) 30 | { 31 | OnStart?.Invoke(); 32 | } 33 | if (Input.GetMouseButtonUp(0)) 34 | { 35 | OnStop?.Invoke(); 36 | } 37 | return; 38 | #endif 39 | if (Input.touches.Length > 0) 40 | { 41 | if (!_isTouched) 42 | { 43 | _isTouched = true; 44 | OnStart?.Invoke(); 45 | } 46 | } 47 | else 48 | { 49 | if (_isTouched) 50 | { 51 | _isTouched = false; 52 | OnStop?.Invoke(); 53 | } 54 | } 55 | } 56 | } 57 | } 58 | 59 | /* Player.cs file */ 60 | using System.Collections; 61 | using System.Collections.Generic; 62 | using UnityEngine; 63 | 64 | namespace MyGame 65 | { 66 | public class Player : MonoBehaviour 67 | { 68 | 69 | [SerializeField] private Rigidbody _rigidbody; 70 | [SerializeField] private GameObject _controlObject; 71 | [SerializeField] private float _speedMax; 72 | 73 | private float speed = 0; 74 | 75 | public IController _controller; 76 | 77 | private bool _isControled = false; 78 | 79 | private Quaternion _defaultRotation; 80 | private RigidbodyConstraints _constraints; 81 | 82 | public bool IsControled 83 | { 84 | get => _isControled; 85 | set => _isControled = value; 86 | } 87 | 88 | // Start is called before the first frame update 89 | void Start() 90 | { 91 | _constraints = _rigidbody.constraints; 92 | _defaultRotation = transform.rotation; 93 | 94 | _controller = _controlObject.GetComponent(); 95 | _controller.OnStart += StartMovement; 96 | _controller.OnStop += StopMovement; 97 | } 98 | 99 | private void StopMovement() 100 | { 101 | speed = 0; 102 | } 103 | 104 | private void StartMovement() 105 | { 106 | speed = _speedMax; 107 | } 108 | 109 | // Update is called once per frame 110 | void Update() 111 | { 112 | if (_isControled) 113 | { 114 | _rigidbody.velocity = Vector3.forward * speed; 115 | } 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /IsBetweenRange.cs: -------------------------------------------------------------------------------- 1 | public static class MathExtension 2 | { 3 | public static bool IsBetweenRange(this float thisValue, float value1, float value2) 4 | { 5 | return thisValue >= Mathf.Min(value1, value2) && thisValue <= Mathf.Max(value1, value2); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /JoystickController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | using UnityEngine.UI; 5 | 6 | public class JoystickController : MonoBehaviour { 7 | 8 | public RectTransform center; 9 | public RectTransform knob; 10 | public float range; 11 | public bool fixedJoystick; 12 | 13 | 14 | public Vector2 direction; 15 | 16 | Vector2 start; 17 | 18 | void Start(){ 19 | ShowHide(false); 20 | } 21 | 22 | void Update(){ 23 | Vector2 pos = Input.mousePosition; 24 | 25 | if(Input.GetMouseButtonDown(0)){ 26 | ShowHide(true); 27 | start = pos; 28 | 29 | knob.position = pos; 30 | center.position = pos; 31 | } 32 | else if(Input.GetMouseButton(0)){ 33 | knob.position = pos; 34 | knob.position = center.position + Vector3.ClampMagnitude(knob.position - center.position, center.sizeDelta.x * range); 35 | 36 | if(knob.position != Input.mousePosition && !fixedJoystick){ 37 | Vector3 outsideBoundsVector = Input.mousePosition - knob.position; 38 | center.position += outsideBoundsVector; 39 | } 40 | 41 | direction = (knob.position - center.position).normalized; 42 | } 43 | else if(Input.GetMouseButtonUp(0)){ 44 | ShowHide(false); 45 | direction = Vector2.zero; 46 | } 47 | } 48 | 49 | void ShowHide(bool state){ 50 | center.gameObject.SetActive(state); 51 | knob.gameObject.SetActive(state); 52 | } 53 | } 54 | 55 | 56 | /* PLAYER CONTROLLER */ 57 | /* 58 | //move 59 | Vector2 direction = joystick.direction; 60 | moveDirection = new Vector3(direction.x, 0, direction.y); 61 | transform.position += moveDirection * Time.deltaTime * moveSpeed; 62 | //rotate 63 | Quaternion targetRotation = moveDirection != Vector3.zero ? Quaternion.LookRotation(moveDirection) : transform.rotation; 64 | transform.rotation = targetRotation; 65 | */ 66 | -------------------------------------------------------------------------------- /Jump.cs: -------------------------------------------------------------------------------- 1 | IEnumerator DoJump() 2 | { 3 | //the initial jump 4 | playerRigidBody.AddForce(Vector2.Up * jumpForce); 5 | yield return null; 6 | 7 | //can be any value, maybe this is a start ascending force, up to you 8 | float currentForce = jumpForce; 9 | 10 | while(Input.GetKey(KeyCode.Space) && currentForce > 0) 11 | { 12 | playerRigidBody.AddForce(Vector2.Up * currentForce); 13 | 14 | currentForce -= decayRate * Time.deltaTime; 15 | yield return null; 16 | } 17 | } 18 | 19 | void Update() 20 | { 21 | if(Input.GetKeyDown(KeyCode.Space) && isGrounded) 22 | { 23 | StartCoRoutine(DoJump()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LaunchProjectiles.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class LaunchProjectiles : MonoBehaviour { 6 | 7 | [SerializeField] 8 | int numberOfProjectiles; 9 | 10 | [SerializeField] 11 | GameObject projectile; 12 | 13 | Vector2 startPoint; 14 | 15 | float radius, moveSpeed; 16 | 17 | // Use this for initialization 18 | void Start () { 19 | radius = 5f; 20 | moveSpeed = 5f; 21 | } 22 | 23 | // Update is called once per frame 24 | void Update () { 25 | if (Input.GetButtonDown ("Fire1")) { 26 | startPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition); 27 | SpawnProjectiles (numberOfProjectiles); 28 | } 29 | } 30 | 31 | void SpawnProjectiles(int numberOfProjectiles) 32 | { 33 | float angleStep = 360f / numberOfProjectiles; 34 | float angle = 0f; 35 | 36 | for (int i = 0; i <= numberOfProjectiles - 1; i++) { 37 | 38 | float projectileDirXposition = startPoint.x + Mathf.Sin ((angle * Mathf.PI) / 180) * radius; 39 | float projectileDirYposition = startPoint.y + Mathf.Cos ((angle * Mathf.PI) / 180) * radius; 40 | 41 | Vector2 projectileVector = new Vector2 (projectileDirXposition, projectileDirYposition); 42 | Vector2 projectileMoveDirection = (projectileVector - startPoint).normalized * moveSpeed; 43 | 44 | var proj = Instantiate (projectile, startPoint, Quaternion.identity); 45 | proj.GetComponent ().velocity = 46 | new Vector2 (projectileMoveDirection.x, projectileMoveDirection.y); 47 | 48 | angle += angleStep; 49 | } 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /LeanTweenOnComplete.cs: -------------------------------------------------------------------------------- 1 | LeanTween.moveX(cubeToRemove, -5.5f, 1f).setOnComplete(() => RemoveMe(foo.id, cubeToRemove)); 2 | -------------------------------------------------------------------------------- /LerpCameraZoom.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class LerpCameraZoom : MonoBehaviour { 6 | 7 | public float[] FOVS = {45,30,15}; 8 | public float speed = 2f; 9 | public bool zoomIn, zoomOut; 10 | Camera myCamera; 11 | int FOVpos = 0; 12 | 13 | // Use this for initialization 14 | void Start () { 15 | myCamera = GetComponent(); 16 | } 17 | 18 | // Update is called once per frame 19 | void Update () { 20 | if (Input.GetMouseButtonDown(0)) { 21 | ZoomIn(); 22 | } 23 | 24 | if (Input.GetMouseButtonDown(1)) { 25 | ZoomOut(); 26 | } 27 | 28 | if (zoomIn) { 29 | myCamera.fieldOfView = Mathf.Lerp(myCamera.fieldOfView, FOVS[FOVpos], speed * Time.deltaTime); 30 | if (Mathf.Approximately(myCamera.fieldOfView, FOVS[FOVpos])) { 31 | zoomIn = false; 32 | } 33 | } 34 | 35 | if (zoomOut) { 36 | myCamera.fieldOfView = Mathf.Lerp(myCamera.fieldOfView, FOVS[FOVpos], speed * Time.deltaTime); 37 | if (Mathf.Approximately(myCamera.fieldOfView, FOVS[FOVpos])) { 38 | zoomOut = false; 39 | } 40 | } 41 | } 42 | 43 | void ZoomIn() { 44 | if (FOVpos >= FOVS.Length - 1) { 45 | FOVpos = FOVS.Length - 1; 46 | } else { 47 | FOVpos += 1; 48 | } 49 | zoomIn = true; 50 | } 51 | 52 | void ZoomOut() { 53 | if (FOVpos <= 0) { 54 | FOVpos = 0; 55 | } else { 56 | FOVpos -= 1; 57 | } 58 | zoomOut = true; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /LerpDemo.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | [ExecuteInEditMode] 4 | public class LerpDemo: MonoBehaviour{ 5 | 6 | [SerializeField] 7 | private float start = 0; 8 | [SerializeField] 9 | private float end = 100; 10 | [SerializeField] 11 | [Range(0f,1f)] 12 | private float lerpPct = 0.5f; 13 | public float finalValue; 14 | 15 | private void Update(){ 16 | finalValue = Mathf.Lerp(start, end, lerpPct); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LerpDemo2.cs: -------------------------------------------------------------------------------- 1 | private Vector3 Pos1; 2 | private Vector3 Pos2; 3 | 4 | gameobject.transform.localPosition = Vector3.Lerp(gameobject.transform.localPosition, Pos1, Time.deltaTime / 0.2f); 5 | 6 | 7 | 8 | private bool CheckIfColliderAbove() 9 | { 10 | //returns true if anything collides with a 1 unit long raycast drawn from player's current position (ultimately checks if something solid is above him) 11 | return Physics.Raycast(transform.position, Vector3.up, 1); 12 | } 13 | -------------------------------------------------------------------------------- /LerpMoveDemo.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | [ExecuteInEditMode] 4 | public class LerpMoveDemo: MonoBehaviour 5 | { 6 | [SerializeField] 7 | private Transform startCube; 8 | [SerializeField] 9 | private Transform endCube; 10 | [SerializeField] 11 | [Range(0f,1f)] 12 | private float lerpPct = 0.5f; 13 | 14 | private void Update(){ 15 | transform.position = Vector3.Lerp(startCube.position, endCube.position, lerpPct); 16 | transform.rotation = Vector3.Lerp(startCube.rotation, endCube.rotation, lerpPct); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Lerper.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class Lerper : MonoBehaviour { 6 | 7 | public Transform startPos, endPos; 8 | public bool repeatable = false; 9 | public float speed = 1.0f; 10 | public float duration = 3.0f; 11 | 12 | float startTime, totalDistance; 13 | 14 | // Use this for initialization 15 | IEnumerator Start () { 16 | startTime = Time.time; 17 | totalDistance = Vector3.Distance(startPos.position, endPos.position); 18 | while(repeatable) { 19 | yield return RepeatLerp(startPos.position, endPos.position, duration); 20 | yield return RepeatLerp(endPos.position, startPos.position, duration); 21 | } 22 | } 23 | 24 | // Update is called once per frame 25 | void Update () { 26 | if(!repeatable) { 27 | float currentDuration = (Time.time - startTime) * speed; 28 | float journeyFraction = currentDuration / totalDistance; 29 | this.transform.position = Vector3.Lerp(startPos.position, endPos.position, journeyFraction); 30 | } 31 | } 32 | 33 | public IEnumerator RepeatLerp(Vector3 a, Vector3 b, float time) { 34 | float i = 0.0f; 35 | float rate = (1.0f / time) * speed; 36 | while (i < 1.0f) { 37 | i += Time.deltaTime * rate; 38 | this.transform.position = Vector3.Lerp(a, b, i); 39 | yield return null; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /LevelGenerator.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public class LevelGenerator : MonoBehaviour { 4 | 5 | public Texture2D map; 6 | 7 | public ColorToPrefab[] colorMappings; 8 | 9 | // Use this for initialization 10 | void Start () { 11 | GenerateLevel(); 12 | } 13 | 14 | void GenerateLevel () 15 | { 16 | for (int x = 0; x < map.width; x++) 17 | { 18 | for (int y = 0; y < map.height; y++) 19 | { 20 | GenerateTile(x, y); 21 | } 22 | } 23 | } 24 | 25 | void GenerateTile (int x, int y) 26 | { 27 | Color pixelColor = map.GetPixel(x, y); 28 | 29 | if (pixelColor.a == 0) 30 | { 31 | // The pixel is transparrent. Let's ignore it! 32 | return; 33 | } 34 | 35 | foreach (ColorToPrefab colorMapping in colorMappings) 36 | { 37 | if (colorMapping.color.Equals(pixelColor)) 38 | { 39 | Vector2 position = new Vector2(x, y); 40 | Instantiate(colorMapping.prefab, position, Quaternion.identity, transform); 41 | } 42 | } 43 | } 44 | 45 | } 46 | 47 | 48 | 49 | ColorToPrefab.cs 50 | **************** 51 | using UnityEngine; 52 | 53 | [System.Serializable] 54 | public class ColorToPrefab { 55 | 56 | public Color color; 57 | public GameObject prefab; 58 | 59 | } 60 | 61 | -------------------------------------------------------------------------------- /LightAdjuster.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class LightAdjuster : MonoBehaviour { 6 | 7 | public Light myLight; 8 | 9 | // Range Variables 10 | public bool changeRange = false; 11 | public float rangeSpeed = 1.0f; 12 | public float maxRange = 10.0f; 13 | public bool repeatRange = false; 14 | 15 | // Intensity Variables 16 | public bool changeIntensity = false; 17 | public float intensitySpeed = 1.0f; 18 | public float maxIntensity = 10.0f; 19 | public bool repeatIntensity = false; 20 | 21 | // Color variables 22 | public bool changeColors = false; 23 | public float colorSpeed = 1.0f; 24 | public Color startColor; 25 | public Color endColor; 26 | public bool repeatColor = false; 27 | 28 | float startTime; 29 | 30 | // Use this for initialization 31 | void Start () { 32 | myLight = GetComponent(); 33 | startTime = Time.time; 34 | } 35 | 36 | // Update is called once per frame 37 | void Update () { 38 | if(changeRange) { 39 | if(repeatRange) { 40 | myLight.range = Mathf.PingPong(Time.time * rangeSpeed, maxRange); 41 | } else { 42 | myLight.range = Time.time * rangeSpeed; 43 | if(myLight.range >= maxRange) { 44 | changeRange = false; 45 | } 46 | } 47 | } 48 | 49 | if(changeIntensity) { 50 | if(repeatIntensity) { 51 | myLight.intensity = Mathf.PingPong(Time.time * intensitySpeed, maxIntensity); 52 | } else { 53 | myLight.intensity = Time.time * intensitySpeed; 54 | if(myLight.intensity >= maxIntensity) { 55 | changeIntensity = false; 56 | } 57 | } 58 | } 59 | 60 | if(changeColors) { 61 | if(repeatColor) { 62 | float t = (Mathf.Sin(Time.time - startTime * colorSpeed)); 63 | myLight.color = Color.Lerp(startColor, endColor, t); 64 | } else { 65 | float t = Time.time - startTime * colorSpeed; 66 | myLight.color = Color.Lerp(startColor, endColor, t); 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /ListExamples.cs: -------------------------------------------------------------------------------- 1 | public List balloonList = new List(); 2 | #region FIND BALLOONS 3 | foreach (GameObject balloonsFinded in GameObject.FindGameObjectsWithTag("Balloon")) 4 | { 5 | if (balloonsFinded.GetComponent().balloonLive) 6 | { 7 | balloonList.Add(balloonsFinded); 8 | } 9 | } 10 | #endregion 11 | 12 | using System.Linq; 13 | GameObject temp = list.Where(obj => obj.name == "Sword").SingleOrDefault(); 14 | 15 | Inventory item = inventario.Find(x=> x.name == komeslipapes); 16 | if(item == null){ 17 | Debug.Log ("No!"); 18 | } 19 | else{ 20 | Debug.Log ("Yes!"); 21 | } 22 | 23 | bool hasApple = inventario.Any(x => x.name == "Apple"); 24 | 25 | EnemyInfo enemyInList = enemyList.Find( x => x.enemy==target); 26 | 27 | public List dropObject(GameObject gameObjectYouWantToDrop) { 28 | //if you want to find the gameObject itself, just replace FindIndex with Find 29 | Vector3 myLocation = new Vector3 (x,y,z); 30 | int indexOfYourGameObject = inventory.FindIndex(x => x.Equals(gameObjectYouWantToDrop)); 31 | Instantiate (inventory[indexOfYourGameObject] , myLocation); 32 | inventory.RemoveAt(indexOfYourGameObject); 33 | return inventory; 34 | } 35 | 36 | int findIndex = GameManager.instance.balloonList.FindIndex(obj => obj.GetComponent().balloonNumber == balloonIndex); 37 | Debug.Log("Findex: " + findIndex); 38 | -------------------------------------------------------------------------------- /LivingBox.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using Ballistics; 4 | 5 | public class LivingBox : LivingEntity { 6 | 7 | /// 8 | /// called when Health is 0 9 | /// 10 | public override void OnDeath() 11 | { 12 | //Debug.Log("Dead"); 13 | } 14 | 15 | /// 16 | /// called when health value changed 17 | /// 18 | /// 19 | public override void OnHealthChanged(float amount) 20 | { 21 | Debug.Log(transform.name + " took " + (-amount).ToString() + " damage"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LivingEntity.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | 5 | namespace Ballistics 6 | { 7 | public class LivingEntity : MonoBehaviour 8 | { 9 | /// 10 | /// maximum health 11 | /// 12 | public float StartHealth; 13 | 14 | /// 15 | /// health handler 16 | /// 17 | [HideInInspector] 18 | public float Health 19 | { 20 | get { return myHealth; } 21 | set 22 | { 23 | float before = myHealth; 24 | if (value > 0f && value <= StartHealth) 25 | { 26 | myHealth = value; 27 | } 28 | else 29 | { 30 | if (value > 0f) 31 | { 32 | myHealth = StartHealth; 33 | } 34 | else 35 | { 36 | myHealth = 0; 37 | OnDeath(); 38 | } 39 | } 40 | OnHealthChanged(value - before); 41 | } 42 | } 43 | 44 | private float myHealth = 0; 45 | 46 | void Awake() 47 | { 48 | myHealth = StartHealth; 49 | } 50 | 51 | /// 52 | /// called when health is 0 53 | /// 54 | public virtual void OnDeath() 55 | { } 56 | 57 | /// 58 | /// called when the health value changed 59 | /// 60 | /// value of the change 61 | public virtual void OnHealthChanged(float amount) 62 | { 63 | 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /LivingEntityCollider.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | namespace Ballistics 5 | { 6 | public class LivingEntityCollider : MonoBehaviour 7 | { 8 | //set (for example) to 0.75f when LivingEntity has armor 9 | public float DamageMultiplier = 1; 10 | 11 | //when LivingEntityCollider is child of a GameObject with LivingEntity 12 | //ParentLE can be set automatically through LivingEntity-Inspector (Button) 13 | public LivingEntity ParentLivingEntity; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /LockOnTarget.cs: -------------------------------------------------------------------------------- 1 | Target curTarget; //gameobject 2 | 3 | [Header("Rotate Settings")] 4 | private Vector3 targetPos; 5 | public Transform partToRotate; 6 | [Range(0, 1)] 7 | [SerializeField] private float _turnSpeed; 8 | public float turnSpeed 9 | { 10 | get 11 | { 12 | return Mathf.Lerp(.1f, 10f, _turnSpeed); 13 | } 14 | set 15 | { 16 | _turnSpeed = value; 17 | } 18 | } 19 | 20 | void Update(){ 21 | targets = GameObject.FindGameObjectsWithTag("Target"); 22 | foreach (var target in targets) { 23 | var t = target.GetComponent(); 24 | if (t) { 25 | curTarget = t; 26 | break; 27 | } 28 | } 29 | } 30 | 31 | public void LockOnTarget() 32 | { 33 | targetPos = curTarget.transform.position; 34 | Vector3 dir = targetPos - transform.position; 35 | Quaternion lookRotation = Quaternion.LookRotation(dir); 36 | Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles; 37 | partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f); 38 | } 39 | -------------------------------------------------------------------------------- /LookAtTarget.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using UnityEngine; 3 | 4 | public class LookAtTarget : MonoBehaviour 5 | { 6 | public Transform Target; 7 | public float Speed = 1f; 8 | 9 | private Coroutine LookCoroutine; 10 | 11 | public void StartRotating() 12 | { 13 | if (LookCoroutine != null) 14 | { 15 | StopCoroutine(LookCoroutine); 16 | } 17 | 18 | LookCoroutine = StartCoroutine(LookAt()); 19 | } 20 | 21 | private IEnumerator LookAt() 22 | { 23 | Quaternion lookRotation = Quaternion.LookRotation(Target.position - transform.position); 24 | 25 | float time = 0; 26 | 27 | Quaternion initialRotation = transform.rotation; 28 | while (time < 1) 29 | { 30 | transform.rotation = Quaternion.Slerp(initialRotation, lookRotation, time); 31 | 32 | time += Time.deltaTime * Speed; 33 | 34 | yield return null; 35 | } 36 | } 37 | 38 | // You can remove this, it is only for the demo. 39 | private void OnGUI() 40 | { 41 | if (GUI.Button(new Rect(10, 10, 200, 30), "Look At")) 42 | { 43 | StartRotating(); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /MapBuilderVertical.cs: -------------------------------------------------------------------------------- 1 | public class MapBuilderVertical : MonoBehaviour 2 | { 3 | 4 | public GameObject[] tilePrefabs; 5 | 6 | private Transform playerTransform; 7 | private float spawnY = 0.0f; 8 | private float tileLength = 10f; 9 | private int amnTilesOnScreen = 4; 10 | 11 | private void Awake() 12 | { 13 | playerTransform = GameObject.FindGameObjectWithTag("Player").transform; 14 | for (int i = 0; i < amnTilesOnScreen; i++) 15 | { 16 | SpawnTile(); 17 | 18 | } 19 | 20 | } 21 | // Update is called once per frame 22 | private void Update() 23 | { 24 | if (playerTransform != null && playerTransform.position.y > (spawnY - amnTilesOnScreen * tileLength)) 25 | { 26 | SpawnTile(); 27 | } 28 | } 29 | private void SpawnTile(int prefabIndex = -1) 30 | { 31 | GameObject go; 32 | go = Instantiate(tilePrefabs[0]) as GameObject; 33 | go.transform.SetParent(transform); 34 | go.transform.position = Vector3.up * spawnY; 35 | spawnY += tileLength; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /MapGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | [System.Serializable] 6 | public class ColorToPrefab 7 | { 8 | public Color color; 9 | public GameObject prefab; 10 | public float PosY; 11 | } 12 | 13 | public class MapGenerator : MonoBehaviour 14 | { 15 | public List LevelImages = new List(); 16 | 17 | public List ColorMaps = new List(); 18 | 19 | public Transform LevelMap; 20 | 21 | private void Start() 22 | { 23 | GenerateMap(0); 24 | } 25 | 26 | private void GenerateMap(int index) 27 | { 28 | for (int x = 0; x < LevelImages[index].width; x++) 29 | { 30 | for (int z = 0; z < LevelImages[index].height; z++) 31 | { 32 | GenerateTile(x, z, index); 33 | } 34 | } 35 | } 36 | 37 | private void GenerateTile(int x, int z, int index) 38 | { 39 | Color pixelColor = LevelImages[index].GetPixel(x, z); 40 | 41 | if (pixelColor.a != 0) 42 | { 43 | foreach (ColorToPrefab ColorMap in ColorMaps) 44 | { 45 | if (ColorMap.color.Equals(pixelColor)) 46 | { 47 | Vector3 tilePos = new Vector3(x, ColorMap.PosY, z); 48 | GameObject tile = Instantiate(ColorMap.prefab, tilePos, Quaternion.identity, LevelMap); 49 | break; 50 | } 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /MaterialChanger.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace myProject 6 | { 7 | public class MaterialChanger : MonoBehaviour 8 | { 9 | [SerializeField] 10 | Material material; 11 | 12 | [SerializeField] 13 | float interval = 0.1f; 14 | 15 | [SerializeField] 16 | bool loop = false; 17 | 18 | 19 | Material originalMaterial; 20 | 21 | 22 | private void OnEnable() 23 | { 24 | Renderer ren = GetComponent(); 25 | this.originalMaterial = ren.sharedMaterial; 26 | StartCoroutine(PlayMaterial()); 27 | } 28 | 29 | 30 | private void OnDisable() 31 | { 32 | Renderer ren = GetComponent(); 33 | ren.material = this.originalMaterial; 34 | } 35 | 36 | 37 | IEnumerator PlayMaterial() 38 | { 39 | Renderer ren = GetComponent(); 40 | 41 | if (this.loop) 42 | { 43 | while (true) 44 | { 45 | ren.material = this.material; 46 | yield return new WaitForSeconds(this.interval); 47 | 48 | ren.material = this.originalMaterial; 49 | yield return new WaitForSeconds(this.interval); 50 | } 51 | } 52 | else 53 | { 54 | ren.material = this.material; 55 | yield return new WaitForSeconds(this.interval); 56 | } 57 | 58 | base.enabled = false; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /MaterialPropertyBlock.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using UnityEngine; 5 | 6 | public class MaterialPropertyBlock : MonoBehaviour 7 | { 8 | [SerializedField] private Color mainColor = Color.black; 9 | private Renderer _renderer = null; 10 | private MaterialPropertyBlock _materialPropertyBlock = null; 11 | 12 | private void Start(){ 13 | _renderer = GetComponent(); 14 | _materialPropertyBlock = new MaterialPropertyBlock(); 15 | } 16 | 17 | private void Update(){ 18 | _materialPropertyBlock.SetColor("_Color", mainColor); 19 | _renderer.SetPropertyBlock(_materialPropertyBlock); 20 | } 21 | } 22 | 23 | // Add new shader -> add to head [PerRendererData] tag to property 24 | // eg. [PerRendererData] _Color ("Color", Color) = (1,1,1,1) 25 | 26 | // Sample Case: 27 | /* 28 | public class MeshBall : MonoBehaviour 29 | { 30 | static int baseColorId = Shader.PropertyToID("_BaseColor"); 31 | [SerializeField] 32 | Mesh ballmesh = default; 33 | [SerializeField] 34 | Material instancedMaterial = default; 35 | 36 | Matrix4x4[] matrices = new Matrix4x4[1023]; 37 | 38 | Vector4[] colors = new Vector4[1023]; 39 | 40 | MaterialPropertyBlock materialBlock; 41 | 42 | // Update is called once per frame 43 | void Awake() 44 | { 45 | for (int i = 0; i < matrices.Length; i++) 46 | { 47 | matrices[i] = Matrix4x4.TRS(Random.insideUnitSphere * 50f, Quaternion.identity, Vector3.one); 48 | colors[i] = new Vector4(Random.value, Random.value, Random.value, Random.Range(0.5f, 1f)); 49 | } 50 | } 51 | 52 | 53 | void Update() 54 | { 55 | if (materialBlock == null) 56 | { 57 | materialBlock = new MaterialPropertyBlock(); 58 | materialBlock.SetVectorArray(baseColorId, colors); 59 | } 60 | 61 | Graphics.DrawMeshInstanced(ballmesh, 0, instancedMaterial, matrices, 1023, materialBlock); 62 | } 63 | } 64 | */ 65 | -------------------------------------------------------------------------------- /MatthiasWindZone.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class MatthiasWindZone : MonoBehaviour { 6 | 7 | List RigidbodiesInWindZoneList = new List(); 8 | public Vector3 windDirection = Vector3.right; 9 | public float windStrength = 5; 10 | 11 | private void OnTriggerEnter(Collider col) 12 | { 13 | Rigidbody objectRigid = col.gameObject.GetComponent(); 14 | if(objectRigid != null) 15 | RigidbodiesInWindZoneList.Add(objectRigid); 16 | } 17 | 18 | private void OnTriggerExit(Collider col) 19 | { 20 | Rigidbody objectRigid = col.gameObject.GetComponent(); 21 | if (objectRigid != null) 22 | RigidbodiesInWindZoneList.Remove(objectRigid); 23 | } 24 | 25 | private void FixedUpdate() 26 | { 27 | if(RigidbodiesInWindZoneList.Count > 0) { 28 | foreach (Rigidbody rigid in RigidbodiesInWindZoneList) 29 | { 30 | rigid.AddForce(windDirection * windStrength); 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /MeshExtensions.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public static Mesh ScaleMesh(this Mesh mesh, float scale) 4 | { 5 | var vertices = mesh.vertices; 6 | 7 | for (int i = 0; i < vertices.Length; i++) 8 | { 9 | Vector3 vertex = vertices[i]; 10 | vertex += mesh.normals[i] * scale; 11 | vertices[i] = vertex; 12 | } 13 | 14 | mesh.vertices = vertices; 15 | mesh.RecalculateBounds(); 16 | return mesh; 17 | } 18 | 19 | public static Mesh ScaleCentered(this Mesh mesh, Vector3 scale) 20 | { 21 | var vertices = mesh.vertices; 22 | 23 | for (int i = 0; i < vertices.Length; i++) 24 | { 25 | Vector3 vertex = vertices[i] - mesh.bounds.center; 26 | vertex.x *= scale.x; 27 | vertex.y *= scale.y; 28 | vertex.z *= scale.z; 29 | vertices[i] = vertex + mesh.bounds.center; 30 | } 31 | 32 | mesh.vertices = vertices; 33 | mesh.RecalculateBounds(); 34 | return mesh; 35 | } 36 | 37 | public static Mesh ScaleCentered(this Mesh mesh, float scale) 38 | { 39 | return ScaleCentered(mesh, new Vector3(scale, scale, scale)); 40 | } 41 | 42 | public static Mesh AddOffset(this Mesh mesh, float offset) 43 | { 44 | var vertices = mesh.vertices; 45 | 46 | for (int i = 0; i < vertices.Length; i++) 47 | { 48 | Vector3 vertex = vertices[i]; 49 | vertex += mesh.normals[i] * offset; 50 | vertices[i] = vertex; 51 | } 52 | 53 | mesh.vertices = vertices; 54 | mesh.RecalculateBounds(); 55 | return mesh; 56 | } 57 | 58 | public static Mesh Clone(this Mesh mesh) 59 | { 60 | Mesh newMesh = new Mesh(); 61 | newMesh.vertices = mesh.vertices; 62 | newMesh.normals = mesh.normals; 63 | newMesh.triangles = mesh.triangles; 64 | 65 | return newMesh; 66 | } 67 | 68 | public static Mesh InvertNormals(this Mesh mesh) 69 | { 70 | Vector3[] normals = mesh.normals; 71 | for (int i = 0; i < normals.Length; i++) 72 | { 73 | normals[i] *= -1; 74 | } 75 | 76 | mesh.normals = normals; 77 | mesh.RecalculateNormals(); 78 | return mesh; 79 | } 80 | -------------------------------------------------------------------------------- /MilesPerHour.cs: -------------------------------------------------------------------------------- 1 | public class MilesPerHour : MonoBehaviour 2 | { 3 | public float milesPerHour = 0f; 4 | 5 | [Space(20)] 6 | 7 | public float metersTravelledPerSecond; 8 | public float metersTravelledPerMinute; 9 | public float metersTravelledPerHour; 10 | 11 | // Got this value from a google search. Unity uses meters, 12 | // and one meter = 0.000621371f miles. 13 | private float metersToMiles = 0.000621371f; 14 | private Vector3 prevPosition = Vector3.zero; 15 | 16 | // Use this for initialization 17 | void Start() 18 | { 19 | prevPosition = transform.position; 20 | } 21 | 22 | private void FixedUpdate() 23 | { 24 | Vector3 v = transform.position - prevPosition; 25 | 26 | float distance = v.magnitude; 27 | if (distance < 0.0002f) 28 | distance = 0f; 29 | 30 | // Get the meters travelled per second. 31 | metersTravelledPerSecond = distance / Time.deltaTime; 32 | 33 | // Meters per minute. There are 60 seconds in one minute! 34 | metersTravelledPerMinute = metersTravelledPerSecond * 60f; 35 | 36 | // Meters per hour. There are 60 minutes in one hour! 37 | metersTravelledPerHour = metersTravelledPerMinute * 60f; 38 | 39 | // Finally, multiply are speed - which is in meters - by our conversion variable to get the miles per hour. 40 | milesPerHour = metersTravelledPerHour * metersToMiles; 41 | 42 | prevPosition = transform.position; 43 | } 44 | 45 | 46 | } 47 | -------------------------------------------------------------------------------- /MonoBehaviourBase.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class MonoBehaviourBase : MonoBehaviour { 5 | public delegate void Task(); 6 | 7 | public void Invoke(Task task, float time) { 8 | Invoke(task.Method.Name, time); 9 | } 10 | 11 | static public Transform FindInChildren( Transform t, string name ) { 12 | Transform r = null; 13 | 14 | foreach ( Transform child in t ) { 15 | if ( child.name.ToLower() == name.ToLower() ) { 16 | r = child; 17 | break; 18 | } 19 | } 20 | 21 | if ( r == null ) { 22 | foreach ( Transform child in t ) { 23 | r = FindInChildren( child, name ); 24 | if ( r != null ) { 25 | break; 26 | } 27 | } 28 | } 29 | 30 | return r; 31 | } 32 | 33 | static public void SetLayerRecursively( GameObject go, int layer ) { 34 | go.layer = layer; 35 | foreach ( Transform t in go.transform ) { 36 | SetLayerRecursively( t.gameObject, layer ); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MovingEnemy.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using UnityEngine; 5 | 6 | public class MovingEnemy : MonoBehaviour 7 | { 8 | 9 | public Transform pos1; 10 | public Transform pos2; 11 | public Transform movingEnemy; 12 | public float delayBetweenTransform = 1; 13 | public float movingEnemyMovingTime = 1; 14 | // Use this for initialization 15 | void Start() 16 | { 17 | movingEnemy.position = pos1.position; 18 | StartCoroutine(MoveEnemy()); 19 | } 20 | 21 | private IEnumerator MoveEnemy() 22 | { 23 | yield return null; 24 | while (gameObject.activeInHierarchy) 25 | { 26 | Vector3 targetPos = GetTargetPos(); 27 | float distance = (targetPos - movingEnemy.position).magnitude; 28 | float movedDistance = 0; 29 | while (movedDistance < distance) 30 | { 31 | Vector3 d = (targetPos - transform.position).normalized * distance / movingEnemyMovingTime * Time.fixedDeltaTime; 32 | movingEnemy.position += d; 33 | movedDistance += d.magnitude; 34 | yield return null; 35 | } 36 | yield return new WaitForSeconds(delayBetweenTransform); 37 | } 38 | } 39 | 40 | private Vector3 GetTargetPos() 41 | { 42 | if ((movingEnemy.position - pos1.position).magnitude < (pos2.position - pos1.position).magnitude / 2) 43 | { 44 | return pos2.position; 45 | } 46 | else 47 | { 48 | return pos1.position; 49 | } 50 | } 51 | 52 | // Update is called once per frame 53 | void Update() 54 | { 55 | 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /NeighborsDirectionExtensions.cs: -------------------------------------------------------------------------------- 1 | public enum NeighborsDirection { 2 | NORTH, 3 | EAST, 4 | SOUTH, 5 | WEST 6 | } 7 | 8 | public static class NeighborsDirectionExtensions { 9 | public static NeighborsDirection Opppsite( this NeighborsDirection direction ) { 10 | return (int)direction < 2 ? ( direction + 2 ) : ( direction -2 ); 11 | } 12 | 13 | public static NeighborsDirection Previous( this NeighborsDirection direction ) { 14 | return direction == NeighborsDirection.NORTH ? NeighborsDirection.WEST : direction -1; 15 | } 16 | 17 | public static NeighborsDirection Next ( this NeighborsDirection direction ) { 18 | return direction == NeighborsDirection.WEST ? NeighborsDirection.NORTH : direction +1; 19 | } 20 | 21 | public static Vector2 Vector( this NeighborsDirection direction ) { 22 | switch (direction) { 23 | case NeighborsDirection.NORTH: 24 | return Vector2.up; 25 | case NeighborsDirection.EAST: 26 | return Vector2.right; 27 | case NeighborsDirection.SOUTH: 28 | return Vector2.down; 29 | default: 30 | return Vector2.left; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /OffsetUVs.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class OffsetUVs : MonoBehaviour 5 | { 6 | public Material mat; 7 | public Vector2 offset; 8 | 9 | void Awake() { 10 | offset = new Vector2( 0, 0 ); 11 | } 12 | 13 | void Update() { 14 | mat.SetTextureOffset( "_MainTex", offset ); 15 | } 16 | 17 | void OnDisable() { 18 | mat.SetTextureOffset( "_MainTex", Vector2.zero ); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /OnParticleCollision.cs: -------------------------------------------------------------------------------- 1 | protected override void OnParticleCollision(GameObject hitTarget) 2 | { 3 | base.OnParticleCollision(hitTarget); 4 | 5 | Agent hitAgent = hitTarget.GetComponent(); 6 | 7 | if (!CheckForFriendlyFire(hitAgent)) 8 | hitAgent.TakeDamage(CurrentStage.Damage, DamageSource.Bullet); 9 | 10 | } 11 | -------------------------------------------------------------------------------- /Orbit.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class Orbit : MonoBehaviour { 6 | 7 | public float xSpread; 8 | public float zSpread; 9 | public float yOffset; 10 | public Transform centerPoint; 11 | 12 | public float rotSpeed; 13 | public bool rotateClockwise; 14 | 15 | float timer = 0; 16 | 17 | // Update is called once per frame 18 | void Update () { 19 | timer += Time.deltaTime * rotSpeed; 20 | Rotate(); 21 | } 22 | 23 | void Rotate() { 24 | if(rotateClockwise) { 25 | float x = -Mathf.Cos(timer) * xSpread; 26 | float z = Mathf.Sin(timer) * zSpread; 27 | Vector3 pos = new Vector3(x, yOffset, z); 28 | transform.position = pos + centerPoint.position; 29 | } else { 30 | float x = Mathf.Cos(timer) * xSpread; 31 | float z = Mathf.Sin(timer) * zSpread; 32 | Vector3 pos = new Vector3(x, yOffset, z); 33 | transform.position = pos + centerPoint.position; 34 | } 35 | } 36 | } 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /ParseINT.cs: -------------------------------------------------------------------------------- 1 | // Benchmark: 2 | // int.Parse("400") 123.07 ns 3 | // IntParseFast("400") 2.87 ns 4 | public static int IntParseFast(string value) 5 | { 6 | int result = 0; 7 | for (int i = 0; i < value.Length; i++) 8 | { 9 | char letter = value[i]; 10 | result = 10 * result + (letter - 48); 11 | } 12 | return result; 13 | } 14 | 15 | public static int IntParseFast(char value) 16 | { 17 | int result = 0; 18 | result = 10 * result + (value - 48); 19 | return result; 20 | } 21 | -------------------------------------------------------------------------------- /PathScript.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using UnityEngine; 3 | 4 | public class PathScript : MonoBehaviour 5 | { 6 | public LineRenderer line; 7 | private List points = new List(); 8 | 9 | // Use this for initialization 10 | public void start(LineRenderer lines) 11 | { 12 | points.Clear(); 13 | line = lines; 14 | GameObject caret = null; 15 | caret = new GameObject("Lines"); 16 | 17 | Vector3 left, right; // A position to the left of the current line 18 | 19 | // For all but the last point 20 | for (var i = 0; i < line.positionCount - 1; i++) 21 | { 22 | caret.transform.position = line.GetPosition(i); 23 | caret.transform.LookAt(line.GetPosition(i + 1)); 24 | right = caret.transform.position + transform.right * line.startWidth / 2; 25 | left = caret.transform.position - transform.right * line.startWidth / 2; 26 | points.Add(left); 27 | points.Add(right); 28 | } 29 | 30 | // Last point looks backwards and reverses 31 | caret.transform.position = line.GetPosition(line.positionCount - 1); 32 | caret.transform.LookAt(line.GetPosition(line.positionCount - 2)); 33 | right = caret.transform.position + transform.right * line.startWidth / 2; 34 | left = caret.transform.position - transform.right * line.startWidth / 2; 35 | points.Add(left); 36 | points.Add(right); 37 | Destroy(caret); 38 | DrawMesh(); 39 | } 40 | 41 | private void DrawMesh() 42 | { 43 | Vector3[] verticies = new Vector3[points.Count]; 44 | 45 | for (int i = 0; i < verticies.Length; i++) 46 | { 47 | verticies[i] = points[i]; 48 | } 49 | 50 | int[] triangles = new int[((points.Count / 2) - 1) * 6]; 51 | 52 | //Works on linear patterns tn = bn+c 53 | int position = 6; 54 | for (int i = 0; i < (triangles.Length / 6); i++) 55 | { 56 | triangles[i * position] = 2 * i; 57 | triangles[i * position + 3] = 2 * i; 58 | 59 | triangles[i * position + 1] = 2 * i + 3; 60 | triangles[i * position + 4] = (2 * i + 3) - 1; 61 | 62 | triangles[i * position + 2] = 2 * i + 1; 63 | triangles[i * position + 5] = (2 * i + 1) + 2; 64 | } 65 | 66 | 67 | Mesh mesh = GetComponent().mesh; 68 | mesh.Clear(); 69 | mesh.vertices = verticies; 70 | mesh.triangles = triangles; 71 | mesh.RecalculateNormals(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /PauseWaitResume.cs: -------------------------------------------------------------------------------- 1 | /* 1 */ 2 | 3 | function PauseWaitResume (pauseDelay : float) { 4 | Time.timeScale = .0000001; 5 | yield WaitForSeconds(pauseDelay * Time.timeScale); 6 | Time.timeScale = 1.0; 7 | } 8 | 9 | /* 2 */ 10 | 11 | void PauseAndResume() 12 | { 13 | Time.timeScale = 0; 14 | //Display Image here 15 | StartCoroutine(ResumeAfterNSeconds(3.0f)); 16 | } 17 | 18 | float timer = 0; 19 | IEnumerator ResumeAfterNSeconds(float timePeriod) 20 | { 21 | yield return new WaitForEndOfFrame(); 22 | timer += Time.unscaledDeltaTime; 23 | if(timer < timePeriod) 24 | StartCoroutine(ResumeAfterNSeconds(3.0f)); 25 | else 26 | { 27 | Time.timeScale = 1; //Resume 28 | timer = 0; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /PerlinNoise.cs: -------------------------------------------------------------------------------- 1 | private float maxOffset = 3f; 2 | 3 | void Update(){ 4 | float noise = Mathf.PerlinNoise(transform.position.x / 10f + Time.time, transform.position.z /10f + Time.time); 5 | transform.Localscale = new Vector3(1f, noise * maxOffset, 1f); 6 | } 7 | -------------------------------------------------------------------------------- /Proximity_Sensor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using UnityEngine; 5 | 6 | ////// 7 | /// Author: Nicolas Granese. 8 | /// To contact the author, please use the electronic address nicolasgranese65@gmail.com 9 | ////// 10 | 11 | /// 12 | /// This script takes the shortest distance from several raycasts. 13 | /// 14 | 15 | public class Proximity_sensor : MonoBehaviour 16 | { 17 | public Transform[] sensors; 18 | public RaycastHit[] hitINFO; 19 | public LayerMask rayMask; 20 | public float maxRayDistance = 5f; 21 | private readonly float min = 1.5f, max = 4.0f; 22 | 23 | private float maxDist = Mathf.Infinity; 24 | public float factor; 25 | 26 | private int distIndex = 0; 27 | public int actualIndex; 28 | 29 | // Update is called once per frame 30 | void Update() 31 | { 32 | ProximitySensor(); 33 | } 34 | 35 | void ProximitySensor() 36 | { 37 | hitINFO = new RaycastHit[sensors.Length]; 38 | for (int n = 0; n < sensors.Length; n++) 39 | { 40 | 41 | if (Physics.Raycast(sensors[n].transform.position, sensors[n].transform.right, out hitINFO[n], maxRayDistance, rayMask)) // Uses local rotation 42 | { 43 | Debug.DrawRay(sensors[n].transform.position, sensors[n].transform.right * hitINFO[n].distance, Color.red); 44 | 45 | // Gets the shortest hit distance. 46 | if (hitINFO[n].distance < maxDist) 47 | { 48 | maxDist = hitINFO[n].distance; 49 | distIndex = n; 50 | } 51 | else 52 | { 53 | distIndex = sensors.Length + 1; 54 | maxDist = hitINFO[n].distance; 55 | } 56 | } 57 | else 58 | { 59 | Debug.DrawRay(sensors[n].position, sensors[n].right * maxRayDistance, Color.green); 60 | 61 | maxDist = Mathf.Infinity; 62 | } 63 | if (distIndex != (sensors.Length + 1)) 64 | { 65 | // Generates the interpolation factor. 66 | actualIndex = distIndex; 67 | factor = Mathf.InverseLerp(max, min, hitINFO[actualIndex].distance); 68 | 69 | // Command line debug. 70 | string debug = string.Format("Shortest Hit Index: {0} | Distance: {1} | Interpolation: {2}", actualIndex, hitINFO[actualIndex].distance, factor); 71 | print(debug); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Unity-Scripts 2 | Unity Script Samples 3 | -------------------------------------------------------------------------------- /RandomColor.cs: -------------------------------------------------------------------------------- 1 | string seed = Time.time.ToString(); 2 | System.Random random = new System.Random(seed.GetHashCode()); 3 | Color randomColor = new Color( 4 | (float)random.Next(0, 255), 5 | (float)random.Next(0, 255), 6 | (float)random.Next(0, 255) 7 | ); 8 | -------------------------------------------------------------------------------- /RandomPointOnMesh.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | namespace Utils { 5 | 6 | public class RandomPointOnMesh { 7 | 8 | public static Vector3 Sample (Mesh mesh) { 9 | int[] triangles = mesh.triangles; 10 | int index = Mathf.FloorToInt(Random.value * (triangles.Length / 3)); 11 | Vector3 v0 = mesh.vertices[triangles[index * 3 + 0]]; 12 | Vector3 v1 = mesh.vertices[triangles[index * 3 + 1]]; 13 | Vector3 v2 = mesh.vertices[triangles[index * 3 + 2]]; 14 | return Vector3.Lerp(v0, Vector3.Lerp(v1, v2, Random.value), Random.value); 15 | } 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /RandomRotation.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class RandomRotation : MonoBehaviour 6 | { 7 | private bool right; 8 | 9 | public float rotateSpeed = 10; 10 | public AnimationCurve lerpEase = default; 11 | public float yRot; 12 | 13 | [Space] 14 | [Header("Ghost Aim")] 15 | public Transform player; 16 | 17 | private void OnEnable() 18 | { 19 | StartCoroutine(RotateTo()); 20 | StartCoroutine(ChooseDir()); 21 | } 22 | 23 | IEnumerator RotateTo() 24 | { 25 | yRot += Random.Range(15, 45) * (right ? 1 : -1); 26 | float distance = Mathf.Abs(Mathf.DeltaAngle(transform.localEulerAngles.y, yRot)); 27 | 28 | Quaternion startRot = transform.rotation; 29 | Quaternion endRot = Quaternion.Euler(0, yRot, 0); 30 | 31 | float animateTime = 0; 32 | float animationLength = distance / rotateSpeed; 33 | 34 | while (animateTime < animationLength) 35 | { 36 | animateTime += Time.deltaTime; 37 | transform.rotation = Quaternion.Slerp(startRot, endRot, lerpEase.Evaluate(animateTime / (animationLength))); 38 | yield return null; 39 | } 40 | 41 | StartCoroutine(RotateTo()); 42 | } 43 | 44 | IEnumerator ChooseDir() 45 | { 46 | yield return new WaitForSeconds(Random.Range(1, 3)); 47 | right = (Random.value > 0.5f); 48 | StartCoroutine(ChooseDir()); 49 | } 50 | 51 | private void OnDisable() 52 | { 53 | StopCoroutine("RotateTo"); 54 | StopCoroutine("ChooseDir"); 55 | StopAllCoroutines(); 56 | } 57 | 58 | private void OnDestroy() 59 | { 60 | if(FindObjectOfType() != null) 61 | transform.rotation = FindObjectOfType().transform.rotation; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /RandomSeed.cs: -------------------------------------------------------------------------------- 1 | Update(){ 2 | Random.seed = 12345; 3 | Debug.Log(Random.Range(0,10)); //returns 6 every time 4 | Debug.Log(Random.Range(0,10)); //returns 2 every time 5 | } 6 | -------------------------------------------------------------------------------- /RandomSpawner.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class RandomSpawner : MonoBehaviour { 6 | 7 | public GameObject[] spawnees; 8 | public Transform spawnPos; 9 | 10 | int randomInt; 11 | 12 | // Update is called once per frame 13 | void Update () { 14 | if(Input.GetMouseButton(0)) { 15 | SpawnRandom(); 16 | } 17 | } 18 | 19 | void SpawnRandom() { 20 | randomInt = Random.Range(0, spawnees.Length); 21 | Instantiate(spawnees[randomInt], spawnPos.position, spawnPos.rotation); 22 | } 23 | } -------------------------------------------------------------------------------- /RaycastPlayerDoorOpen.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | // attach to players head (player on layer "Player") 6 | public class Interact : MonoBehaviour 7 | { 8 | [SerializeField] KeyCode interactionKey = KeyCode.E; 9 | [SerializeField] float interactingRange = 2; 10 | LayerMask layerMask; 11 | 12 | private void Start() 13 | { 14 | // layer mask that represents every layer except player 15 | layerMask = Physics.DefaultRaycastLayers & ~(1 << LayerMask.NameToLayer("Player")); 16 | } 17 | 18 | void Update() 19 | { 20 | if (Input.GetKeyDown(interactionKey)) 21 | { 22 | AttemptInteraction(); 23 | } 24 | } 25 | 26 | void AttemptInteraction() 27 | { 28 | var ray = new Ray(transform.position, transform.forward); 29 | RaycastHit hit; 30 | 31 | if (Physics.Raycast(ray, out hit, interactingRange, layerMask)) 32 | { 33 | var interactable = hit.collider.GetComponent(); 34 | 35 | if (!ReferenceEquals(interactable, null)) 36 | { 37 | interactable.Interact(); 38 | } 39 | } 40 | } 41 | } 42 | 43 | DoorInteract.cs 44 | ################################### 45 | using System.Collections; 46 | using System.Collections.Generic; 47 | using UnityEngine; 48 | 49 | // attach to door with collider 50 | 51 | [RequireComponent(typeof(Collider))] 52 | 53 | public class DoorInteract : MonoBehaviour 54 | { 55 | Animator anim; 56 | public bool dooropen = false; 57 | 58 | private void Start() 59 | { 60 | anim = GetComponent(); 61 | } 62 | 63 | public void Interact() 64 | { 65 | ToggleDoor(); 66 | } 67 | 68 | void ToggleDoor() 69 | { 70 | if (dooropen) 71 | { 72 | DoorClose(); 73 | } 74 | else 75 | { 76 | DoorOpen(); 77 | } 78 | } 79 | 80 | public void DoorOpen() 81 | { 82 | dooropen = true; 83 | anim.Play("dooropen"); 84 | } 85 | 86 | public void DoorClose() 87 | { 88 | dooropen = false; 89 | anim.Play("doorclose"); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /Raycasting.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public class Raycasting : MonoBehaviour 4 | { 5 | [Header("Spawning")] 6 | public GameObject prefabToSpawn; 7 | 8 | [Header("Settings")] 9 | public float distance = 100f; 10 | 11 | public LayerMask collisionMask = -1; 12 | 13 | public float spawnRate = 5f; 14 | 15 | [Header("Debug")] 16 | public Color hitColor = Color.green; 17 | public Color noHitColor = Color.red; 18 | 19 | private float lastTimeSpawned; 20 | 21 | private void Update() 22 | { 23 | if(Time.time > lastTimeSpawned + 1/ spawnRate) 24 | { 25 | if(Input.GetMouseButton(0)) 26 | PerformRaycast(); 27 | } 28 | } 29 | 30 | private void PerformRaycast() 31 | { 32 | if(Camera.main == null) 33 | return; 34 | 35 | Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 36 | RaycastHit hit; 37 | bool wasHit = Physics.Raycast(ray,out hit, distance, collisionMask); 38 | 39 | Color debugColor = wasHit ? hitColor : noHitColor; 40 | Vector3 rayEnd = wasHit ? hit.point : ray.direction * distance; 41 | 42 | Debug.DrawLine(Camera.main.transform.position, rayEnd, debugColor, 5f); 43 | 44 | if(wasHit && prefabToSpawn != null) 45 | { 46 | GameObject spawnedObject = Instantiate(prefabToSpawn, hit.point, Quaternion.LookRotation(hit.normal)); 47 | lastTimeSpawned = Time.time; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /RigidbodyExtensions.cs: -------------------------------------------------------------------------------- 1 | public static class RigidbodyExtensions 2 | { 3 | public static void Merge(this Rigidbody a, Rigidbody b) 4 | { 5 | if (b == null) 6 | { 7 | return; 8 | } 9 | 10 | var mass = a.mass + b.mass; 11 | var velocity = a.velocity * (a.mass / mass) + b.velocity * (b.mass / mass); 12 | var angularVelocity = a.angularVelocity * (a.mass / mass) + b.angularVelocity * (b.mass / mass); 13 | 14 | a.mass = mass; 15 | a.velocity = velocity; 16 | a.angularVelocity = angularVelocity; 17 | a.ResetCenterOfMass(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Rolling.shader: -------------------------------------------------------------------------------- 1 | Shader " Custom/Rolling " 2 | { 3 | Properties 4 | { 5 | _MainTex ("Base (RGB)", 2D) = "white" {} 6 | _Bend("Bend",Float) = 1 7 | _Strength("Strength",Float) = 1 8 | } 9 | 10 | SubShader 11 | { 12 | Tags {"Queue"="Geometry" "IgnoreProjector"="true" "RenderType"="Opaque"} 13 | Cull Off 14 | 15 | Pass 16 | { 17 | CGPROGRAM 18 | #pragma vertex vert 19 | #pragma fragment frag 20 | #include "UnityCG.cginc" 21 | 22 | struct v2f 23 | { 24 | half2 texcoord : TEXCOORD0; 25 | float4 vertex : SV_POSITION; 26 | }; 27 | 28 | sampler2D _MainTex; 29 | float _Bend; 30 | float _Strength; 31 | 32 | v2f vert(appdata_full v) 33 | { 34 | v2f o; 35 | 36 | //I don't know what should I write here for rolling ,please help me. 37 | //v.vertex.y *= ??? 38 | v.vertex.y *= exp(_Bend+(v.vertex.x*_Strength)); // something like this but this hasn't twist effect 39 | o.vertex = UnityObjectToClipPos(v.vertex); 40 | o.texcoord = v.texcoord; 41 | return o; 42 | } 43 | 44 | float4 frag (v2f i) : COLOR 45 | { 46 | 47 | float2 uv = i.texcoord.xy; 48 | float4 tex = tex2D(_MainTex, uv); 49 | 50 | return tex; 51 | } 52 | ENDCG 53 | } 54 | } 55 | Fallback Off 56 | } 57 | -------------------------------------------------------------------------------- /RollingaCube.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using UnityEngine; 3 | 4 | public class PlayerController : MonoBehaviour { 5 | [SerializeField] private float _rollSpeed = 5; 6 | private bool _isMoving; 7 | 8 | private void Update() { 9 | if (_isMoving) return; 10 | 11 | if (Input.GetKey(KeyCode.A)) Assemble(Vector3.left); 12 | else if (Input.GetKey(KeyCode.D)) Assemble(Vector3.right); 13 | else if (Input.GetKey(KeyCode.W)) Assemble(Vector3.forward); 14 | else if (Input.GetKey(KeyCode.S)) Assemble(Vector3.back); 15 | 16 | void Assemble(Vector3 dir) { 17 | var anchor = transform.position + (Vector3.down + dir) * 0.5f; 18 | var axis = Vector3.Cross(Vector3.up, dir); 19 | StartCoroutine(Roll(anchor, axis)); 20 | } 21 | } 22 | 23 | private IEnumerator Roll(Vector3 anchor, Vector3 axis) { 24 | _isMoving = true; 25 | for (var i = 0; i < 90 / _rollSpeed; i++) { 26 | transform.RotateAround(anchor, axis, _rollSpeed); 27 | yield return new WaitForSeconds(0.01f); 28 | } 29 | _isMoving = false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /RopeSection.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | //A class that will hold information about each rope section 6 | public struct RopeSection 7 | { 8 | public Vector3 pos; 9 | public Vector3 vel; 10 | 11 | //To write RopeSection.zero 12 | public static readonly RopeSection zero = new RopeSection(Vector3.zero); 13 | 14 | public RopeSection(Vector3 pos) 15 | { 16 | this.pos = pos; 17 | 18 | this.vel = Vector3.zero; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Rotater.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class Rotater : MonoBehaviour { 6 | 7 | public enum ROTATIONAXIS { 8 | xAxis, 9 | yAxis, 10 | zAxis 11 | } 12 | 13 | public float maxRotationAngle; 14 | public float period; 15 | 16 | float myTime; 17 | 18 | public ROTATIONAXIS rotationAxis; 19 | 20 | 21 | // Update is called once per frame 22 | void FixedUpdate () { 23 | if(rotationAxis == ROTATIONAXIS.xAxis) 24 | { 25 | myTime += Time.deltaTime; 26 | float phase = Mathf.Sin(myTime / period); 27 | transform.localRotation = Quaternion.Euler(new Vector3(phase * maxRotationAngle,0,0)); 28 | } 29 | 30 | else if (rotationAxis == ROTATIONAXIS.yAxis) 31 | { 32 | myTime += Time.deltaTime; 33 | float phase = Mathf.Sin(myTime / period); 34 | transform.localRotation = Quaternion.Euler(new Vector3(0, phase * maxRotationAngle, 0)); 35 | } 36 | 37 | else if (rotationAxis == ROTATIONAXIS.zAxis) 38 | { 39 | myTime += Time.deltaTime; 40 | float phase = Mathf.Sin(myTime / period); 41 | transform.localRotation = Quaternion.Euler(new Vector3(0, 0, phase * maxRotationAngle)); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Rotation.cs: -------------------------------------------------------------------------------- 1 | .transform.rotation = Quaternion.Euler(0.0f, 0.0f, 0.0f); 2 | -------------------------------------------------------------------------------- /Rotator.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class Rotator : MonoBehaviour 5 | { 6 | void Update () 7 | { 8 | if( Input.GetKeyDown(KeyCode.Space) ) 9 | { 10 | StartCoroutine( Rotate(Vector3.up, 90, 1.0f) ); 11 | } 12 | } 13 | 14 | IEnumerator Rotate( Vector3 axis, float angle, float duration = 1.0f) 15 | { 16 | Quaternion from = transform.rotation; 17 | Quaternion to = transform.rotation; 18 | to *= Quaternion.Euler( axis * angle ); 19 | 20 | float elapsed = 0.0f; 21 | while( elapsed < duration ) 22 | { 23 | transform.rotation = Quaternion.Slerp(from, to, elapsed / duration ); 24 | elapsed += Time.deltaTime; 25 | yield return null; 26 | } 27 | transform.rotation = to; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Save.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using UnityEngine; 3 | 4 | [System.Serializable] 5 | public class Save 6 | { 7 | public List targetPositions = new List(); 8 | public List targetRotation = new List(); 9 | } 10 | [System.Serializable] 11 | public struct Vector3Serializable 12 | { 13 | public float x; 14 | public float y; 15 | public float z; 16 | } 17 | [System.Serializable] 18 | public struct QuaternionSerializable 19 | { 20 | public float x; 21 | public float y; 22 | public float z; 23 | public float w; 24 | } 25 | -------------------------------------------------------------------------------- /SaveGame.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Runtime.Serialization.Formatters.Binary; 5 | using UnityEngine; 6 | 7 | public class SaveGame : MonoBehaviour 8 | { 9 | [Header("Variables")] 10 | public GameObject[] targets; 11 | private Save CreateSaveGameObject() 12 | { 13 | var save = new Save(); 14 | foreach (var targetGameObject in targets) 15 | { 16 | var position = targetGameObject.transform.position; 17 | var rotation = targetGameObject.transform.rotation; 18 | 19 | Vector3Serializable serializableVector3 = new Vector3Serializable 20 | { 21 | x = position.x, y = position.y, z = position.z 22 | }; 23 | QuaternionSerializable serializableQuaternion = new QuaternionSerializable 24 | { 25 | x = rotation.x, y = rotation.y, z = rotation.z, w = rotation.w 26 | }; 27 | save.targetPositions.Add(serializableVector3); 28 | save.targetRotation.Add(serializableQuaternion); 29 | } 30 | return save; 31 | } 32 | public void SaveGameFile() 33 | { 34 | var save = CreateSaveGameObject(); 35 | 36 | BinaryFormatter bf = new BinaryFormatter(); 37 | FileStream file = File.Create(Application.persistentDataPath + "/gamesave.save"); 38 | bf.Serialize(file, save); 39 | file.Close(); 40 | 41 | Debug.Log("Game Saved"); 42 | } 43 | public void LoadGameFile() 44 | { 45 | if (File.Exists(Application.persistentDataPath + "/gamesave.save")) 46 | { 47 | BinaryFormatter bf = new BinaryFormatter(); 48 | FileStream file = File.Open(Application.persistentDataPath + "/gamesave.save", FileMode.Open); 49 | Save save = (Save)bf.Deserialize(file); 50 | file.Close(); 51 | 52 | for (var i = 0; i < save.targetPositions.Count; i++) 53 | { 54 | Vector3 vector3 = new Vector3() 55 | { 56 | x = save.targetPositions[i].x, y = save.targetPositions[i].y, z = save.targetPositions[i].z 57 | }; 58 | Quaternion quaternion = new Quaternion() 59 | { 60 | x = save.targetRotation[i].x, y = save.targetRotation[i].y, z = save.targetRotation[i].z, w = save.targetRotation[i].w 61 | }; 62 | targets[i].transform.position = vector3; 63 | targets[i].transform.rotation = quaternion; 64 | } 65 | 66 | Debug.Log("Game Loaded"); 67 | } 68 | else 69 | { 70 | Debug.Log("No game saved!"); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /ScaleLerper.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class ScaleLerper : MonoBehaviour { 6 | 7 | Vector3 minScale; 8 | public Vector3 maxScale; 9 | public bool repeatable; 10 | public float speed = 2f; 11 | public float duration = 5f; 12 | 13 | // Use this for initialization 14 | IEnumerator Start () { 15 | minScale = transform.localScale; 16 | while (repeatable) { 17 | yield return RepeatLerp(minScale, maxScale, duration); 18 | yield return RepeatLerp(maxScale, minScale, duration); 19 | } 20 | } 21 | 22 | public IEnumerator RepeatLerp(Vector3 a, Vector3 b, float time) { 23 | float i = 0.0f; 24 | float rate = (1.0f / time) * speed; 25 | while (i < 1.0f) { 26 | i += Time.deltaTime * rate; 27 | transform.localScale = Vector3.Lerp(a, b, i); 28 | yield return null; 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /ScaleToView.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class ScaleToView : MonoBehaviour 6 | { 7 | void Start() 8 | { 9 | SpriteRenderer spriteRenderer = GetComponent(); 10 | if (spriteRenderer != null) { 11 | float height = Camera.main.orthographicSize * 2; 12 | float width = height * Screen.width/ Screen.height; 13 | 14 | Sprite sprite = spriteRenderer.sprite; 15 | float unitWidth = sprite.textureRect.width / sprite.pixelsPerUnit; 16 | float unitHeight = sprite.textureRect.height / sprite.pixelsPerUnit; 17 | 18 | transform.localScale = new Vector3(width / unitWidth, height / unitHeight, 1); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ScoreCounter.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class ScoreCounter : MonoBehaviour 5 | { 6 | public float duration = 0.5f; 7 | int score = 0; 8 | 9 | void OnGUI () { 10 | GUIButtonCountTo (0); 11 | GUIButtonCountTo (5000); 12 | GUIButtonCountTo (20000); 13 | GUILayout.Label ("Current score is " + score); 14 | } 15 | 16 | void GUIButtonCountTo (int target) { 17 | if (GUILayout.Button ("Count to " + target)) { 18 | StopCoroutine ("CountTo"); 19 | StartCoroutine ("CountTo", target); 20 | } 21 | } 22 | 23 | IEnumerator CountTo (int target) { 24 | int start = score; 25 | for (float timer = 0; timer < duration; timer += Time.deltaTime) { 26 | float progress = timer / duration; 27 | score = (int)Mathf.Lerp (start, target, progress); 28 | yield return null; 29 | } 30 | score = target; 31 | } 32 | } 33 | 34 | 35 | /* 36 | public int partialScore; 37 | private int scoreT = 0; 38 | void Start () { 39 | partialScore = 3000; //example score 40 | } 41 | void Update () { 42 | if(int.Parse(GetComponent().text) < partialScore){ 43 | GetComponent().text = scoreT.ToString(); 44 | scoreT = scoreT + 10; //Example Step 45 | } 46 | } 47 | */ 48 | -------------------------------------------------------------------------------- /ScreenShotter.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class ScreenShotter : MonoBehaviour 5 | { 6 | public bool captureScreenshot; 7 | public string shotName; 8 | int takeNumber; 9 | 10 | 11 | IEnumerator RecordFrame() 12 | { 13 | captureScreenshot = false; 14 | yield return new WaitForEndOfFrame(); 15 | var texture = ScreenCapture.CaptureScreenshotAsTexture(); 16 | // do something with texture 17 | byte[] _byteArray = texture.EncodeToJPG(); 18 | System.IO.File.WriteAllBytes(Application.dataPath + $"/Screenshoot_{shotName}_{takeNumber}.png", _byteArray); 19 | 20 | // cleanup 21 | takeNumber++; 22 | Object.Destroy(texture); 23 | } 24 | 25 | public void LateUpdate() 26 | { 27 | if (captureScreenshot) 28 | StartCoroutine(RecordFrame()); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ScreenshotWindow.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using UnityEditor; 3 | using UnityEngine; 4 | 5 | public class ScreenshotWindow : EditorWindow 6 | { 7 | private int superSize; 8 | private string folder; 9 | 10 | [MenuItem("Tools/Create Screenshot")] 11 | private static void Init() 12 | { 13 | var window = GetWindow(false,"Screenshots", true); 14 | if (string.IsNullOrEmpty(window.folder)) 15 | { 16 | window.folder = Directory.GetCurrentDirectory(); 17 | } 18 | } 19 | 20 | private void OnGUI() 21 | { 22 | GUILayout.Label("Settings", EditorStyles.boldLabel); 23 | superSize = (int)EditorGUILayout.Slider("Super Size", superSize, 1, 20); 24 | 25 | GUILayout.BeginHorizontal(); 26 | 27 | EditorGUILayout.TextField("Folder", folder); 28 | if (GUILayout.Button("...", GUILayout.MaxWidth(50))) 29 | { 30 | folder = EditorUtility.SaveFolderPanel("Save screenshots to folder", folder, ""); 31 | if (string.IsNullOrEmpty(folder)) 32 | { 33 | folder = Directory.GetCurrentDirectory(); 34 | } 35 | } 36 | 37 | GUILayout.EndHorizontal(); 38 | 39 | GUILayout.Space(10); 40 | 41 | if (GUILayout.Button("Capture")) 42 | { 43 | if (!Directory.Exists(folder)) 44 | { 45 | EditorUtility.DisplayDialog("Folder not found", "Could not find the folder, does it exist?", "Ok"); 46 | } 47 | else 48 | { 49 | int counter = 0; 50 | string filename = GetFilename(counter); 51 | while (File.Exists(filename)) 52 | { 53 | filename = GetFilename(++counter); 54 | } 55 | ScreenCapture.CaptureScreenshot(filename, superSize); 56 | } 57 | } 58 | } 59 | 60 | private string GetFilename(int index) 61 | { 62 | return Path.Combine(folder, string.Format("Screenshot_{0:000}.png",index)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /ScriptableData.txt: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | [System.Serializable] 3 | public class Avatar 4 | { 5 | public string AvatarName; 6 | public byte AvatarId; 7 | public Sprite Icon; 8 | public string Description; 9 | } 10 | 11 | 12 | 13 | using System.Collections.Generic; 14 | using UnityEngine; 15 | [CreateAssetMenu(fileName = "Avatar Data", menuName = "Create Avatar Data", order = 51)] 16 | public class AvatarData : ScriptableObject 17 | { 18 | public List avatars = new List(); 19 | } 20 | 21 | 22 | 23 | using UnityEngine; 24 | public class AvatarSelection : MonoBehaviour 25 | { 26 | [SerializeField] 27 | private AvatarData avatarData; 28 | private void Start() 29 | { 30 | for (int i = 0; i < avatarData.avatars.Count; i++) 31 | { 32 | Debug.Log("Avatar Name: " + avatarData.avatars[i].AvatarName); 33 | Debug.Log("Avatar Id: " + avatarData.avatars[i].AvatarId); 34 | Debug.Log("Avatar description: " + avatarData.avatars[i].Description); 35 | } 36 | } 37 | } 38 | 39 | 40 | 41 | using System.IO; 42 | using UnityEngine; 43 | public class AvatarSelection : MonoBehaviour 44 | { 45 | private AvatarData avatarData; 46 | private void Awake() 47 | { 48 | avatarData = LoadData(); 49 | } 50 | private void Start() 51 | { 52 | for (int i = 0; i < avatarData.avatars.Count; i++) 53 | { 54 | Debug.Log("Avatar Name: " + avatarData.avatars[i].AvatarName); 55 | Debug.Log("Avatar Id: " + avatarData.avatars[i].AvatarId); 56 | Debug.Log("Avatar description: " + avatarData.avatars[i].Description); 57 | } 58 | } 59 | private void OnDisable() 60 | { 61 | SaveData(); 62 | } 63 | void SaveData() 64 | { 65 | string json = JsonUtility.ToJson(avatarData); 66 | File.WriteAllText(Application.persistentDataPath + Path.DirectorySeparatorChar + "AvatarData.txt", json); 67 | } 68 | AvatarData LoadData() 69 | { 70 | AvatarData data = null; 71 | if (File.Exists(Application.persistentDataPath + Path.DirectorySeparatorChar + "AvatarData.txt")) 72 | { 73 | data = ScriptableObject.CreateInstance(); 74 | string json = File.ReadAllText(Application.persistentDataPath + Path.DirectorySeparatorChar + "AvatarData.txt"); 75 | JsonUtility.FromJsonOverwrite(json, data); 76 | } 77 | else 78 | { 79 | data = Resources.Load("Avatar Data"); 80 | } 81 | return data; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /ScrollAndPinch.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Set this on an empty game object positioned at (0,0,0) and attach your active camera. 3 | The script only runs on mobile devices or the remote app. 4 | */ 5 | 6 | using UnityEngine; 7 | 8 | class ScrollAndPinch : MonoBehaviour 9 | { 10 | #if UNITY_IOS || UNITY_ANDROID 11 | public Camera Camera; 12 | public bool Rotate; 13 | protected Plane Plane; 14 | 15 | private void Awake() 16 | { 17 | if (Camera == null) 18 | Camera = Camera.main; 19 | } 20 | 21 | private void Update() 22 | { 23 | 24 | //Update Plane 25 | if (Input.touchCount >= 1) 26 | Plane.SetNormalAndPosition(transform.up, transform.position); 27 | 28 | var Delta1 = Vector3.zero; 29 | var Delta2 = Vector3.zero; 30 | 31 | //Scroll 32 | if (Input.touchCount >= 1) 33 | { 34 | Delta1 = PlanePositionDelta(Input.GetTouch(0)); 35 | if (Input.GetTouch(0).phase == TouchPhase.Moved) 36 | Camera.transform.Translate(Delta1, Space.World); 37 | } 38 | 39 | //Pinch 40 | if (Input.touchCount >= 2) 41 | { 42 | var pos1 = PlanePosition(Input.GetTouch(0).position); 43 | var pos2 = PlanePosition(Input.GetTouch(1).position); 44 | var pos1b = PlanePosition(Input.GetTouch(0).position - Input.GetTouch(0).deltaPosition); 45 | var pos2b = PlanePosition(Input.GetTouch(1).position - Input.GetTouch(1).deltaPosition); 46 | 47 | //calc zoom 48 | var zoom = Vector3.Distance(pos1, pos2) / 49 | Vector3.Distance(pos1b, pos2b); 50 | 51 | //edge case 52 | if (zoom == 0 || zoom > 10) 53 | return; 54 | 55 | //Move cam amount the mid ray 56 | Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, 1 / zoom); 57 | 58 | if (Rotate && pos2b != pos2) 59 | Camera.transform.RotateAround(pos1, Plane.normal, Vector3.SignedAngle(pos2 - pos1, pos2b - pos1b, Plane.normal)); 60 | } 61 | 62 | } 63 | 64 | protected Vector3 PlanePositionDelta(Touch touch) 65 | { 66 | //not moved 67 | if (touch.phase != TouchPhase.Moved) 68 | return Vector3.zero; 69 | 70 | //delta 71 | var rayBefore = Camera.ScreenPointToRay(touch.position - touch.deltaPosition); 72 | var rayNow = Camera.ScreenPointToRay(touch.position); 73 | if (Plane.Raycast(rayBefore, out var enterBefore) && Plane.Raycast(rayNow, out var enterNow)) 74 | return rayBefore.GetPoint(enterBefore) - rayNow.GetPoint(enterNow); 75 | 76 | //not on plane 77 | return Vector3.zero; 78 | } 79 | 80 | protected Vector3 PlanePosition(Vector2 screenPos) 81 | { 82 | //position 83 | var rayNow = Camera.ScreenPointToRay(screenPos); 84 | if (Plane.Raycast(rayNow, out var enterNow)) 85 | return rayNow.GetPoint(enterNow); 86 | 87 | return Vector3.zero; 88 | } 89 | 90 | private void OnDrawGizmos() 91 | { 92 | Gizmos.DrawLine(transform.position, transform.position + transform.up); 93 | } 94 | #endif 95 | } 96 | -------------------------------------------------------------------------------- /ScrollUVs.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class ScrollUVs : MonoBehaviour 5 | { 6 | public float USpeed; 7 | public float VSpeed; 8 | public Material mat; 9 | 10 | Vector2 offset; 11 | 12 | void Awake() { 13 | offset = new Vector2( 0, 0 ); 14 | } 15 | 16 | void Update() { 17 | offset.x = offset.x + (USpeed * Time.deltaTime) % 1.0f; 18 | offset.y = offset.y + (VSpeed * Time.deltaTime) % 1.0f; 19 | mat.SetTextureOffset( "_MainTex", offset ); 20 | } 21 | 22 | void OnDisable() { 23 | mat.SetTextureOffset( "_MainTex", Vector2.zero ); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /SeedFactory.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public class SeedFactory { 4 | 5 | private Random.State state; 6 | 7 | public SeedFactory (int seed) { 8 | Random.InitState(seed); 9 | state = Random.state; 10 | } 11 | 12 | // Set Unity's global Random state with this SeedFactory's state, get a random int, 13 | // then set our SeedFactory's state with the new state. 14 | // (this allows us to use multiple SeedFactories for multiple paths of determinism 15 | // if desired) 16 | public int GetRandomInt (int minInclusive, int maxExclusive) { 17 | Random.state = state; 18 | int randomInt = Random.Range(minInclusive, maxExclusive); 19 | state = Random.state; 20 | return randomInt; 21 | } 22 | 23 | } 24 | 25 | MonoBehaviour to run the test 26 | 27 | public class SeedTest : MonoBehaviour { 28 | 29 | void Start () { 30 | SeedFactory seedFactory = new SeedFactory(123456789); 31 | string result = ""; 32 | for (int i = 0; i < 20; i++) { 33 | result += seedFactory.GetRandomInt(int.MinValue, int.MaxValue) + ", "; 34 | } 35 | Debug.Log(result); 36 | } 37 | } 38 | 39 | Windows Editor: 40 | 217814258, 711215697, 1793372675, -1318111305, -513578644, 1776128467, -1503243711, -285471819, -1800526065, -1845985472, -2061970588, 188207569, 1858341351, -1139513088, 2136219157, 1255727479, -2070068486, 459175680, 1151694536, 1232856178, 41 | 42 | Windows Standalone: 43 | 217814258, 711215697, 1793372675, -1318111305, -513578644, 1776128467, -1503243711, -285471819, -1800526065, -1845985472, -2061970588, 188207569, 1858341351, -1139513088, 2136219157, 1255727479, -2070068486, 459175680, 1151694536, 1232856178, 44 | 45 | macOS Standalone: 46 | 217814258, 711215697, 1793372675, -1318111305, -513578644, 1776128467, -1503243711, -285471819, -1800526065, -1845985472, -2061970588, 188207569, 1858341351, -1139513088, 2136219157, 1255727479, -2070068486, 459175680, 1151694536, 1232856178, 47 | 48 | Android: 49 | 217814258, 711215697, 1793372675, -1318111305, -513578644, 1776128467, -1503243711, -285471819, -1800526065, -1845985472, -2061970588, 188207569, 1858341351, -1139513088, 2136219157, 1255727479, -2070068486, 459175680, 1151694536, 1232856178, 50 | -------------------------------------------------------------------------------- /SelectVertex.cs: -------------------------------------------------------------------------------- 1 | public int ClosestIndexToPoint(Raycast ray) 2 | { 3 | RaycastHit hit; 4 | if(Raycast(ray.origin, ray.direction, out hit)) 5 | { 6 | Mesh m = hit.transform.GetComponent().sharedMesh; 7 | int[] tri = new int[3] { 8 | m.triangles[hit.triangleIndex * 3 + 0], 9 | m.triangles[hit.triangleIndex * 3 + 1], 10 | m.triangles[hit.triangleIndex * 3 + 2] 11 | } 12 | 13 | // loop through hit triangle and see which vertex is closest to the hit point 14 | Vector3 closestDistance = Vector3.Distance(m.vertices[tri[0]], hit.point); 15 | int closestVertexIndex = tri[0]; 16 | for(int i = 0; i < tri.Length; i++) 17 | { 18 | Vector3 dist = Vector3.Distance(m.vertices[tri[i]], hit.point); 19 | if(dist < closestDistance) 20 | { 21 | Vector3 closestDistance = dist; 22 | closestVertexIndex = tri[i]; 23 | } 24 | } 25 | 26 | // returns the index of the closest vertex to hit point. 27 | return closestVertexIndex; 28 | } 29 | else 30 | return -1; 31 | } 32 | -------------------------------------------------------------------------------- /SetScreenSize.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class SetScreenSize : MonoBehaviour { 5 | 6 | // Use this for initialization 7 | void Start () { 8 | GameObject mainCamera = GameObject.Find("Main Camera"); 9 | 10 | Camera.main.orthographicSize = (720 * (16f / 9f) / 2) / 100; 11 | 12 | Camera.main.aspect = 9f / 16f; 13 | 14 | float camHalfHeight = Camera.main.orthographicSize; 15 | float camHalfWidth = Camera.main.aspect * camHalfHeight; 16 | 17 | mainCamera.transform.position = new Vector3(mainCamera.transform.position.x, camHalfHeight, mainCamera.transform.position.z); 18 | 19 | Vector3 topLeftPosition = new Vector3(-camHalfWidth, camHalfHeight, 0) + Camera.main.transform.position; 20 | print("Top Left : " + topLeftPosition); 21 | } 22 | 23 | // Update is called once per frame 24 | void Update () { 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /SigletonScriptableObject.cs: -------------------------------------------------------------------------------- 1 | using System.Collection; 2 | using System.Collection.Generic; 3 | using UnityEngine; 4 | 5 | public class SingletonScriptableObject : ScriptableObject where T : SingletonScriptableObject 6 | { 7 | private static T instance; 8 | public static T Instance { 9 | get { 10 | if (instance == null){ 11 | T[] = Resources.LoadAll(""); 12 | if (assets == null || assets.Length < 1){ 13 | throw new System.Exception("Could not find and singleton scriptable object instance in the resource"); 14 | } 15 | else if (assets.Length > 1){ 16 | Debug.LoagWarning("Multiple instance of the singleton scriptable object fount in the resources"); 17 | } 18 | instance = assets[0]; 19 | } 20 | return instance; 21 | } 22 | } 23 | 24 | } 25 | 26 | 27 | /////////////////////// GameSettings.cs 28 | 29 | [CreateAssetMenu(filename="Game Settings", menuName="Scriptable Objects/Game Settings")] 30 | public class GameSettings : SingletonScriptableObject 31 | { 32 | public string gameName; 33 | public int gameVersion; 34 | } 35 | -------------------------------------------------------------------------------- /SimulateProjectileCR.cs: -------------------------------------------------------------------------------- 1 | public float gravity = 60f; 2 | public float heightOfShot = 12f; 3 | 4 | IEnumerator SimulateProjectileCR(Transform projectile, Vector3 startPosition, Vector3 endPosition) 5 | { 6 | projectile.position = startPosition; 7 | float arcAmount = 8f; 8 | Vector3 newVel = new Vector3(); 9 | // Find the direction vector without the y-component 10 | Vector3 direction = new Vector3(endPosition.x, 0f, endPosition.z) - new Vector3(startPosition.x, 0f, startPosition.z); 11 | // Find the distance between the two points (without the y-component) 12 | float range = direction.magnitude; 13 | 14 | // Find unit direction of motion without the y component 15 | Vector3 unitDirection = direction.normalized; 16 | // Find the max height 17 | 18 | float maxYPos = startPosition.y + heightOfShot; 19 | 20 | // if it has, switch the height to match a 45 degree launch angle 21 | if (range / 2f > maxYPos) 22 | maxYPos = range / arcAmount; 23 | //fix bug when shooting on tower 24 | if (maxYPos - startPosition.y <= 0) 25 | { 26 | maxYPos = startPosition.y + 2f; 27 | } 28 | //fix bug caused if we can't shoot higher than target 29 | if (maxYPos - endPosition.y <= 0) 30 | { 31 | maxYPos = endPosition.y + 2f; 32 | } 33 | // find the initial velocity in y direction 34 | newVel.y = Mathf.Sqrt(-2.0f * -gravity * (maxYPos - startPosition.y)); 35 | // find the total time by adding up the parts of the trajectory 36 | // time to reach the max 37 | float timeToMax = Mathf.Sqrt(-2.0f * (maxYPos - startPosition.y) / -gravity); 38 | // time to return to y-target 39 | float timeToTargetY = Mathf.Sqrt(-2.0f * (maxYPos - endPosition.y) / -gravity); 40 | // add them up to find the total flight time 41 | float totalFlightTime = timeToMax + timeToTargetY; 42 | // find the magnitude of the initial velocity in the xz direction 43 | float horizontalVelocityMagnitude = range / totalFlightTime; 44 | // use the unit direction to find the x and z components of initial velocity 45 | newVel.x = horizontalVelocityMagnitude * unitDirection.x; 46 | newVel.z = horizontalVelocityMagnitude * unitDirection.z; 47 | 48 | float elapse_time = 0; 49 | while (elapse_time < totalFlightTime) 50 | { 51 | projectile.Translate(newVel.x * Time.deltaTime, (newVel.y - (gravity * elapse_time)) * Time.deltaTime, newVel.z * Time.deltaTime); 52 | elapse_time += Time.deltaTime; 53 | yield return null; 54 | } 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Singleton.cs: -------------------------------------------------------------------------------- 1 | #region static data 2 | public static GameManager instance { get; private set; } 3 | public void Awake() 4 | { 5 | if (instance == null) 6 | { 7 | instance = this; 8 | DontDestroyOnLoad(instance); 9 | } 10 | else 11 | { 12 | Destroy(gameObject); 13 | } 14 | } 15 | #endregion 16 | -------------------------------------------------------------------------------- /Slerper.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class Slerper : MonoBehaviour { 6 | 7 | public Transform startPos; 8 | public Transform endPos; 9 | public float journeyTime = 1.0f; 10 | public float speed; 11 | public bool repeatable; 12 | 13 | float startTime; 14 | Vector3 centerPoint; 15 | Vector3 startRelCenter; 16 | Vector3 endRelCenter; 17 | 18 | // Update is called once per frame 19 | void Update () { 20 | GetCenter(Vector3.up); 21 | if(!repeatable) { 22 | float fracComplete = (Time.time - startTime) / journeyTime * speed; 23 | transform.position = Vector3.Slerp(startRelCenter, endRelCenter, fracComplete * speed); 24 | transform.position += centerPoint; 25 | } 26 | if (repeatable) { 27 | float fracComplete = Mathf.PingPong(Time.time - startTime, journeyTime / speed); 28 | transform.position = Vector3.Slerp(startRelCenter, endRelCenter, fracComplete * speed); 29 | transform.position += centerPoint; 30 | if (fracComplete >= 1) { 31 | startTime = Time.time; 32 | } 33 | } 34 | } 35 | 36 | public void GetCenter(Vector3 direction) { 37 | centerPoint = (startPos.position + endPos.position) * .5f; 38 | centerPoint -= direction; 39 | startRelCenter = startPos.position - centerPoint; 40 | endRelCenter = endPos.position - centerPoint; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /SliderFill.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | using UnityEngine.UI; 4 | 5 | [RequireComponent(typeof(Slider))] 6 | public class SliderFill : MonoBehaviour { 7 | 8 | public float fillSpeed = 1.0f; 9 | 10 | private Slider slider; 11 | private RectTransform fillRect; 12 | private float targetValue = 0f; 13 | private float curValue = 0f; 14 | 15 | void Awake () { 16 | slider = GetComponent(); 17 | 18 | //Adds a listener to the main slider and invokes a method when the value changes. 19 | slider.onValueChanged.AddListener (delegate {ValueChange ();}); 20 | 21 | fillRect = slider.fillRect; 22 | targetValue = curValue = slider.value; 23 | } 24 | 25 | // Invoked when the value of the slider changes. 26 | public void ValueChange() 27 | { 28 | targetValue = slider.value; 29 | } 30 | 31 | // Update is called once per frame 32 | void Update () { 33 | curValue = Mathf.MoveTowards(curValue, targetValue, Time.deltaTime * fillSpeed); 34 | 35 | Vector2 fillAnchor = fillRect.anchorMax; 36 | fillAnchor.x = Mathf.Clamp01(curValue/slider.maxValue); 37 | fillRect.anchorMax = fillAnchor; 38 | } 39 | } 40 | 41 | 42 | 43 | /* 44 | public class Example : MonoBehaviour 45 | { 46 | public float thedamage; 47 | public float variable; 48 | public float actualvariable; 49 | 50 | private void Start() 51 | { 52 | // Both of theses floats have to be the same! 53 | variable = 5f; 54 | actualvariable = 5f; 55 | 56 | // Example damage 57 | thedamage = 1; 58 | } 59 | 60 | void DamageExample() 61 | { 62 | actualvariable -= thedamage; 63 | } 64 | 65 | private void Update() 66 | { 67 | variable = Mathf.Lerp(variable, actualvariable, 4 * Time.deltaTime); 68 | // And you can ajust the speed by changing the '4' number ! 69 | } 70 | } 71 | */ 72 | -------------------------------------------------------------------------------- /SpawnRadial.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class SpawnRadial : MonoBehaviour 6 | { 7 | // Instantiates prefabs in a circle formation 8 | public GameObject prefab; 9 | public int numberOfObjects = 10; 10 | public float radius = 10f; 11 | void Start() 12 | { 13 | for (int i = 0; i < numberOfObjects; i++) 14 | { 15 | float angle = i * Mathf.PI * 2 / numberOfObjects; 16 | float x = Mathf.Cos(angle) * radius; 17 | float z = Mathf.Sin(angle) * radius; 18 | Vector3 pos = transform.position + new Vector3(x, 0, z); 19 | float angleDegrees = -angle * Mathf.Rad2Deg; 20 | Quaternion rot = Quaternion.Euler(0, angleDegrees, 0); 21 | Instantiate(prefab, pos, rot); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Spin.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public class MathTab : MonoBehaviour 4 | { 5 | public Vector3 spinSpeed; 6 | public float spinDuration = 1f; 7 | public AnimationCurve spinDecline; 8 | 9 | private float spin = 0f; 10 | 11 | [System.NonSerialized] 12 | public MathGate gate; 13 | [System.NonSerialized] 14 | public bool isCorrect = false; 15 | TextMesh textMesh; 16 | MeshRenderer _renderer; 17 | Transform trs; 18 | 19 | public void Initialize(string answer, bool isCorrect) 20 | { 21 | textMesh = GetComponentInChildren(); 22 | _renderer = GetComponent(); 23 | trs = transform; 24 | textMesh.text = answer; 25 | this.isCorrect = isCorrect; 26 | } 27 | 28 | private void Update() 29 | { 30 | if(spin > 0f) 31 | { 32 | spin = Mathf.MoveTowards(spin, 0f, Time.deltaTime / spinDuration); 33 | trs.Rotate(spinSpeed * spinDecline.Evaluate(1f - spin) * Time.deltaTime, Space.Self); 34 | } 35 | } 36 | 37 | public void SetMaterial(Material mat) 38 | { 39 | _renderer.sharedMaterial = mat; 40 | } 41 | 42 | public void SetAlpha(float alpha) 43 | { 44 | Color col = textMesh.color; 45 | col.a = alpha; 46 | textMesh.color = col; 47 | } 48 | 49 | private void OnTriggerEnter(Collider other) 50 | { 51 | if (gate.answered) return; 52 | if (other.GetComponentInParent() == null) return; 53 | if (isCorrect) 54 | { 55 | gate.OnCorrectAnswer(); 56 | spin = 1f; 57 | } else 58 | { 59 | gate.OnWrongAnswer(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /SteppedCameraZoom.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class SteppedCameraZoom : MonoBehaviour { 6 | 7 | public float[] FOVS = {45,30,15}; 8 | Camera myCamera; 9 | int FOVpos = 0; 10 | 11 | // Use this for initialization 12 | void Start () { 13 | myCamera = GetComponent(); 14 | } 15 | 16 | // Update is called once per frame 17 | void Update () { 18 | if (Input.GetMouseButtonDown(0)) { 19 | ZoomIn(); 20 | } 21 | 22 | if (Input.GetMouseButtonDown(1)) { 23 | ZoomOut(); 24 | } 25 | } 26 | 27 | void ZoomIn() { 28 | if (FOVpos >= FOVS.Length - 1) { 29 | FOVpos = FOVS.Length - 1; 30 | } else { 31 | FOVpos += 1; 32 | } 33 | myCamera.fieldOfView = FOVS[FOVpos]; 34 | } 35 | 36 | void ZoomOut() { 37 | if (FOVpos <= 0) { 38 | FOVpos = 0; 39 | } else { 40 | FOVpos -= 1; 41 | } 42 | myCamera.fieldOfView = FOVS[FOVpos]; 43 | } 44 | } 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /StringExtensions.cs: -------------------------------------------------------------------------------- 1 | public static class StringExtensions 2 | { 3 | public static bool IsNullOrEmpty(this string value) 4 | { 5 | return string.IsNullOrEmpty(value); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /SuperRandomSpawner.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class SuperRandomSpawner : MonoBehaviour { 6 | 7 | public GameObject[] spawnees; 8 | public GameObject[] spawnPoints; 9 | 10 | public float radius = 2; 11 | 12 | int randomInt; 13 | int randomIntTwo; 14 | Vector3 randomVec; 15 | 16 | void Start() { 17 | spawnPoints = GameObject.FindGameObjectsWithTag("spawnPoint"); 18 | } 19 | 20 | // Update is called once per frame 21 | void Update () { 22 | if(Input.GetMouseButton(0)) { 23 | SpawnRandom(); 24 | } 25 | } 26 | 27 | int GetRandom(int count) { 28 | return Random.Range(0, count); 29 | } 30 | 31 | Vector3 GetRandomVector (Vector3 vec) { 32 | return (Random.insideUnitSphere * radius) + vec; 33 | } 34 | 35 | void SpawnRandom() { 36 | randomInt = GetRandom(spawnees.Length); 37 | randomIntTwo = GetRandom(spawnPoints.Length); 38 | randomVec = GetRandomVector(spawnPoints[randomIntTwo].transform.position); 39 | Instantiate(spawnees[randomInt], randomVec, spawnPoints[randomIntTwo].transform.rotation); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /SwipeDetector.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class SwipeDetector : MonoBehaviour 5 | { 6 | 7 | public float minSwipeDistY; 8 | 9 | public float minSwipeDistX; 10 | 11 | private Vector2 startPos; 12 | 13 | void Update() 14 | { 15 | //#if UNITY_ANDROID 16 | if (Input.touchCount > 0) 17 | 18 | { 19 | 20 | Touch touch = Input.touches[0]; 21 | 22 | 23 | 24 | switch (touch.phase) 25 | 26 | { 27 | 28 | case TouchPhase.Began: 29 | 30 | startPos = touch.position; 31 | 32 | break; 33 | 34 | 35 | 36 | case TouchPhase.Ended: 37 | 38 | float swipeDistVertical = (new Vector3(0, touch.position.y, 0) - new Vector3(0, startPos.y, 0)).magnitude; 39 | 40 | if (swipeDistVertical > minSwipeDistY) 41 | 42 | { 43 | 44 | float swipeValue = Mathf.Sign(touch.position.y - startPos.y); 45 | 46 | if (swipeValue > 0)//up swipe 47 | 48 | //Jump (); 49 | 50 | else if (swipeValue < 0)//down swipe 51 | 52 | //Shrink (); 53 | 54 | } 55 | 56 | float swipeDistHorizontal = (new Vector3(touch.position.x,0, 0) - new Vector3(startPos.x, 0, 0)).magnitude; 57 | 58 | if (swipeDistHorizontal > minSwipeDistX) 59 | 60 | { 61 | 62 | float swipeValue = Mathf.Sign(touch.position.x - startPos.x); 63 | 64 | if (swipeValue > 0)//right swipe 65 | 66 | //MoveRight (); 67 | 68 | else if (swipeValue < 0)//left swipe 69 | 70 | //MoveLeft (); 71 | 72 | } 73 | break; 74 | } 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /SwipeManager.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public enum Swipes { None, Up, Down, Left, TopLeft, BottomLeft, Right, TopRight, BottomRight}; 4 | 5 | public class SwipeManager : MonoBehaviour 6 | { 7 | public float minSwipeLength = 200f; 8 | Vector2 currentSwipe; 9 | 10 | private Vector2 fingerStart; 11 | private Vector2 fingerEnd; 12 | 13 | public static Swipes direction; 14 | 15 | void Update () 16 | { 17 | SwipeDetection(); 18 | } 19 | 20 | public void SwipeDetection () 21 | { 22 | if (Input.GetMouseButtonDown(0)) { 23 | fingerStart = Input.mousePosition; 24 | fingerEnd = Input.mousePosition; 25 | } 26 | 27 | if(Input.GetMouseButton(0)) { 28 | fingerEnd = Input.mousePosition; 29 | 30 | currentSwipe = new Vector2 (fingerEnd.x - fingerStart.x, fingerEnd.y - fingerStart.y); 31 | 32 | // Make sure it was a legit swipe, not a tap 33 | if (currentSwipe.magnitude < minSwipeLength) { 34 | direction = Swipes.None; 35 | return; 36 | } 37 | 38 | float angle = (Mathf.Atan2(currentSwipe.y, currentSwipe.x) / (Mathf.PI)); 39 | Debug.Log(angle); 40 | // Swipe up 41 | if (angle>0.375f && angle<0.625f) { 42 | direction = Swipes.Up; 43 | Debug.Log ("Up"); 44 | // Swipe down 45 | } else if (angle<-0.375f && angle>-0.625f) { 46 | direction = Swipes.Down; 47 | Debug.Log ("Down"); 48 | // Swipe left 49 | } else if (angle<-0.875f || angle>0.875f) { 50 | direction = Swipes.Left; 51 | Debug.Log ("Left"); 52 | // Swipe right 53 | } else if (angle>-0.125f && angle<0.125f) { 54 | direction = Swipes.Right; 55 | Debug.Log ("Right"); 56 | } 57 | else if(angle>0.125f && angle<0.375f){ 58 | direction = Swipes.TopRight; 59 | Debug.Log ("top right"); 60 | } 61 | else if(angle>0.625f && angle<0.875f){ 62 | direction = Swipes.TopLeft; 63 | Debug.Log ("top left"); 64 | } 65 | else if(angle<-0.125f && angle>-0.375f){ 66 | direction = Swipes.BottomRight; 67 | Debug.Log ("bottom right"); 68 | } 69 | else if(angle<-0.625f && angle>-0.875f){ 70 | direction = Swipes.BottomLeft; 71 | Debug.Log ("bottom left"); 72 | } 73 | } 74 | 75 | if(Input.GetMouseButtonUp(0)) { 76 | direction = Swipes.None; 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /TextureAnimation.shader: -------------------------------------------------------------------------------- 1 | Shader "Mattatz/TextureAnimation" 2 | { 3 | Properties 4 | { 5 | _MainTex ("Texture", 2D) = "white" {} 6 | _Color ("Color", Color) = (1, 1, 1, 1) 7 | 8 | _Cols ("Cols Count", Int) = 5 9 | _Rows ("Rows Count", Int) = 3 10 | _Frame ("Per Frame Length", Float) = 0.5 11 | } 12 | 13 | SubShader 14 | { 15 | Tags { "RenderType"="Opaque" } 16 | LOD 100 17 | 18 | Pass 19 | { 20 | CGPROGRAM 21 | #pragma vertex vert 22 | #pragma fragment frag 23 | 24 | #include "UnityCG.cginc" 25 | 26 | struct appdata 27 | { 28 | float4 vertex : POSITION; 29 | float2 uv : TEXCOORD0; 30 | }; 31 | 32 | struct v2f 33 | { 34 | float2 uv : TEXCOORD0; 35 | float4 vertex : SV_POSITION; 36 | }; 37 | 38 | sampler2D _MainTex; 39 | float4 _MainTex_ST; 40 | 41 | fixed4 _Color; 42 | 43 | uint _Cols; 44 | uint _Rows; 45 | 46 | float _Frame; 47 | 48 | fixed4 shot (sampler2D tex, float2 uv, float dx, float dy, int frame) { 49 | return tex2D(tex, float2( 50 | (uv.x * dx) + fmod(frame, _Cols) * dx, 51 | 1.0 - ((uv.y * dy) + (frame / _Cols) * dy) 52 | )); 53 | } 54 | 55 | v2f vert (appdata v) { 56 | v2f o; 57 | o.vertex = mul(UNITY_MATRIX_MVP, v.vertex); 58 | o.uv = TRANSFORM_TEX(v.uv, _MainTex); 59 | return o; 60 | } 61 | 62 | fixed4 frag (v2f i) : SV_Target { 63 | int frames = _Rows * _Cols; 64 | float frame = fmod(_Time.y / _Frame, frames); 65 | int current = floor(frame); 66 | float dx = 1.0 / _Cols; 67 | float dy = 1.0 / _Rows; 68 | 69 | // not lerping to next frame 70 | // return shot(_MainTex, i.uv, dx, dy, current) * _Color; 71 | 72 | int next = floor(fmod(frame + 1, frames)); 73 | return lerp(shot(_MainTex, i.uv, dx, dy, current), shot(_MainTex, i.uv, dx, dy, next), frame - current) * _Color; 74 | } 75 | 76 | ENDCG 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /TimedSpawn.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class TimedSpawn : MonoBehaviour { 6 | 7 | public GameObject spawnee; 8 | public bool stopSpawning = false; 9 | public float spawnTime; 10 | public float spawnDelay; 11 | 12 | // Use this for initialization 13 | void Start () { 14 | InvokeRepeating("SpawnObject", spawnTime, spawnDelay); 15 | } 16 | 17 | public void SpawnObject() { 18 | Instantiate(spawnee, transform.position, transform.rotation); 19 | if(stopSpawning) { 20 | CancelInvoke("SpawnObject"); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /TouchManager.cs: -------------------------------------------------------------------------------- 1 | void update() 2 | { 3 | if (Input.GetMouseButton(0)) 4 | { 5 | Vector3 mousePosFar = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.farClipPlane); 6 | Vector3 mousePosNear = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane); 7 | 8 | Vector3 MousePosF = Camera.main.ScreenToWorldPoint(mousePosFar); 9 | Vector3 MousePosN = Camera.main.ScreenToWorldPoint(mousePosNear); 10 | 11 | Debug.DrawRay(MousePosN, MousePosF - MousePosN, Color.green); 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /TouchToShoot.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | public class TouchToShoot : MonoBehaviour { 4 | 5 | public Material hitMaterial; 6 | 7 | // Use this for initialization 8 | void Start () { 9 | 10 | } 11 | 12 | // Update is called once per frame 13 | void Update () { 14 | 15 | if (Input.GetMouseButtonDown(0)) 16 | { 17 | var ray = Camera.main.ScreenPointToRay(Input.mousePosition); 18 | RaycastHit hitInfo; 19 | if (Physics.Raycast(ray, out hitInfo)) 20 | { 21 | var rig = hitInfo.collider.GetComponent(); 22 | if(rig != null) 23 | { 24 | rig.GetComponent().material = hitMaterial; 25 | rig.AddForceAtPosition(ray.direction * 50f, hitInfo.point, ForceMode.VelocityChange); 26 | } 27 | } 28 | } 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /TransformTemp.txt: -------------------------------------------------------------------------------- 1 | Vector3 temp = transform.position; 2 | temp.y += bounceSpeed; 3 | transform.position = temp; 4 | -------------------------------------------------------------------------------- /UnbreakableCollider.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | public class UnbreakableCollider : MonoBehaviour 4 | { 5 | public Transform DotPrefab; 6 | Vector3 lastDotPosition; 7 | bool lastPointExists; 8 | void Start() 9 | { 10 | lastPointExists = false; 11 | } 12 | void Update() 13 | { 14 | if (Input.GetMouseButton(0)) 15 | { 16 | Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition); 17 | Vector3 newDotPosition = mouseRay.origin - mouseRay.direction / mouseRay.direction.y * mouseRay.origin.y; 18 | if (newDotPosition != lastDotPosition) 19 | { 20 | MakeADot(newDotPosition); 21 | } 22 | } 23 | } 24 | void MakeADot(Vector3 newDotPosition) 25 | { 26 | Transform dot = (Transform)Instantiate(DotPrefab, newDotPosition, Quaternion.identity); //use random identity to make dots looks more different 27 | if (lastPointExists) 28 | { 29 | GameObject colliderKeeper = new GameObject("collider"); 30 | BoxCollider bc = colliderKeeper.AddComponent(); 31 | colliderKeeper.transform.position = Vector3.Lerp(newDotPosition, lastDotPosition, 0.5f); 32 | colliderKeeper.transform.LookAt(newDotPosition); 33 | bc.size = new Vector3(0.1f, 0.1f, Vector3.Distance(newDotPosition, lastDotPosition)); 34 | } 35 | lastDotPosition = newDotPosition; 36 | lastPointExists = true; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Unique.cs: -------------------------------------------------------------------------------- 1 | private int maxNumbers = 20; 2 | private List uniqueNumbers; 3 | private List finishedList; 4 | private List finishedNumbers; 5 | 6 | void Start(){ 7 | uniqueNumber = new List(); 8 | finishedList = new List(); 9 | } 10 | 11 | public void GenerateRandomList(){ 12 | for(int i = 0; i < maxNumbers; i++){ 13 | uniqueNumbers.Add(i); 14 | } 15 | for(int i = 0; i< maxNumbers; i ++){ 16 | int ranNum = uniqueNumbers[Random.Range(0,uniqueNumbers.Count)]; 17 | finishedNumbers.Add(ranNum); 18 | uniqueNumbers.Remove(ranNum) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /WavingGrass.shader: -------------------------------------------------------------------------------- 1 | Shader "Hidden/TerrainEngine/Details/WavingDoublePass" { 2 | Properties { 3 | _WavingTint ("Fade Color", Color) = (.7,.6,.5, 0) 4 | _MainTex ("Base (RGB) Alpha (A)", 2D) = "white" {} 5 | _WaveAndDistance ("Wave and distance", Vector) = (12, 3.6, 1, 1) 6 | _Cutoff ("Cutoff", float) = 0.5 7 | } 8 | 9 | SubShader { 10 | Tags { 11 | "Queue" = "Geometry+200" 12 | "IgnoreProjector"="True" 13 | "RenderType"="Grass" 14 | } 15 | Cull Off 16 | LOD 200 17 | ColorMask RGB 18 | 19 | CGPROGRAM 20 | #pragma surface surf Lambert vertex:WavingGrassVert addshadow fullforwardshadows 21 | #pragma exclude_renderers flash 22 | #include "TerrainEngine.cginc" 23 | 24 | sampler2D _MainTex; 25 | fixed _Cutoff; 26 | 27 | struct Input { 28 | float2 uv_MainTex; 29 | fixed4 color : COLOR; 30 | }; 31 | 32 | void surf (Input IN, inout SurfaceOutput o) { 33 | fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * IN.color; 34 | o.Albedo = c.rgb; 35 | o.Alpha = c.a; 36 | clip (o.Alpha - _Cutoff); 37 | o.Alpha *= IN.color.a; 38 | } 39 | ENDCG 40 | } 41 | 42 | SubShader { 43 | Tags { 44 | "Queue" = "Geometry+200" 45 | "IgnoreProjector"="True" 46 | "RenderType"="Grass" 47 | } 48 | Cull Off 49 | LOD 200 50 | ColorMask RGB 51 | 52 | Pass { 53 | Tags { "LightMode" = "Vertex" } 54 | Material { 55 | Diffuse (1,1,1,1) 56 | Ambient (1,1,1,1) 57 | } 58 | Lighting On 59 | ColorMaterial AmbientAndDiffuse 60 | AlphaTest Greater [_Cutoff] 61 | SetTexture [_MainTex] { combine texture * primary DOUBLE, texture } 62 | } 63 | Pass { 64 | Tags { "LightMode" = "VertexLMRGBM" } 65 | AlphaTest Greater [_Cutoff] 66 | BindChannels { 67 | Bind "Vertex", vertex 68 | Bind "texcoord1", texcoord0 // lightmap uses 2nd uv 69 | Bind "texcoord", texcoord1 // main uses 1st uv 70 | } 71 | SetTexture [unity_Lightmap] { 72 | matrix [unity_LightmapMatrix] 73 | combine texture * texture alpha DOUBLE 74 | } 75 | SetTexture [_MainTex] { combine texture * previous QUAD, texture } 76 | } 77 | } 78 | 79 | Fallback Off 80 | } 81 | -------------------------------------------------------------------------------- /WindArea.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class WindArea : MonoBehaviour { 6 | 7 | public float strength; 8 | public Vector3 direction; 9 | 10 | } 11 | -------------------------------------------------------------------------------- /_BlockSpawnPointChecker.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class BlockSpawnPointChecker : MonoBehaviour 6 | { 7 | public bool objectAlreadyAtSpawn = false; 8 | public float sideLengthOfCollider; 9 | BoxCollider checkerCollider; 10 | 11 | private void Start() 12 | { 13 | objectAlreadyAtSpawn = false; 14 | checkerCollider = GetComponent(); 15 | checkerCollider.size = new Vector3(sideLengthOfCollider, sideLengthOfCollider, sideLengthOfCollider); 16 | } 17 | 18 | private void OnTriggerEnter(Collider other) 19 | { 20 | if (other.CompareTag("PlayerObject") || other.CompareTag("EnemyObject") || other.CompareTag("Environment")) 21 | { 22 | objectAlreadyAtSpawn = true; 23 | } 24 | } 25 | 26 | private void OnTriggerStay(Collider other) 27 | { 28 | if (other.CompareTag("PlayerObject") || other.CompareTag("EnemyObject") || other.CompareTag("Environment")) 29 | { 30 | objectAlreadyAtSpawn = true; 31 | } 32 | } 33 | 34 | private void OnTriggerExit(Collider other) 35 | { 36 | if (other.CompareTag("PlayerObject") || other.CompareTag("EnemyObject") || other.CompareTag("Environment")) 37 | { 38 | objectAlreadyAtSpawn = false; 39 | } 40 | } 41 | 42 | private void Update() 43 | { 44 | Vector3 pos = Input.mousePosition; 45 | pos.z = Camera.main.gameObject.transform.position.z; 46 | 47 | Vector3 spawnPos = Camera.main.ScreenToWorldPoint(pos); 48 | 49 | gameObject.transform.position = spawnPos; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /_DataManager.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class DataManager : MonoBehaviour 6 | { 7 | public static DataManager Instance { get; private set; } 8 | 9 | private void Awake() 10 | { 11 | if(!Instance) 12 | { 13 | Instance = this; 14 | DontDestroyOnLoad(gameObject); 15 | } 16 | else 17 | { 18 | Destroy(gameObject); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /_EnemyBlockSpawner.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class EnemyBlockSpawner : MonoBehaviour 6 | { 7 | [Header("Enemy Block Control")] 8 | //How long the delay between enemy placing blocks is 9 | public float delayBetweenSpawningEnemyBlocks; 10 | //The actual timer 11 | float enemyBlocksDelayTimer; 12 | //The box that will be spawned 13 | public GameObject enemyBox; 14 | //The game controller so we can get the list of current spawned blocks 15 | public GameController gameController; 16 | 17 | //User inputted ymin and ymax and zpos 18 | [Header("Height and Depth Cords")] 19 | public float minY; 20 | public float maxY; 21 | public float zPos; 22 | 23 | public float xLeftCord; 24 | public float xRightCord; 25 | 26 | public GameObject plank; 27 | 28 | // Use this for initialization 29 | void Start() 30 | { 31 | gameController = GameObject.FindGameObjectWithTag("GameController").GetComponent(); 32 | 33 | if (plank != null) 34 | { 35 | xLeftCord = plank.transform.position.x - plank.transform.localScale.x / 2; 36 | xRightCord = plank.transform.position.x + plank.transform.localScale.x / 2; 37 | } 38 | } 39 | 40 | // Update is called once per frame 41 | void Update() 42 | { 43 | //Spawn enemy blocks 44 | if (Time.time > enemyBlocksDelayTimer && gameController.playingGame) 45 | { 46 | //Pick an x position based on the smallest and largest values 47 | float xSpawnVal = Mathf.Round(Random.Range(xLeftCord + .5f, xRightCord - .5f)); 48 | 49 | //We pick a random height for the block to spawn in based on ymin and ymax 50 | float ySpawnVal = Random.Range(minY, maxY); 51 | 52 | //Send where the enemy box is spawned and correlate to where the player has blocks spawned 53 | 54 | //spawn the box based on the random values and a predetermined zposition 55 | Instantiate(enemyBox, new Vector3(xSpawnVal, ySpawnVal, zPos), Quaternion.identity); 56 | 57 | //increase the delay timer for the next spawned block 58 | enemyBlocksDelayTimer = Time.time + delayBetweenSpawningEnemyBlocks; 59 | } 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /_PlankRotationController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class PlankRotationController : MonoBehaviour 6 | { 7 | [Header("Plank")] 8 | public GameObject plank; 9 | 10 | //Rotation Control 11 | [Header("Rotation Control")] 12 | //The plank where the player want to land the values 13 | //Basically how this works is how far to the left or right the plank can rotate to 14 | //The max rotation angle, this is the max angle that the plank can rotate to 15 | public float maxRightRotationAnglePlank; 16 | //The min rotation angle, this is the minimum angle the plank can rotate to 17 | public float maxLeftRotationAnglePlank; 18 | //How long before the plank picks a new rotation 19 | public int plankRotationDelay; 20 | //How fast the plank will move to the new rotation MAX 21 | public float maxRotationSpeedPlank; 22 | //the slowest the plank will move to its next rotation 23 | public float minRotationSpeedPlank; 24 | //I dont know what this does 25 | //public float rotationAdder; 26 | //The timer counting up to the next rotation 27 | float plankRotationTimer; 28 | //the next target rotation 29 | float plankRotationTarget; 30 | //the speed the plank will rotate to the next rotation 31 | float plankRotationSpeed; 32 | public GameController gameController; 33 | 34 | 35 | // Use this for initialization 36 | void Start() 37 | { 38 | plankRotationTimer = Time.time + plankRotationDelay; 39 | plank = gameObject; 40 | gameController = GameObject.FindGameObjectWithTag("GameController").GetComponent(); 41 | } 42 | 43 | // Update is called once per frame 44 | void Update() 45 | { 46 | //Rotate platform 47 | //if the current global time is longer than the plank rotation timer its time to rotate again 48 | if (Time.time > plankRotationTimer && gameController.playingGame) 49 | { 50 | plankRotationTarget = Mathf.Round(Random.Range(-maxLeftRotationAnglePlank, maxRightRotationAnglePlank)); 51 | 52 | //No idea what this does 53 | //plankRotationTarget += (Mathf.Sign(plankRotationTarget) * rotationAdder); 54 | 55 | plankRotationSpeed = Random.Range(minRotationSpeedPlank, maxRotationSpeedPlank); 56 | plankRotationTimer = Time.time + plankRotationDelay; 57 | } 58 | 59 | //create the new value and move towards it 60 | float angle = Mathf.MoveTowardsAngle(plank.transform.eulerAngles.z, plankRotationTarget, plankRotationSpeed * Time.deltaTime); 61 | //set the transform of the plank 62 | plank.transform.eulerAngles = new Vector3(0, 0, angle); 63 | //rotate platform ends 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /calcCenterPoint.cs: -------------------------------------------------------------------------------- 1 | public void calcCenterPoint(GameObject gobj) 2 | { 3 | int i = 0; 4 | centerPoint += player.GetComponent().firstActivePiece.transform.position; 5 | 6 | foreach (GameObject obj in gobj.GetComponent().activePieces) 7 | { 8 | if (obj) 9 | { 10 | centerPoint += obj.transform.position; 11 | i++; 12 | } 13 | } 14 | 15 | centerPoint /= i+1; 16 | 17 | if (debugGOBJ) 18 | { 19 | debugGOBJ.transform.position = centerPoint; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /countdownTimer.cs: -------------------------------------------------------------------------------- 1 | IEnumerator countdownTimer() 2 | { 3 | yield return new WaitForSecondsRealtime(1); 4 | countdown.text = "2"; 5 | yield return new WaitForSecondsRealtime(1); 6 | countdown.text = "1"; 7 | yield return new WaitForSecondsRealtime(1); 8 | Time.timeScale = 1; 9 | countdown.gameObject.SetActive(false); 10 | countdown.text = "3"; 11 | } 12 | -------------------------------------------------------------------------------- /dash.cs: -------------------------------------------------------------------------------- 1 | rb.MovePosition(gameObject.transform.position - (gameObject.transform.forward * 5)); 2 | //GameManager.instance.player.transform.position = GameManager.instance.player.transform.position + GameManager.instance.player.transform.forward * playerDashValue; 3 | -------------------------------------------------------------------------------- /destroyer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class destroyer : MonoBehaviour { 6 | 7 | public float lifeTime = 10f; 8 | 9 | // Update is called once per frame 10 | void Update () { 11 | if(lifeTime > 0) { 12 | lifeTime -= Time.deltaTime; 13 | if(lifeTime <= 0) { 14 | Destruction(); 15 | } 16 | } 17 | 18 | if(this.transform.position.y <= -20) { 19 | Destruction(); 20 | } 21 | } 22 | 23 | void OnCollisionEnter(Collision coll) { 24 | if(coll.gameObject.name == "destroyer") { 25 | Destruction(); 26 | } 27 | } 28 | 29 | void Destruction() { 30 | Destroy(this.gameObject); 31 | } 32 | } -------------------------------------------------------------------------------- /foreachReverse.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | public class ExampleClass : MonoBehaviour { 4 | 5 | public Object[] anyTypeArray; 6 | 7 | public void Start () { 8 | 9 | foreach(Object part in anyTypeArray.Reverse()) { 10 | //Insert your code Here 11 | } 12 | 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /gametime.cs: -------------------------------------------------------------------------------- 1 | StartCoundownTimer(); 2 | 3 | public Text gameTime; 4 | private float time; 5 | private bool isGameOver = false; 6 | 7 | //Start Count down of the timer 8 | void StartCoundownTimer() 9 | { 10 | if (gameTime != null) 11 | { 12 | time = 120;//2 minute 13 | gameTime.text = "Time Left: 2:00:000"; //set initial string to two minutes 14 | InvokeRepeating("UpdateTimer", 0.0f, 0.01f); //Invokes the method UpdateTimer in time seconds, then repeatedly every repeatRate seconds. 15 | } 16 | } 17 | 18 | 19 | void UpdateTimer() 20 | { 21 | //when gameTime is exists and Game is not over 22 | //update time text on the screen 23 | if (gameTime != null && !isGameOver) 24 | { 25 | time -= Time.deltaTime; 26 | string minutes = Mathf.Floor(time / 60).ToString("00"); 27 | string seconds = (time % 60).ToString("00"); 28 | string fraction = ((time * 100) % 100).ToString("000"); 29 | gameTime.text = "Time Left: " + minutes + ":" + seconds + ":" + fraction; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /leftRightTouch.cs: -------------------------------------------------------------------------------- 1 | void Update () { 2 | if (Input.touchCount > 0) 3 | { 4 | var touch = Input.GetTouch(0); 5 | if (touch.position.x < Screen.width/2) 6 | { 7 | Debug.Log ("Left click"); 8 | } 9 | else if (touch.position.x > Screen.width/2) 10 | { 11 | Debug.Log ("Right click"); 12 | } 13 | } 14 | } 15 | 16 | //multi touch 17 | 18 | private int finId1 = -1; //id finger for cancel touch event 19 | private int finId2 = -1; 20 | 21 | void Start() { 22 | Input.multiTouchEnabled = true; //enabled Multitouch 23 | } 24 | 25 | void Update() { 26 | //First check count of touch 27 | if (Input.touchCount > 0) { 28 | foreach (Touch touch in Input.touches) { 29 | //For left half screen 30 | if (touch.phase == TouchPhase.Began && touch.position.x <= Screen.width && finId1 == -1) { 31 | //Do something: start other function 32 | finId1 = touch.fingerId; //store Id finger 33 | } 34 | //For right half screen 35 | if (touch.phase == TouchPhase.Began && touch.position.x > Screen.width && finId2 == -1) { 36 | //Do something 37 | finId2 = touch.fingerId; 38 | } 39 | if (touch.phase == TouchPhase.Ended) { //correct end of touch 40 | if(touch.fingerId == finId1) { //check id finger for end touch 41 | finId1 = -1; 42 | } else if(touch.fingerId == finId2) { 43 | finId2 = -1; 44 | } 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /newArray.cs: -------------------------------------------------------------------------------- 1 | Array1 = new Transform[Array2.Length]; 2 | -------------------------------------------------------------------------------- /shakeDetect.cs: -------------------------------------------------------------------------------- 1 | float accelerometerUpdateInterval = 1.0f / 60.0f; 2 | // The greater the value of LowPassKernelWidthInSeconds, the slower the 3 | // filtered value will converge towards current input sample (and vice versa). 4 | float lowPassKernelWidthInSeconds = 1.0f; 5 | // This next parameter is initialized to 2.0 per Apple's recommendation, 6 | // or at least according to Brady! ;) 7 | float shakeDetectionThreshold = 2.0f; 8 | 9 | float lowPassFilterFactor; 10 | Vector3 lowPassValue; 11 | 12 | void Start() 13 | { 14 | lowPassFilterFactor = accelerometerUpdateInterval / lowPassKernelWidthInSeconds; 15 | shakeDetectionThreshold *= shakeDetectionThreshold; 16 | lowPassValue = Input.acceleration; 17 | } 18 | 19 | void Update() 20 | { 21 | Vector3 acceleration = Input.acceleration; 22 | lowPassValue = Vector3.Lerp(lowPassValue, acceleration, lowPassFilterFactor); 23 | Vector3 deltaAcceleration = acceleration - lowPassValue; 24 | 25 | if (deltaAcceleration.sqrMagnitude >= shakeDetectionThreshold) 26 | { 27 | // Perform your "shaking actions" here. If necessary, add suitable 28 | // guards in the if check above to avoid redundant handling during 29 | // the same shake (e.g. a minimum refractory period). 30 | Debug.Log("Shake event detected at time "+Time.time); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /smoothColorChange.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace gamename 6 | { 7 | public class smoothColorChange : MonoBehaviour 8 | { 9 | public float timeLeft; 10 | public Color colorTarget; 11 | 12 | private Renderer renderOBJ; 13 | 14 | void Start() 15 | { 16 | renderOBJ = GetComponent(); 17 | } 18 | 19 | void Update() 20 | { 21 | if (timeLeft <= Time.deltaTime) 22 | { 23 | renderOBJ.material.color = colorTarget; 24 | timeLeft = 0f; 25 | } 26 | else 27 | { 28 | renderOBJ.material.color = Color.Lerp(renderOBJ.material.color, colorTarget, Time.deltaTime / timeLeft); 29 | timeLeft -= Time.deltaTime; 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /spawner.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | public class spawner : MonoBehaviour { 6 | 7 | public Transform spawnPos; 8 | public GameObject spawnee; 9 | 10 | // Update is called once per frame 11 | void Update () { 12 | if(Input.GetMouseButton(0)) { 13 | Instantiate(spawnee, spawnPos.position, spawnPos.rotation); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /steeringWheelControl.cs: -------------------------------------------------------------------------------- 1 | // If we are using mobile controls, turn left/right based on the tap side position on the screen 2 | if (Application.isMobilePlatform) 3 | { 4 | // If we have a steering wheel slider assigned, use it 5 | if (steeringWheel) 6 | { 7 | // If we press the mouse button, check our position relative to the screen center 8 | if (Input.GetMouseButton(0)) 9 | { 10 | playerDirection = steeringWheel.value; 11 | } 12 | else // Otherwise, if we didn't press anything, don't rotate and straighten up 13 | { 14 | steeringWheel.value = playerDirection = 0; 15 | } 16 | 17 | steeringWheel.transform.Find("Wheel").eulerAngles = Vector3.forward * playerDirection * -100; 18 | } 19 | else if (Input.GetMouseButton(0)) // If we press the mouse button, check our position relative to the screen center 20 | { 21 | // If we are to the right of the screen, rotate to the right 22 | if (Input.mousePosition.x > Screen.width * 0.5f) 23 | { 24 | playerDirection = 1; 25 | } 26 | else // Othwerwise, rotate to the left 27 | { 28 | playerDirection = -1; 29 | } 30 | } 31 | else // Otherwise, if we didn't press anything, don't rotate and straighten up 32 | { 33 | playerDirection = 0; 34 | } 35 | } 36 | else // Otherwise, use gamepad/keyboard controls 37 | { 38 | playerDirection = Input.GetAxis("Horizontal"); 39 | } 40 | 41 | // Calculate the rotation direction 42 | playerObject.Rotate(playerDirection); 43 | -------------------------------------------------------------------------------- /walkback.cs: -------------------------------------------------------------------------------- 1 | transform.forward * -1 is the inverse of transform.forward 2 | --------------------------------------------------------------------------------