AutomatedTurret C# script
This script controls a turret that scans for enemy Players, checks if they are in range, and fires at the closest target.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AutomatedTurret : MonoBehaviour { public bool isActive = true; //turret [SerializeField] private float range = 50.0f; [SerializeField] private float rotationSpeed = 3.0f; private float scanTimer = 0.0f; //target private GameObject currentTarget; private List targetList = new List(); //bullet [SerializeField] private GameObject bullet; [SerializeField] private float bulletSpeed = 100.0f; [SerializeField] private float fireRate = 3.0f; [SerializeField] private float attackTimer = 1.0f; // Update is called once per frame void Update () { if (isActive) { //Scans for new targets after seconds equal to scanTimer if (scanTimer > 0) scanTimer -= Time.deltaTime; else { Scan(); scanTimer = 1.0f; //checks targetlist and updates target if (targetList.Count > 0) { currentTarget = SetTarget(targetList); } } if (currentTarget != null) { //Vector direction from turret to target Vector3 targetDirection = currentTarget.transform.position - transform.position; //distance between turret and target float targetDistance = targetDirection.magnitude; //Rotate turret towards target Vector3 rotateDir = Vector3.RotateTowards(transform.forward, targetDirection, rotationSpeed * Time.deltaTime,0.0f); transform.rotation = Quaternion.LookRotation(rotateDir); //Attack Target after delay equal to attacktimer if (attackTimer > 0) attackTimer -= Time.deltaTime; else { Shoot(); //sets attacks per second equal to firerate attackTimer = 1 / fireRate; } } } } //detect targets within range private void Scan() { targetList.Clear(); //detects Player colliders in sphere around turret with radius equal to range, RaycastHit[] hits = Physics.SphereCastAll(transform.position, range, transform.forward, 0, 1 << LayerMask.NameToLayer("Player")); //if a target is detected, adds it to targetList foreach (RaycastHit hit in hits) { targetList.Add(hit.collider.gameObject); } } //Returns a new target from a list of avaiable targets protected GameObject SetTarget(List targets) { GameObject closestTarget = null; float minDistance = Mathf.Infinity; foreach (GameObject target in targets) { //Vector direction from turret to target Vector3 direction = (target.transform.position - transform.position); //distance between turret and possible target float distance = direction.magnitude; //Prioritizes closest target and checks that no colliders are in the path from the turret to the target (ignoring Player colliders) if (distance < minDistance && !Physics.Raycast(transform.position, direction, distance, ~(1 << LayerMask.NameToLayer("Player")))) { minDistance = distance; closestTarget = target; } } //reset attacktimer when new target is selected if(currentTarget != closestTarget) attackTimer = 1.0f; return closestTarget; } //Spawns bullet and gives it velocity equal to bulletspeed protected void Shoot() { GameObject newBullet = Instantiate(bullet,transform.position,Quaternion.identity); newBullet.GetComponent().velocity = transform.TransformDirection(Vector3.forward * bulletSpeed); } }
DialogueController C# script
This script controls the dialogue/speech and text display in Damage Control, my Global Game Jam 2018 entry.
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; using UnityEngine.SceneManagement; public class DialogueController : MonoBehaviour { //struct for event used by event scheduler [Serializable] private struct SpeechEvent { public float delay; public UnityEvent action; } //Serielized eventscheduler to sequance events in editor [SerializeField] private SpeechEvent[] eventSchedule; //struct for censor timings public struct StatementTime { public float intro; public float outro; } //Struct for audioclip, transcript, and timings for speech [Serializable] public struct Statement { public AudioClip clip; public string transcript; public StatementTime[] timings; } public List statementList; //current statment being played public Statement currentStatement; //check if a statement is playing public bool playingStatement = false; //AudioMangager script private AudioManager audioManager; //Script controlling president [SerializeField] private PresidentController president; //Script controlling Censor Mechanic private Censor censor; //screen fader [SerializeField] private Fader fader; //UI text object to display transcript text [SerializeField] private Text transcriptUI; private float clipWait = 0; private Coroutine speechCoroutine; private void Awake() { InitiateData(); } private void Start() { audioManager = GetComponent(); speechCoroutine = StartCoroutine(Speech()); censor = GetComponent(); } //Retrieves data from text file private static string GetDialogueData() { TextAsset file = Resources.Load("DialogueData") as TextAsset; return file.text; } //Uses text data to populate stamentList timings private void InitiateData() { int num = 0; string dialogueText = GetDialogueData(); string[] list = dialogueText.Split("\n"[0]); foreach (string line in list) { List DataList = new List(); string[] split = line.Split(';'); foreach (string part in split) { if (part != "") { string[] segment = part.Split('/'); float introTime = float.Parse(segment[0].Trim()); float outroTime = float.Parse(segment[1].Trim()); StatementTime newStatementTime = new StatementTime() { intro = introTime, outro = outroTime }; DataList.Add(newStatementTime); } } statementList[num].timings = DataList.ToArray(); num++; } } //Used by event scheduler to play statement public void PlayStatement(int num) { playingStatement = true; currentStatement = statementList[num]; clipWait = currentStatement.clip.length; audioManager.PlaceSpeech(currentStatement.clip); president.StartTalking(); transcriptUI.text = currentStatement.transcript; } //Sequences through eventschedule private IEnumerator Speech() { for (int i = 0; i < eventSchedule.Length; i++) { yield return new WaitForSeconds(eventSchedule[i].delay); eventSchedule[i].action.Invoke(); yield return new WaitForSeconds(clipWait); while (audioManager.main.isPlaying || fader.isFading == true) yield return null; playingStatement = false; } } }