Questions in topic: "scrpting" The latest questions for the topic "scrpting" Scriptable Object won't Reset values after play. I'm creating Pokemon-esk RPG game and decided to make the creatures scriptable objects. Each object has the values of Name, Max Health, Current Health, and Attack List. I've made it so a Slider acts as a health bar and lowers the Scriptable Objects "Current Health Integer". However after testing that out and stopping the program, the value in the Scriptable Object didn't change back to its original value. Is there a way to prevent this? inspector scrpting Sat, 06 Apr 2019 22:33:39 GMT MasonXY Problem in EulerAngles Understanding ??,EulerAngles.x is not exceeding -90 to 90 range?? Vector3 v; void Start () { v =; } void Update () { _xRotation = Mathf.Lerp(_xRotation, 0, _lerpRate); _yYRotation = Mathf.Lerp(_yYRotation, 0, _lerpRate); v.x += _yYRotation; v.y += _xRotation; v.z += 1 * Time.deltaTime; transform.eulerAngles = v; // ******Above code ********* transform.eulerAngles += new Vector3(0, _xRotation, -_yYRotation); } Hello friends, I am a beginner in unity and also please forgive my spelling mistake or grammatical mistake in the question. Actually i am trying to orbit the camera around the player and i have problem in understanding in eulerAngles because when i use code above comment line the camera rotate in 360 angle but when i use code below the comment line the camera rotates only in 180 degree for x axis and for y axis it rotate 360 angle same value same code for x and y value but still this weird behavior. i am guessing this happen because " vector3 v" Declared ones in code above comment line and and in code below comment line every time it register new vector3 m i correct?? please explain. note : code below is in comment written just for understanding thank you in advance. scripting problem transform scrpting Thu, 10 May 2018 08:21:20 GMT idcanu Roleplay Engine that decides outcomes based on variables I want to create a simple roleplay engine for me and my friends that basically is used for sports, or war matchups, and I want to ask for how i go on doing this, i want it to look something like this. Subject: (ex. War, Sports Matchup) the subject is just asthetic and anything would be able to be put as a subject ______________________________________ Teams: (ex.) Blue Red Green Yellow ________________________________________________ there should be an infinite amount of sides you may insert, and all can have different names. and from this example, blue should have a 25 percent chance of winning, and depending on how many sides there are, the chance of winning is equal, but smaller since there are more teams, and same vise versa ________________________________________________ Matches?: (Ex: 3) any amount of matches is possible ____________________ Match 1: Red Wins ____________________ Match 2: Yellow wins _____________________ Match 3: Yellow Wins _______________________ Outcome: Yellow Wins (ex. War) whatever was the subject would be displayed here if it is a tie, then it would display tie. But yeah its just a simple app i want to create and i have no coding experience, so how would i go and start this. it is basically a more advanced flip a coin, dice or spin the wheel, and would be made for roleplay matchups. scrpting Wed, 09 May 2018 23:01:52 GMT AmanteMartin Primary constructor body is not allowed?! Please help me with my program! Whenever I try to run it it says "Primary constructor body is not allowed" Can someone fix it. Thanks! using UnityEngine; [RequireComponent(typeof(Rigidbody))] public class PlayerMotor : MonoBehaviour { private Vector3 velocity =; private Rigidbody rb; void Start () { rb = GetComponent<Rigidbody>(); } // Gets a movement vector public void Move (Vector3 _velocity) { velocity = _velocity; } // Run every physics iteration void FixedUpdate () { PerformMovement(); } //Perform movement based on velocity variable void PerformMovement (); { if (velocity != { RenderBuffer.MovePosition(RenderBuffer.position + velocity * Time.fixedDeltaTime); } } } programming problem during runtime console errors scrpting Sat, 19 Aug 2017 20:13:45 GMT CoolBusGaming Destroy GameObjects with Tag ( Not found) Hi guys ! I have created this script to instantiate two set of coins in alternation, but the coins are not destroyed ... all the coins have the tag "Pick Up", but the script does not work to destroy them, something wrong? The result is that the sets do not alternate and overlap continuously public GameObject coin; public GameObject coinB; public Transform coinPosition; public float spawnTime = 40f; public float spawnTimeB = 20f; public float destroyTime = 20f; void Start () { startTime = Time.time; InvokeRepeating ("Spawn", spawnTime, spawnTime); InvokeRepeating ("SpawnB", spawnTimeB, spawnTimeB); InvokeRepeating ("destroyCoin", destroyTime, destroyTime); } void Spawn () { Instantiate (coin, coinPosition.position, coinPosition.rotation); } void SpawnB () { Instantiate (coinB, coinPosition.position, coinPosition.rotation); } void destroyCoin() { Destroy(GameObject.FindWithTag("Pick Up")); } scrpting Sun, 02 Apr 2017 12:53:28 GMT Cervelx How to attach a basic first person camera to a capsule? So I want to attach a camera to a capsule so that it can pretty much be the player model. I want a first person camera to be attached to it and I don't know how to make the script to attach it or make the camera. I'm new so any help is appreciated. camera first-person-controller scrpting Mon, 26 Sep 2016 10:11:18 GMT ApesUpt Distance between two objects Unity I want to find the distance between the player and the projectile. this is what I tried: public GameObject other; void Update(){ float dist = Vector2.Distance(other.transform.position, transform.position); print("Distance" + " " + dist);} the ProjectileController: MyRB = GetComponent<Rigidbody2D>(); MyRB.AddForce(transform.right * rocketSpeed, ForceMode2D.Impulse) gunController: Instantiate(bullet, guntip.position, guntip.rotation); scriptingbasics maths scrpting Sat, 09 Jul 2016 08:09:01 GMT Killerpenguin21 what is wrong whis this? public List SampleMethod(List i){ return i; } c# script. function method scrpting Wed, 02 Mar 2016 16:18:09 GMT Linus333 Scripts worked but since 3 days its not working, please help. Hello Everyone. To begin, I apolazise for my bad english. Im new on unity. My scripts worked very well but since 3 days, they are not working. Even if i add a component, the basic script is not working. Help me please. I'ts for a school projet. [1]: /storage/temp/64521-script2.png c# addcomponent scrpting Wed, 24 Feb 2016 13:01:01 GMT Riday New at Unity, Issues following Sams Teach Yourself I recently bought a Sams Teach Yourself Unity Game Development and have come accross many issues. 1 is that the book is for Unity 4 but I downloaded Unity 5.3.2, the other is that the files they have associated to the book are outdated in a sense that heightmaps they give us are terrible and ive had to make my own. I have made a game and the scripting they are giving us is error filled. I have minor experince in coding, but dont understand how it goes with the book and I cant figure it out because so much of whats in the book is outdated. I will show you the codes that are given in the book. Game Control Script: using UnityEngine; using System.Collections; public class GameControlScript : MonoBehaviour { //The amount of ellapsed time private float time = 0; //Flags that control the state of the game private bool isRunning = false; private bool isFinished = false; //place holders for the player and the spawn point public Transform spawnPoint; public GameObject player; //place holders for the scripts on the character controller public CharacterMotor motorScript; public MouseLook lookScript; //This resets to game back to the way it started private void InitLevel() { time = 0; isRunning = true; isFinished = false; //move the player to the spawn point player.transform.position = spawnPoint.position; //Allow the character controller to move and //look around motorScript.enabled = true; lookScript.enabled = true; } // Use this for initialization void Start () { //prevent the character controller //from looking around motorScript.enabled = false; lookScript.enabled = false; } // Update is called once per frame void Update () { //add time to the clock if the game //is running if(isRunning) time += Time.deltaTime; } //This runs when the player enters the finish //zone public void FinishedGame() { isRunning = false; isFinished = true; //freeze the character controller motorScript.enabled = false; lookScript.enabled = false; } //This section creates the Graphical User Interface (GUI) void OnGUI() { if(!isRunning) { string message; if(isFinished) message = "Click to Play Again"; else message = "Click to Play"; if(GUI.Button(new Rect(Screen.width / 2 - 70, Screen.height/2, 140, 30), message)) { //start the game if the user clicks to play InitLevel (); } } //If the player finished the game, show the final time if(isFinished) { GUI.Box(new Rect(Screen.width / 2 - 65, 185, 130, 40), "Your Time Was"); GUI.Label(new Rect(Screen.width / 2 - 10, 200, 20, 30), ((int)time).ToString()); } //If the game is running, show the current time else if(isRunning) { GUI.Box(new Rect(Screen.width / 2 - 65, Screen.height - 115, 130, 40), "Your Time Is"); GUI.Label(new Rect(Screen.width / 2 - 10, Screen.height - 100, 20, 30), ((int)time).ToString()); } } } ------------------------------------------------------ Finish Script: using UnityEngine; using System.Collections; public class FinishScript : MonoBehaviour { //This is a place holder for the script that controls the game public GameControlScript gameControlScript; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } //This states that when an object enters the finish zone, let the //game control know that the current game has ended void OnTriggerEnter(Collider other) { gameControlScript.FinishedGame(); } } ----------------------- Here are the errors that appear when I move the script codes into the script folder. Assets/Scripts/GameControlScript.cs(6,6) error CS1003: syntax error, '.' expected Assets/Scripts/GameControlScript.cs(6,48) error CS8032 internal compiler error during parsing, run with -v for details scrpting Tue, 16 Feb 2016 21:05:43 GMT ethankelly77 All the script stoped the update func when i lock the computer Hi guys; our company has an project which is about going to finish。But recently we found a problem. the unity version we used is 4.3.4.we found that when we lock the windows for a while and unlock it , the game begain at the time we locked the computer.And in the building setting inspector,we made the RunInBackground toggle checked. we write an test script as blew, when we locked the windows ,the count stopped counting.that means the update func has stopped working.we test this code at unity 4.1.2 it works well. but 4.3.4-4.6.4 does not work.we also tested it in unity 5.1.2 and it works..but if the whole project upgrade to UNITY5 ,the work we should do is huge. so,is anyone has the same problem? and how can i fix it with no big change(or upgrade)? using UnityEngine; using System.Collections; public class Test1 : MonoBehaviour { int[] t = new int[10]; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Debug.LogError("Update"); t[0]++; } void LateUpdate() { Debug.LogError("LateUpdate"); t[1]++; } void OnDisable() { Debug.LogError("OnDisable"); } void OnEnable() { Debug.LogError("OnEnable"); } void FixedUpdate() { Debug.LogError("FixedUpdate"); } void OnApplicationPause(bool pause) { Debug.LogError("OnApplicationPause (" + pause + ")"); } void OnGUI() { Debug.LogError("OnGUI"); t[2]++; GUILayout.Label(t[0]+", " + t[1] + ", " + t[2] + ": \t(" + Time.realtimeSinceStartup + ") \t(" + Time.time + ")"); GUILayout.Label("Mouse Position: " + Input.mousePosition); GUILayout.Label("Screnn Size: " + Screen.width + " * " + Screen.height); } } scrpting Tue, 22 Sep 2015 02:09:17 GMT zlbdemon BCE0005 Unknown identifier: 'FirstPersonController' Help please So my code worked in unity 4.5 but when i start using unity 5 i tried to put the same code but it dose not work even after i edit the script, The problem that it is shown to me is : Unknown identifier: 'FirstPersonController' Here is the line of code that has the problem : GameObject.Find("FPSController").GetComponent(FirstPersonController).enabled = false; I tried a lot to make it work but no use. Any help will be appreciated. error scrpting Mon, 21 Sep 2015 19:04:42 GMT MemoThunder Ragdoll Base 2 Questions Greetings, Just 2 simple questions about this game - Stickman Warriors - 1 - Player Controls - How the player controls has been Created(Just the mesh or that 2d stickman movement), are these on player or enemy heads? 2 - Enemy AI - How the enemy ai has been set on this game like the enemy rotate flies come to player smartly (Well might be chance but perfect) , Navigation Mesh is un-understandable with these function (Including rai ai(just forget that)). Please guys if these is a script that can do miracle or something to achieve that kind of ai . android unity 5 ai ragdoll scrpting Sat, 25 Jul 2015 18:40:15 GMT JeevanjotSingh SemiColon At The End and Found /n Errors! Help! #pragma strict var TheDamage : int 50; var Distance : float; Function Uptade () ' { if (Input.GetMouseButtonDown("Fire1")) { var hit : RaycastHit; if (Physics.Raycast Transform.position, Transform.TransformDirection(Vector3.forward), hit)) { Distance = hit.distance; hit.transform.SendMessage("ApplyDamage"), TheDamage, SendMessageOptions.DontRequireReceiver); } } } I get 2 errors that says expecting semicolon at the end and expecting found /n PLEASE HELP! javascript semicolon scrpting found Tue, 14 Jul 2015 09:22:32 GMT WaelShahine How Patch My game? I want to add a little extra Gui the game and some changes .how I patch my web game? with unity 5 audio optimization website hosting scrpting Mon, 18 May 2015 10:16:45 GMT hannyunity Shoot script not working anymore.... So I messed with my Bullet script so that it would instantiate an explosion prefab when it collided with something/ after 5 seconds if it didn't... and somehow now ONLY the explosion instantiates and not the bullet itself, when I fire the bullet doesn't move anymore and so just explodes on itself. If anyone could tell me what I did wrong that would be really appreciated. Here is the Shooting script sent on an empty character where the bullet should spawn: public class Shoot : MonoBehaviour { public Rigidbody2D Bullet; public float speed = 20f; private PlayerControl playerCtrl; private Animator anim; void Awake() { anim = transform.root.gameObject.GetComponent<Animator>(); playerCtrl = transform.root.GetComponent<PlayerControl>(); } void Update () { // If the fire button is pressed... if(Input.GetButtonDown("Fire1")) { anim.SetTrigger("Shoot"); // If the player is facing right... if(playerCtrl.facingRight) { // ... instantiate the bullet facing right and set it's velocity to the right. Rigidbody2D bulletInstance = Instantiate(Bullet, transform.position, Quaternion.Euler(new Vector3(0,0,0))) as Rigidbody2D; bulletInstance.velocity = new Vector2(speed, 0); } else { // Otherwise instantiate the bullet facing left and set it's velocity to the left. Rigidbody2D bulletInstance = Instantiate(Bullet, transform.position, Quaternion.Euler(new Vector3(0,0,180f))) as Rigidbody2D; bulletInstance.velocity = new Vector2(-speed, 0); } } } } And here is the Bullet script itself with the Explosion prefab public class Bullet : MonoBehaviour { public GameObject Explosion; // Prefab of explosion effect. void Start () { Destroy(gameObject, 5); } void OnExplode() { // Create a quaternion with a random rotation in the z-axis. Quaternion randomRotation = Quaternion.Euler(0f, 0f, Random.Range(0f, 360f)); . Instantiate(Explosion, transform.position, randomRotation); } void OnTriggerEnter2D (Collider2D col) { // If it hits an enemy... if(col.tag == "Enemy") { // Enemy script and call the Hurt function. col.gameObject.GetComponent<Enemy>().Hurt(); OnExplode(); Destroy (gameObject); } { OnExplode(); Destroy (gameObject); } } } movement shooting scrpting Sat, 11 Apr 2015 09:58:22 GMT XxRQxX Field Initializer Error Hello everyone, I'm working on a project for school and I need to get this complete before I move on. I'm trying to compile a Dictionary listing for animals. For some reason this script is giving me a field initializer error. Any reason why? using UnityEngine; using System.Collections; // NOTE: To use Dictionary, we must add this line using System.Collections.Generic; public class ZooRegistry : MonoBehaviour { int numZebras = zooRegistry["Zebra"]; // variable type variable name Dictionary<string, int> zooRegistry = new Dictionary<string, int>(); // Key type Value type // Use this for initialization void Start () { zooRegistry.Add ("Zebra", 8); zooRegistry.Add ("Kangaroo", 2); zooRegistry.Add ("Giraffe", 6); zooRegistry.Add ("Penguin", 17); zooRegistry.Add ("Sea Turtle", 4); Debug.Log (zooRegistry ["Zebra"]); } // Update is called once per frame void Update() { } unity 5 variable dictionary scrpting cod Thu, 09 Apr 2015 04:37:26 GMT kingari When transform.position is NOT world space!? Interesting problem, no idea what's going on. I was under the impression that transform.position was always world-space coordinates. I have a skeletal rig, to which I have attached a small collider object to each Hand joint. This is so when the character touches something with their hand, it can trigger stuff. Now, the left hand works just fine. I put a script on each collider (the SAME script). In it I capture the WORLD coords of the collider at the time (and track motion too). Looks like this: void Update () { Debug.Log (name+" at "+transform.position.ToString ()); On the left hand, the numbers look correct. Move hand up, Y numbers become more positive, down Y become more negative. On the right hand, however, move hand up, Y numbers become more negative, and vice versa. But this is WORLD space right? So moving anything up, Y values should go up too. It's going the opposite direction. ANY ideas welcome, as I'm losing my hair on this one. transform scrpting Mon, 30 Mar 2015 19:25:12 GMT SpiralConDave New player can't see old players (Unity Network) Hello, I'm using Unity Networking and I have a problem. New spawned player (GameObject) can't see players (GameObjects) spawned before him. I know that question has been asked before, but I didn't found any solution. I'm using Network.Instantiate to "spawn" a player, why doesn't it "save" So, here's my code: void Start () { DontDestroyOnLoad (gameObject); DontDestroyOnLoad (this); Instance = this; //networkView.DontDestroyOnLoad(networkView); } void OnLevelWasLoaded(int level) { if (level == 1){ SpawnPlayer (); } } private void SpawnPlayer(){ GameObject gracz = (GameObject)Network.Instantiate (graczPrefab, GameObject.Find ("Spawny").transform.FindChild("spawn").transform.position, Quaternion.identity, 0); mojGracz = gracz; networkView.RPC ("SpawnPlayer_RPC", RPCMode.AllBuffered, NazwaGracza); gracz.transform.FindChild ("TrzymaczKamery").gameObject.SetActive (true); gracz.transform.FindChild ("modelGracza").gameObject.SetActive (false); gracz.GetComponent<CharacterController>().enabled = true; gracz.GetComponent<RuchGracza>().enabled = true; gracz.GetComponent<Kroki>().enabled = true; //Camera.current.gameObject.SetActive (false); } [RPC] void SpawnPlayer_RPC(string nazwaGracza){ GameObject.Find ("Gracz(Clone)").name = nazwaGracza; } Any solutions? scrpting Thu, 29 Jan 2015 21:36:18 GMT KlivenPL Turn off a script and then back on? I need to turn off a script in my game and then turn it back on. Pretty much the point is here: I got ToggleCursor.cs I need to turn off MouseLook.cs Someone help me! :D on off scrpting Thu, 18 Sep 2014 17:12:43 GMT FineGamer Switch GUIBox for another after few seconds How about, I'm trying to create a GUI Box to start with a message and switch to another after a few seconds, I have tried this script but it only shows the first GUI Box, can you help me please? var Greeting : boolean; var color : Color; var Protocol : boolean; function Start() { ShowGreetings(); } function OnGUI() { if (Greeting) { GUI.color = color;; GUI.Box (Rect (Screen.width / 6 - 50, Screen.height / 2 - 200, 250, 100), "<color=#00ffffff>Abrir vía aérea,\nRespiración</color>"); } } function ShowGreetings() { Greeting = true; color =; yield WaitForSeconds(10); while (color.a > 0) { color.a -= Time.deltaTime/3; yield; } Greeting = false; yield WaitForSeconds(2); ShowProtocols(); } { if (Protocol) { GUI.color = color;; GUI.Box (Rect (Screen.width / 6 - 50, Screen.height / 2 - 200, 250, 100), "<color=#00ffffff>Cánula,\nOxígeno</color>"); } } function ShowProtocols() { Protocol = true; color =; yield WaitForSeconds(10); while (color.a > 0) { color.a -= Time.deltaTime/3; yield; } Protocol = false; } scrpting Thu, 11 Sep 2014 06:07:26 GMT Medhdmi Pause game without using timeScale Hi all, As the title suggests, is there are simple way to pause a game without using `Time.timeScale`? I haven't decided on how I want the pause functionality will work in my game, but I can see problems I may run into if I use the "timeScale" method. What are other ways to pausing a game? Pls try to give examples in C#. ----- Thank you in advance for your help. c# pause game scrpting gamedesign Thu, 19 Jun 2014 01:36:01 GMT Alieos How do you check to see if the class name of a script and the file name is the same? Please give detailed instructions. scrpting Thu, 19 Jun 2014 01:10:41 GMT Bestbuddyonetwothree Score problem First sorry for my english. i made this code but i dont now why it dosent work : var guiScore : GUIText; private var score : int = 0; function Start () { guiScore.text = "Score: 0"; } function OnTriggerEnter() { score ++; guiScore.text = "Score: " + score; } when i catch the first coin the score goes to 1 but then when i catch the second steys in 1 PLEASEEE HELP!!!! scrpting Wed, 19 Mar 2014 05:42:28 GMT nugarte How to make my player respawn? i am creating a FPS survival game and when i die my player just falls down and nothing happens and i want to make him Respawn somewhere can you tell me how to do it or send a likn to a giude? respawn scrpting Sat, 08 Mar 2014 18:13:05 GMT therock3211 How to gradually increase targetAngularVelocity value of a Configurable joint? How do I gradually increase the speed of a configurable joint? When I assigned a value of Vector3(0,0,5) to a conjo rotating about z-axis, value 5 is applied instantly. Is there a way to make the speed goes up gradually to assigned speed? velocity joint configurablejoint scrpting Thu, 27 Feb 2014 03:24:03 GMT ikelaiah A question about references in C# Despite reading everything I can find on the matter I can't seem to figure this out. I have a camera called "standbyCamera" that is deactivated by a script called NetworkManager.cs. I have another script that is attached to the player called health.cs that I would like to reactivate it. Here are simplified versions of those scripts: NetowkManager.cs: using UnityEngine; using System.Collections.Generic; public class NetworkManager : MonoBehaviour { public GameObject standbyCamera; public void SpawnMyPlayer () { standbyCamera.SetActive (false); } } Health.cs: using UnityEngine; using System.Collections; public class Health : MonoBehaviour { public float HP = 100f; public float currentHP; private NetworkManager _NetworkManager; public GameObject _standbyCamera; void Start () { currentHP = HP; _standbyCamera = GameObject.Find("standbyCamera") [RPC] public void TakeDamage (float amt) { currentHP -= amt; if (currentHP <= 0) { Die (); } } public void Die () { _standbyCamera.SetActive (true); // This should be set to the same camera as the Network Manager script, but I don't know how to do that. } } Any help would be greatly appreciated. Thanks! gameobject setactive access scrpting Mon, 06 Jan 2014 22:43:01 GMT lexen1 Stop Coroutine itself? As Title , I have a Coroutine function and use StartCoroutine to run. Now I want to stop itself when finished statement in Coroutine. How to do it? Thanks in advance. coroutine scrpting Fri, 06 Sep 2013 03:06:50 GMT YukariYakumo Is my Unity Bugged? Or am i an idiot? Im trying to make it detect a collision between the gameobject and the floor but every time i press build to check it says there should be a parenthesis where the OnCollisionEnter phrase is in the function? Example: function OnCollisionEnter(CollidedWith : Collision) { error expecting (, found'OnCollisionEnter' if( == "Floor"){ JumpCount = 0; } } Tell me if i made a mistake or its a glitch and how to fix it. Just plz help! collision scrpting preformance Wed, 07 Aug 2013 05:32:58 GMT PowerCore2000 Where can I find C# tutorials for a absolute beginner? Hey All, I wanted to ask where i could find c# tutorials aimed towards the completer beginner to unity and scripting. I have no scripting knowledge and am completely new to unity. I have tried loads of tutorials but they just dont explain what the code means and how it works. For example, I read the clock tutorial, and i fount it very nice in the beginning but after wards i didnt know what things like bool and some other things mean and why they were placed in such format. Are there any tutorials that explain the whole concept properly? Thx in advance. c# beginner new scrpting Thu, 20 Jun 2013 09:53:28 GMT AviGamer