_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Why is an empty Unity Iphone Build over 700 Megs? Is this Normal? So after 2 weeks of slaving over my first game I was finally done! I was entirely ecstatic....until I saw its file size. 770 Megabytes For a simple numbers game, that was way too much and I created an empty unity project as a test and that was also over 700 megs Why is an empty Iphone project this large? |
0 | Does Unity store temporary autosaves for scripts? If not, how do I avoid data corruption My PC lost power in the midst of a save(twice in a row) and I've lost my scene setup as well as a script(its contents actually). I would like to know if there are any fail safes for saving files. If not, how would I prevent future data loss corruption. |
0 | Display Rich Text in a TextMeshProUGUI component I am rading a text to be displayed in a Text UI from an asset using the standard commands Resources.Load lt TextAsset gt ("nameOfMyTextAsset") The text is a .txt. The text contains richtext tags to format the text in bold or italics. The richtext tags are displayed as such. I am using TextMesh Pro and insert the text via the following cmd public TextAsset MainText MainText Resources.Load lt TextAsset gt ("nameOfMyTextAsset") this.GetComponentInChildren lt TextMeshProUGUI gt ().text MainText.text The text is displayed like this How can I read text with richtext tags from a text asset? |
0 | Saving Game Data In Windows Store App I am creating a windows store game using unity . I want to save the current high score data . I most probably use StreamReader StreamWriter for saving data but when i build the executable for windows store app , the compiler is giving me a error that StreamReader class is not supported . Is there any alternate way for solving this problem ? |
0 | Shader that draws just vertex points The game I am developing is in unity and I want to make a shader which can be put on a mesh that only 'draws' color on each vertex point. I am not proficient with shaders, and out of all my searching I have come up empty handed I unfortunately don't even know how to look up this question (I seem to only find results about point clouds, which only serves to confuse and scare me more P). Any help or if you can point me in the right direction on what to search, I would be very much greatful. |
0 | Why when using Linerenderer it's drawing a line also in scene view? I want to draw lines using the Linerenderer only in the game view window. I'm using Debug.DrawLine but only drawing Red lines but for some reason when the Linerenderer draw a line s one of the Linerender lines is yellow it seems the green linerenderer is getting on the red one in the scene view window. Debug.DrawLine(Input.mousePosition, hit.transform.position, Color.red) Is there a way to avoid it ? So Debug.DrawLine will draw only in sceneview and the Linerenderer will draw only in the game view window ? using System.Collections using System.Collections.Generic using UnityEngine public class RotateObjects MonoBehaviour public GameObject objectsToRotate public float speed 0.1f public Vector3 spinDirection public bool useMouse false public bool automaticSpin false public LineRenderer linerendererPrefab List lt LineRenderer gt lrs new List lt LineRenderer gt () Use this for initialization void Start() for(int i 0 i lt objectsToRotate.Length i ) var lr Instantiate(linerendererPrefab) lrs.Add(lr) Update is called once per frame void Update() if (objectsToRotate.Length gt 0) for (int i 0 i lt objectsToRotate.Length i ) var hits Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition), 100.0f) for (int x 0 x lt hits.Length x ) RaycastHit hit hits x if (hit.collider.name objectsToRotate i .name) objectsToRotate i .transform.Rotate(1, 1, 1) Debug.DrawLine(Input.mousePosition, hit.transform.position, Color.red) SpawnLineGenerator(Input.mousePosition, hit.transform.position, false) if(hits.Length 0) SpawnLineGenerator(new Vector3(0,0,0), new Vector3(0,0,0), true) if (useMouse true) if (Input.GetMouseButton(0)) Rotate(i) else Rotate(i) private void Rotate(int i) if (automaticSpin true) objectsToRotate i .transform.Rotate(1, 1, 1) void SpawnLineGenerator(Vector3 start, Vector3 end, bool reset) for(int i 0 i lt lrs.Count i ) if (reset) lrs i .SetPosition(0, start) lrs i .SetPosition(1, end) else lrs i .SetPosition(0, start) lrs i .SetPosition(1, end) |
0 | Can a generic class inherit from MonoBehaviour? Expanding upon a previous tutorial, I am adapting a follow script to support multiple variations of a Bezier spline. Each spline variation uses a custom interface called IBezierInterface, and the follow script accesses the method GetPointOnCurve() to determine the correct position. In theory, this all seems very simple. However, I appear to be running in to some trouble. While I intend to pursue the general issues a bit more, myself, I realise that I may be shooting myself in the foot with the generic implementation. While I can find a lot of good examples demonstrating the correct use of generic types, I can not find anything that gives an example of a generic class that inherits from another class. For example, Microsoft documentation includes examples of inheritance as a restriction on the actual type, and an example of inheriting from a generic class but there are no examples of a generic class that inherits from a standard class. Unity documentation has even less examples, but none pertaining to my query. I am not getting errors but that is no guarantee against error. I can not conceive a good prototype model to test my theory, either, given the fact that I am fairly new to the concept of generic types. Given that I am specifically needing my class to be a MonoBehaviour can I make a custom generic class that inherits from MonoBehaviour, such as in my example? public class SplineWalker lt T gt MonoBehaviour where T IBezierInterface ... |
0 | Pressing two on screen buttons at the same time, with the same touch Android Unity Event Triggers OK so I have this code working and the methods are being called at the times I'd expected (ie. when the mouse hovers over the button and stops hovering over it) But when I test it on an Android device, it is not possible to press both buttons at once. The only button that gets pressed is the one where the touch down happened. public class EventHandlerThrust MonoBehaviour, IPointerEnterHandler, IPointerExitHandler public static EventHandlerThrust instanceOf HideInInspector public bool isButtonPressed false void Start() instanceOf this public void OnPointerEnter(PointerEventData eventData) isButtonPressed true Debug.Log("OnPointerEnter Interfaceyyyy called.") public void OnPointerExit(PointerEventData eventData) isButtonPressed false Debug.Log("OnPointerExit Interfaceyyyy called.") So is it possible to allow the user to press both buttons by holding his thumb over both at the same time, using the Event Trigger System? Or do I have to implement some other kind of Input system? |
0 | Attach component of other Object to a variable within Unity Inspector This question might sound a bit stupid and I'm sure there is a simple solution for this .. I'm just not finding it Actually all I want to do is attach the MeshRenderer Component of this Object to a variable of a script on another Object like Problem As soon as you click on the Capsule Object ofcourse the Inspector changes to this Object and I cannot drag in a component to the previous selected Object anymore. I know there are a lot alternatives like linkin only the GameObject e.g. as MeshObject and later in code refer to MeshObject.GetComponent lt MeshRenderer gt but I wondered if this can be done directly, too. |
0 | How to use HD and SD sprites in Unity addressables I am able to load sprites using Unity addressables. But how can I use SD or HD variants of a sprite based on my device resolution? Previously I was using LIBGDX, and it has ResolutionFileResolver to handle this scenario. |
0 | Sprite with shadows in both sides I have a gameobject with a SpriteRenderer, and I want it to cast (and receive) shadows like a 3D model. The sprite will turn around depending of his direction, so all faces must cast shadows. I already activated Cast Shadows and Receive Shadows in the Sprite Renderer component, and also included a Transparent Cutout shader with the Cull Off instruction (so all faces are drawn), but only one side of the sprite is being affected by light, while the other is even darker. To ilustrate How can I achieve an sprite casting shadows with both faces? |
0 | Projectile movement around spheres of varying gravity I found a game on the Internet called Sagittarius. This game is very fun, and I have a question how can I make the arrow move like it does in this game? I know each sphere has a different gravity, but when I try to use this formula, it's not working as I expect . Can any one help me resolve this problem? Thanks. public List lt PlanetABC gt p new List lt PlanetABC gt () new PlanetABC() x 0.91f, y 1.28f, gravity 5, r 5 , new PlanetABC() x 8.12f, y 1.3f, gravity 3, r 10 void Start () void Update () float gravityOnX 0 float gravityOnY 0 foreach (var planet in p) if (Vector2.Distance(g.transform.position, new Vector2(planet.x, planet.y)) gt planet.r) continue if (planet.x gt g.transform.position.x) gravityOnX planet.gravity else gravityOnX planet.gravity if (planet.y gt g.transform.position.y) gravityOnY planet.gravity else gravityOnY planet.gravity if (currentGravityX gt gravityOnX) currentGravityX Time.deltaTime else currentGravityX Time.deltaTime if (currentGravityY gt gravityOnY) currentGravityY Time.deltaTime else currentGravityY Time.deltaTime Debug.Log(currentGravityX " " currentGravityY) var DEG2RAD Mathf.PI 180 float vx1 Mathf.Cos(angle DEG2RAD) power float vy1 Mathf.Sin(angle DEG2RAD) power float y (0.5f currentGravityY time vy1) time float x (0.5f currentGravityX time vx1) time Vector3 pos g.transform.position pos.x x pos.y y g.transform.position Vector3.Lerp(g.transform.position, pos, Time.deltaTime) time Time.deltaTime Here is the game https gprosser.itch.io sagittarius |
0 | Game is darker on build I've been recently doing test builds of my game. In Unity, I worked on baking the lighting to ensure everything looked fine. However, upon building, the game level becomes far darker and much of the lighting and baking is ineffective. Here is how the scene looks in the editor And here is how it looks in the built game It's much darker than intended. Here are my lighting settings which I've baked in Unity's Editor. These settings and lightmap parameters were designed to, at least in the editor, provide decent quality while making light bake times relatively quick. However, I've noticed that newer Unity's Lighting settings are way different now, so perhaps something is amiss here? I've been at my wits end trying to figure this out for the past while, but I can't figure out why this is happening or how to fix it. Any ideas? |
0 | Make Unity game using files directly from game directory For stats of enemies, and several other kinds of info, I've decided to use not inspector fields or hardcoded values, but to store values to some XML and other types of files, and read them from scripts, obtaining required values. And I want this files to stay in game folder, not packed to .assets file, because I'd like to have possibility to quickly modify this values without need to rebuild whole game. So, how can I mark asset in editor, that it should not be included to .assets, but stay in unchanged form in game folder? UPDATE I will slightly rephrase what I want to achieve. I need possibility to have file in game directory, so I can read it from game, and I'd like to have this possibility in both editor and built game. So, as for answer, I will also receive information about what folder is considered as game folder in editor. |
0 | Unity3D, how much code do you write? I'm curious to know the workflow when creating a game in Unity3D? Does it generate a lot of code for you? My understanding is that you describe the game in Unity and do scripting on the back end to do the logic. Kind of like you use Unity to describe the puppets and you use a scripting language as the puppet master. |
0 | Exclude removed objects from list counting? I want to count the number of objects on my list. But because I remove and add, my script keep count those empty elements. update This happen when I destroy the object when it inside the collider. This object does not get out from quot OnTriggerExit2D quot . public List lt GameObject gt Sorts public List lt GameObject gt ItemsInside public int NumSorts, NumItems Update is called once per frame void Update() NumSorts Sorts.Count NumItems ItemsInside.Count it doesn't give correct number void OnTriggerEnter2D(Collider2D other) if (other.CompareTag( quot Sort quot )) Sorts.Add(other.transform.gameObject) if (other.transform.name ( quot GameItem quot )) ItemsInside.Add(other.transform.gameObject) void OnTriggerExit2D(Collider2D otherOut) if (otherOut.CompareTag( quot Sort quot )) Sorts.Remove(otherOut.transform.gameObject) if (otherOut.transform.name ( quot GameItem quot )) ItemsInside.Remove(otherOut.transform.gameObject) |
0 | The script in the event trigger disappears when the player dies I am making an 2D platformer for mobile in unity with c . Right now it is setup in a way that I have one joystick that controls the players shooting, arm rotation and movement. But on that joystick there is an event trigger which is what I use to make the player shoot the gun when the joystick is pressed. The problem I am having is when the player dies the script in the event trigger disappears and I am no longer able to shoot. I am calling Destory() when the player dies and he does have lives. the location of that script is on the player I am not sure if that has anything to do with it but of anybody has any suggestions that would be great. Here is the code for when the player dies and respawns public static void KillPlayer (Player player) Destroy (player.gameObject) remaningLives 1 if ( remaningLives lt 0) gm.EndGame() else gm.StartCoroutine(gm. RespawnPlayer()) |
0 | Character Controller Rotation in Unity I am using the following code for moving a capsule Vector3 move new Vector3(Input.GetAxis( quot Horizontal quot ), 0, Input.GetAxis( quot Vertical quot )) controller.Move(move Time.deltaTime playerSpeed) I am using the following code for the camera, which is a child of the capsule. (xRotation is intialized to 0.0f, and playerBody is a transform) float mouseX Input.GetAxis( quot Mouse X quot ) mouseSpeed Time.deltaTime float mouseY Input.GetAxis( quot Mouse Y quot ) mouseSpeed Time.deltaTime xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90f) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f) playerBody.Rotate(Vector3.up mouseX) The character is always moving in the same direction, ignoring the rotation. How can I fix this? |
0 | It lags when it collides. Help? ( I am trying (and believing) to make a game of pong. I have got a slightly decent working game. I haven't implemented the scoreboard or AI yet because I want the physics to work first. I am trying to reverse the direction of the ball when it hits either paddle just to make it work cleanly and am having the issue where it changes direction twice, it bounces off the paddle as expected and then goes in the opposite direction to when it hit the paddle . If anyone could help me, it would be much appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class BallController MonoBehaviour private float randomNumber private float range private float pointOfContact private float paddleTop private float paddleBottom private float limits private int speed private int caseNumber private Vector2 direction private Rigidbody2D ballRigidbody void Start () Getcomponent finds the rigidbody of the attached object. ballRigidbody GetComponent lt Rigidbody2D gt () speed 5 caseNumber Random.Range (0, 2) range PickARange (caseNumber) ballDirection (speed, range) void FixedUpdate() void OnCollisionEnter2D (Collision2D coll) if (coll.gameObject.tag "Player" coll.gameObject.tag "Computer") pointOfContact ballRigidbody.position.y print (pointOfContact) ballRigidbody.velocity new Vector2 (ballRigidbody.velocity.x, ballRigidbody.velocity.y 1) void ballDirection (int ballSpeed, float yDirection) randomNumber (Random.Range (0, 100)) if (randomNumber lt 49) direction new Vector2(Random.Range ( 1.0f, 0.5f), yDirection) ballRigidbody.velocity (direction ballSpeed) else direction new Vector2(Random.Range (0.5f, 1.0f), yDirection) ballRigidbody.velocity (direction ballSpeed) float PickARange (int number) switch (number) case(0) range Random.Range (0.5f, 1.0f) return range case(1) range Random.Range ( 1.0f, 0.5f) return range default range 1.0f return range I thought to multiply the whole velocity by 1 but that just caused a loop because of the lag. Even though that's the right way to reverse the direction. I think. Thanks Peeps! |
0 | Align spawned particle system I am working on a game in which tanks can shoot at each other. I intend to spawn a spark particle system (particles emit to Z) when a bullet hits a surface. I want to align the Z axis of the newly spawned particle system to be a) in a 90 degree angle to surface that has been hit b) in a reflective angle from the original trajectory I know that I can "fake it" by setting particle Z to World 90 degrees, however then it will do so on any angled surface, while I would like to have the particle system dynamically orient itself in a 90 degree angle away from the surface that has been hit or reflect into the direction away from the incoming bullet. hope you can help me, getting quite frustrated. |
0 | How can I use Cross Platform Input in Unity 2019? I am trying to use CrossPlatformInput in Unity 2019 to follow this tutorial to use it on iOS https www.youtube.com watch?v Auj1mrsfXDE However, I have no item in the top bar for "Mobile View" like in the tutorial, and I do not know how to enable it. I have Standard Assets imported already. Is there an example project I can download with CrossPlatformInoput that works with iOS or a way for CrossPlatfromInput to work in modern versions of Unity? |
0 | How do I find the name of the current audio clip being played? I have a title scene and a credits scene that use the same music. When I start my game the title scene music plays, and I have my game set up so the audio manager is not destroyed on load. When I enter my credits scene I do not instruct any new music to play, but each time I reload my title scene the title music restarts because a script in the scene tells it do so. How can I get the name of the current audio track so that I will only play audio if it differs from what's currently being played? This is my "LevelMaster" script which is responsible for handling the audio in each scene. public class LevelMaster MonoBehaviour private AudioManager AudioManager SerializeField private string trackName private void Start() AudioManager GameObject.Find("AudioManager").GetComponent lt AudioManager gt () AudioManager.Play(trackName) public void PlaySound(string soundName) AudioManager.Play(soundName) public void StopSound(string soundName) AudioManager.Stop(soundName) |
0 | Error Framework 'Mono .NET 3.5' not installed Recently I installed Ubuntu Mate 16.10. Unity and Monodevelop works, but when I try to compile the javascript on Monodevelop, appears an error Error Framework 'Mono .NET 3.5' not installed. (Assembly CSharp) On 14.04 all works very well but not here....what is the way to fix this problem?? I searched on the internet and I can't find the answer. |
0 | Attach the UIButton to Component Via Script (C Unity) I want to attach the UI to the MC Streaming Option Script via Code . What i wanted here is that this live onOff will go to the Livestream(MC Streaming Option) without dragging it . And i don't know where to start. PS The MC Streaming Option script is being attached only when the program run MC StreamingOption mcStreamingOption gameObject.AddComponent lt MC StreamingOption gt () |
0 | How do I pause and unpause gameobjects on is own in the scene without pressing keys in unity3d I can't get my gameobject to pause or unpause in the scene in Unity3d. I need the game to pause for a couple of seconds maybe longer than unpause by itself. Here is my script using UnityEngine using System.Collections public class hu MonoBehaviour GameObject pauseObjects public bool isPaused void Start () pauseObjects GameObject.FindGameObjectsWithTag("Player") Update is called once per frame void Pause () if(Time.timeScale 1) Time.timeScale 7f else if (Time.timeScale 8f) Time.timeScale 1 |
0 | How do I manually draw a part of a sprite sheet? I'm working in Unity, and I'm finding that the animator isn't working for what I'm trying to do, in my 2D game. I want to build a specific animation, using sprite sheets, and be able to reuse the same animation with other sprites that are the same size and dimensions by cells. After some research, I find that it is impossible. Instead, I'm trying to create my own animation script, but I don't understand how to tell Unity to draw only a section of the sprite. Something like in XNA, where you could render only a specific rectangle of a sprite using start and end coordinates. How do I manually draw a part of a sprite sheet? |
0 | Make the texture array node work with cubemaps? I am working on a procedural interior mapping shader in Unity's Shader Graph. Ideally, I'd like to feed it a set of cubemaps it can pick from semi randomly. However, it seems that by default the texture array asset one can provide to a graph does not support reading cubemaps. Does anyone have a way to use this, or perhaps a clever custom node or alternate texture mapping, so that I can read a number of cubemaps into the shader semi randomly? Preferably an arbitrary number, but even a fixed number would be somewhat of an improvement. |
0 | Unity Is there a way to edit a Skin file? My project has multiple skins and sometimes we have to deal with skins with many custom styles. Editing them in the editor is difficult, for instance, I cannot delete one style that is not the last one without deleting the ones after it. Would there be a way to edit a file that represents this skin? Could I edit a skin file if I use Text in the Asset Serialization Mode (Unity Pro)? If not, is there something in the Unity Store to help me better edit skins? |
0 | Unity associated game object is null when running I am just starting with Unity. I have two UI Text game objects, Atext and Btext. I have associated them by drag dropping with my PlayerController script public variables, say public Text atext and public Text btext. Before running, the Unity editor correctly shows that Atext and Btext are correctly associated with the public variables. When running with debug, I get a null reference exception with btext and even the Unity Editor shows the association as None (Text). After stopping, the association turns to Btext as it is supposed to be. The script is very simple and I don't set btext to null at any point. When I create a new UI Text object by duplicating Atext, it works correctly after associating it with some new variable. When I create a new UI Text object by Create UI Text, it doesnt work Might be a stupid question but what am I forgetting? Edit Here is the problem again with code Before running with debug, the editor shows PlayerController2 (Script) Script PlayerController2 Speed 7 Countboxref Countbox(Text) Winboxref Winbox (Text) Brokenboxref Text (Text) where Countbox, Winbox, and Text are Canvas UI Text objects which I have drag dropped into place. Winbox object has been created by duplicating it from Countbox, Text has been created by Create UI Text. enter using UnityEngine using UnityEngine.UI using System.Collections public class PlayerController2 MonoBehaviour public float speed public Text Countboxref public Text Winboxref public Text Brokenboxref private Rigidbody rb private int boxit void Start () Countboxref.text "count" Winboxref.text "winner" Brokenboxref.text "broken" When the program breaks on line Brokenboxref.text "broken , the editor shows Brokenboxref None (Text) and when the execution is stopped completely, it again returns to Brokenboxref Text (Text) Note 1 In this project, every Text object created with Create UI Text is broken. A new Text object works only when I select Countbox or Winbox and duplicate it. Thus it is not possible that the object would be explicitly destroyed in the code. I can create as many Text objects as I wish by copying (all don't work) and as many Text objects as I wish by duplicating (all will work). Note 2 when I create a new project from scratch, of course everything works as expected. I assume the project is somehow corrupted. Edit 2 No prefabs or such. Just the basic roll a ball tutorial. But this was my son's project so I am not sure what he has done when following the tutorial. Note 3 The problem went away when I deleted the Library folder and forced Unity to rebuild it. Don't know yet if I caused any other problems by doing that. I saw that somewhere as a suggestion for corrupted projects. I don't know if there is a proper way to refresh. Also, this project was originally started with Unity 4.6 and upgraded to 5.02 |
0 | Use constant force to hold something in position This may actually be more of a Physics.SE question but since im doing this in Unity I figured I'd ask here. I am playing around with the Constant Force component and have a sphere constrained with a linear configurable joint (y axis free). With one key I apply a force in one direction to get it moving, but then when i press another key, I want to stop it and hold exactly in place by using an opposite force. So even if some other rigid body hits the sphere, it wont move until I remove a force. Unfortunately, Unity doesnt allow more than one constant force on a gameobject (probably a good reason, not sure exactly) and I know if I do a net force, that it would just end up being 0, which would kind of work but the sphere would move if it gets hit. Another thing I tried was to take the spheres current force and constantly flip it from positive to negative every FixedUpdate but that didn't seem to work at all. I know the quick and easy way would be to just set velocity to zero, but I see tons of comments saying that modifying velocity directly breaks the physics, is bad form, etc. and I want to do this as properly as possible. The best way I can describe what I'm trying to do is like that science experiment where you take a ping pong ball and use a blower to push just enough air to counter gravity and the ball seems to hover in place. My only difference is that my constraint is side to side instead of up down. |
0 | Unity3D Resize texture without corruption I am currently working on a solution to make my game look very pixelated, like Doom or Quake. But there is a big problem. I'm using Unity Personal. I render my camera to a 1920x1080 texture, then I try to use Texture2D.Resize on it, then render it back to the screen using ScaleMode.StretchToFill. But the problem is that the texture seems to corrupt when I use Texture2D.Resize on it. And here is my current code using UnityEngine using System.Collections public class PixelRenderer MonoBehaviour Texture2D texture Use this for initialization void Start () texture new Texture2D(256, 256, TextureFormat.ARGB32, false) Update is called once per frame void OnPostRender() texture new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false) texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0) texture.Apply() texture.Resize(256, 256) void OnGUI() GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), texture, ScaleMode.StretchToFill) Is there something that I'm missing here? Or am I doing something wrong? |
0 | Bullets doesn't do any damage I have a melee enemy tagged as enemy. enemy has two coliders a capsule(physics) and a sphere(for attacking player in radius and istrigger) and a particlesystem, enemy has enemyhealth script attached. Similarly, bullet has capsule collider and set istrigger, I've attached enemyhealth script to bullet as enemy sphere and bullet capsule are triggers (bullet doesn't have any particle system need fix for this too without raycast), bullets are destroyed on colliding with enemy but doesn't damage the enemy. script used for enemy health using UnityEngine using System.Collections public class enemyhealth MonoBehaviour public int health 40 public int current public int score 10 public AudioSource deathclip public ParticleSystem death CapsuleCollider Collider bool dead Use this for initialization void Start () deathclip GetComponent lt AudioSource gt () Collider GetComponent lt CapsuleCollider gt () death GetComponentInChildren lt ParticleSystem gt () current health dead false void Update() public void Takedamage (int amount ) if (dead) return current amount if (current lt 0) die () void die () GetComponent lt NavMeshAgent gt ().enabled false dead true Collider.isTrigger true deathclip.Play () death.transform.parent null death.Play () Destroy(death.gameObject) Destroy(gameObject) script used for bullet using UnityEngine using System.Collections public class mover MonoBehaviour public float speed public int damage 10 enemyhealth Enemyhealth GameObject ENEMY bool enemyinrange Use this for initialization void Awake () GetComponent lt Rigidbody gt ().velocity transform.forward speed Enemyhealth GetComponent lt enemyhealth gt () ENEMY GameObject.FindGameObjectWithTag ("enemy") void OnTriggerEnter(Collider other) if(other.gameObject ENEMY amp amp Enemyhealth.currenthealth gt 0) enemyinrange true Destroy(gameObject) void OnTriggerExit(Collider other) if (other.gameObject ENEMY) enemyinrange false void Damage() Enemyhealth.Takedamage (damage) Update is called once per frame void Update () if (enemyinrange) Damage () |
0 | Accessing vertex Input in surf directly without vert's out parameter In Tessellation Shader I can get the vertex Input in vertex shader as follows o.worldPos v.vertex.xyz But how do I get the worldPos directly without filling the out parameter in the vert function. Asking this because the shader is a DX11 Tessellation one and out parameter in vert function is not available at all. basically I want Initialize my Input shader and pass It to surface shader In vertex shader.I can do It but It's different In Tessellation shader so I need to Accessing vertex position in surf directly without vert's out parameter. Shader "Tessellation Sample" Properties EdgeLength ("Edge length", Range(2,50)) 15 MainTex ("Base (RGB)", 2D) "white" DispTex ("Disp Texture", 2D) "gray" NormalMap ("Normalmap", 2D) "bump" Displacement ("Displacement", Range(0, 1.0)) 0.3 Color ("Color", color) (1,1,1,0) SpecColor ("Spec color", color) (0.5,0.5,0.5,0.5) SubShader Tags "RenderType" "Opaque" LOD 300 CGPROGRAM pragma surface surf BlinnPhong addshadow fullforwardshadows vertex disp tessellate tessEdge nolightmap pragma target 4.6 include "Tessellation.cginc" float EdgeLength float4 tessEdge (appdata full v0, appdata full v1, appdata full v2) return UnityEdgeLengthBasedTess (v0.vertex, v1.vertex, v2.vertex, EdgeLength) float Displacement struct Input float4 position POSITION float3 worldPos TEXCOORD2 Used to calculate the texture UVs and world view vector float4 proj0 TEXCOORD3 Used for depth and reflection textures float4 proj1 TEXCOORD4 Used for the refraction texture void disp (inout appdata full v, out Input o) UNITY INITIALIZE OUTPUT(Input,o) o.worldPos v.vertex.xyz o.position UnityObjectToClipPos(v.vertex) o.proj0 ComputeScreenPos(o.position) COMPUTE EYEDEPTH(o.proj0.z) o.proj1 o.proj0 if UNITY UV STARTS AT TOP o.proj1.y (o.position.w o.position.y) 0.5 endif sampler2D MainTex sampler2D NormalMap fixed4 Color void surf (Input IN, inout SurfaceOutput o) o.Albedo float3(0,0,0) ENDCG FallBack "Diffuse" but I have error Shader error in 'Tessellation Sample' 'disp' no matching 1 parameter function at line 173 (on d3d11) |
0 | How to activate Xbox controller vibrations in Unity? Is there any way to toggle the XBOX controller vibrations in Unity ? I came across Handheld.Vibrate() but it seems like it's not meant for controllers. |
0 | Animate moving object I have a sphere shot out of a cannon which i need to get lined up with another sphere when and if the two spheres collide. Considering that both spheres are moving (one in X and the other is shot at the first one) how would i animate the cannon sphere to line up if the collision occurs? I can use a bool to check if collision but how do i animate the projectile in the animation tab so that the projectile takes into consideration the always changing position of the X moving sphere ? |
0 | Splitting a character model to ease animations I've recently been looking into animations within Unity, and came across the idea of splitting my humanoid character's object into two at the waistline. The Idea being that animations used for movement can be applied to the legs, without interfering with general upper body animations stances (and vice versa). Is this a viable option and would there be any adverse effects from doing this? Also, is there any real need? I've noticed Unity is quite flexible when it comes to animations, but am unsure whether unity would be able to handle this? My main issue is different weapon types, where I would like the hands in different idle positions, but without having to have 4 or 5 different running forward animations. |
0 | Unity3D Button Slicing Problem I'm having trouble getting my button to appear correctly, as you can see in the image below, the right and top sides are stretched out and not displaying properly. I cannot figure out if this is a problem with the image itself or something wrong in the way I'm setting up the button. Here are the settings in the inspector window Here is the original image UPDATE So everything looked fine when I just opened up Unity, so I tried to figure out what I did last time for it to make this switch. It happens when I build and export the scene to my Android device. |
0 | How to rotate a skybox cubemap using Unity Shadergraph Seyed Morteza Kamali solved his own problem of rotating a mesh cubemap with shadergraph here How can I rotate cubemap in shadergraph? However, I have a starry night cubemap inside my Skybox shader done in Unity Shader Graph, and as there is no way to directly attach a script to a Skybox material, I've been accessing the skybox material and the shader via external script. I've been using the Bolt visual scripting, and with this script, it is fairly easy to access other properties of the skybox but not the rotation (4x4 matrix). It is possible to access floats, vector2's, texture maps and even the Cubemap, but even if I have set the cubemap rotation, which to my knowledge has to be done with a Matrix 4, as an Exposed property, when trying to access it, e.g with FindPropertyIndex it gives the value 1, indicating that the property is not found. Edit ok, I found this in the Unity documentation Matrix parameters are not exposed in the material inspector, but can be set and queried with SetMatrix and GetMatrix from scripts. As far as I understand the documentation, the example assumes a mesh renderer, which the skybox doesn't have. Another idea would be to use 3 vectors, which could be exposed and then apply the rotation somehow to them at the same time, I did some tests in this, but all I managed to create was to distort the cubemap. Again I am not trying to rotate the entire skybox, but just a cubemap inside the skybox shader this would allow different rotations to daytime clouds and nighttime stars. Would be best if everything could be done inside ShaderGraph, with the speed and axis values published as properties. A custom function perhaps? I am using URP 7.2.0 and Unity 2019.3.0f6. |
0 | How do I safely change properties on my skybox? Usually in Unity, when your scripts make changes to something at runtime, those changes are not persisted back to design time. This is generally considered a good thing. But for whatever bizarre technical reason, this does not apply to shader properties on materials. If you change something while the game is running, it stays changed! Generally the way to get around this is with a MaterialPropertyBlock, which also helps avoid generating a lot of garbage. But MaterialPropertyBlocks work with Renderers, which leaves out one rather important material the skybox. Right now, I have code that says RenderSettings.skybox.SetFloat( quot PropName quot , value) , and it's incredibly aggravating because it always needs to be reset afterwards. RenderSettings doesn't have a SkyboxRenderer property that I can use in conjunction with a MaterialPropertyBlock, so how can I change shader settings on my skybox and make them not persist after I exit play mode? |
0 | How can I roll up a plane with a vertex shader? I have plane that I want to roll up using a vertex shader, like this I found a math demo that shows the kind of curve I want my mesh to follow. I tried implementing this in my shader code, but the results don't form a roll as expected Shader " Custom Rolling " Properties MainTex ("Base (RGB)", 2D) "white" Bend("Bend",Float) 1 Strength("Strength",Float) 1 SubShader Tags "Queue" "Geometry" "IgnoreProjector" "true" "RenderType" "Opaque" Cull Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct v2f half2 texcoord TEXCOORD0 float4 vertex SV POSITION sampler2D MainTex float Bend float Strength v2f vert(appdata full v) v2f o I don't know what should I write here for rolling ,please help me. v.vertex.y ??? v.vertex.y exp( Bend (v.vertex.x Strength)) something like this but this hasn't twist effect o.vertex UnityObjectToClipPos(v.vertex) o.texcoord v.texcoord return o float4 frag (v2f i) COLOR float2 uv i.texcoord.xy float4 tex tex2D( MainTex, uv) return tex ENDCG Fallback Off Instead of a neat roll, the end of my plane shoots up into the sky! |
0 | Unity keeps reseting my Input Manager settings Basicaly, title. I want to change the second Horizontal entry in the Input Manager but when I do it won't save the changes afterwards. I rename the second Horizontal axis to "Strafe", and I'm reffering to it in the script like that, but when I run the game I get this error "Input Axis Strafe is not setup". This is because there's not input axis called "Strafe", because Unity just reset the default settings for some reason. There's no save button on this window, and I actually got it to save one time and it worked, but the next time it didn't and it reset the axis again! How can I avoid this? I set it up nicely Then it screws me over after running the game once |
0 | How to make an animation play when a button is pressed once? I have added an idle and jump animation to a character in unity. I can make the animation happen when the button is pressed. If the button is up middle at the animation the character goes to the idle position. But I want the whole animation happen in one press to the button and then go back to the idle position. My current script and Animator views are if (Input.GetKeyDown(KeyCode.Space)) Anim.SetBool("is jumping", true) ApplyInput(moveAxis, turnAxis) else if (Input.GetKeyUp(KeyCode.Space)) Anim.SetBool("is jumping", false) |
0 | GetButtonDown for Unity keyboard UI navigation? By default, Unity's keyboard navigation for buttons seems to check for GetButton rather than GetButtonDown if a menu has 5 items and I hold the down arrow, it'll scroll very quickly to the bottom. This feels awkward it would make more sense to check for GetButtonDown and only move 1 space per input. However, I can't find any option to let me change that. Any ideas or workarounds? |
0 | Unity How to take in multiple textures for Image Effect I am trying to write a composite Image Effect shader with a script that works as such The camera texture is taken, and stored into two different variables. For examples sake they will be tex1 and tex2. tex1 is modified by a shader. Both tex1 and tex2 are taken into another shader, which composes them together. The result is stored as tex. tex is printed to the screen. I am not having an issue with the actual content of the shader manipulating the image But I do not know how to pass in both textures to one shader as needs to be done in step three. Thanks in advance if anyone can help. |
0 | Infinite 3D Cave in Unity A friend and I are hoping to make a game in Unity in which you fly through an infinite 3D cave that can twist and wind in any direction (though obviously not to the point that the turns are impossible to make). We were thinking about creating a number of tunnel "pieces" that each curve a certain amount, and spawning each at the end of the one that came before. But we have no idea how to make sure that the mouth of one tunnel piece always aligns perfectly (in both position and rotation) with the end of the previous one. Can anyone offer any advice on how to accomplish this? Are we even going about it in the right way, or is there a better way to procedurally generate the cave? Bonus points It'd be awesome if the cave could change in diameter and or shape as well, though that'd just be gravy. |
0 | (How exactly to use EventSystem?) Assigning string Name to UI Button in Unity without CrossPlatformInput? I'm trying to make a new game for Android. There is a Jump button i've added as UI button , this works fine as I have a method for Jump() which I can just add to the OnClick() method in the Button's Inspector tab. However, for my 'Pick Up' button I don't really want a method for pick up. I already have my item pickup handling code inside a OnTriggerEnter() method and what I was hoping to do was have an additional if condition into my code like if (Input.GetButtonDown("Pickup")) then it ok to pickup! This is how i did it in my other projects. But I had been importing the CrossPlatformInput namespace and then just copied and adapted the buttons from the Jump button that came as standard with that. So now, I can't see how to name my button as 'Pickup'. I tried looking at the code from CrossPlatformInput, it seems it takes the name you provide it, and passes it to VirtualInput (also in the CrossPlatformInput namespace), I couldnt see a copy of this class anywhere, it think its closed source maybe Of course, I could probably manually make a method to add to the OnClick() which just makes a bool true only when it's being clicked. But I feel like there must be a way to just add this UI button as 'Pickup' to the Input system (like you do with "Horizontal", "Vertical" or "Jump" for example). Again, I tried to read the docs, and also lots of forums and sites like this. I found that the EventSystem will (or should) have the part I need, but i am now stuck. I tried this EventSystem.current.currentSelectedGameObject.name ?????????? I read that will return the name of the most recent button pressed, but how would that method know that my new Button is called "Pickup", I dont see how I added it to that yet? Another reason why i'd like to do it this way is for Cross Platform compatibility. If I make it this way, I already now that there is a certain button on the keyboard mapped in Project Input to the same name (ie. "Pickup" Left Ctrl). And it seems cleaner to use the existing way of doing this if possible, im sure its just that I dont know how yet. Most options ive seen online involve the OnClick inspector function, or CrossPlatFormInput imported package. I hope this makes sense to someone, and that there is a way to do it. Thanks for any help as usual very much appreciated. |
0 | Is Apple Game Center Multiplayer Online? I'm trying to build a real time multiplayer game on Unity. I was thinking of using services such as PUN or UNet, but then I ran into Game Center's multiplayer API. I've read that Apple doesn't give servers and only provides matchmaking services. Is that true? How does that work? Would I still need PUN UNet with Game Center? I guess what I'm trying to ask is, will Apple host my game's multiplayer instance, where position of players is synced across, and replace PUN UNet? Any help is appreciated. Thank you. Also, if you can provide a source with your answer, that'd be great. |
0 | How can I get the Launch dynamic link in Unity? I have integrated firebase dynamic link sdk in my app and it is working perfectly fine, I can generate dynamic links, and when clicked on them if the app is not installed it redirects me to the playstore and if installed open up the link in app. My question is how can I get that generated link when I open the app through it, I just could not able to find anything in docs the code I am using to listen for link clicks is as follows void Start() DynamicLinks.DynamicLinkReceived OnDynamicLink Display the dynamic link received by the application. private void OnDynamicLink(object sender, EventArgs args) var dynamicLinkEventArgs args as ReceivedDynamicLinkEventArgs Debug.LogFormat("Received dynamic link 0 ", dynamicLinkEventArgs.ReceivedDynamicLink.Url.OriginalString) Above line gets me the original base link, But I want the link which I clicked |
0 | I have problem understand instantiating new objects in Unity at runtime , help please ) Hi again you fine folks. So I'm making a driving game and there is going to be some cows in the road you have to dodge. Currently I've laid 3 spawnpoints in the form of flat cubes, with the following script attached to each of them. (The reason I am manually laying the spawn points out myself is that the road is very windy, and has steep hills etc , and I was struggling to find a way to prodecurally place them on the road exactly at correct height etc. Here is the code im using for these spawn points. For some reason I am getting all 3 cows spawn on the first spawn point, instead of just one. I haven't driven the car thru to the other 2 spawn points, id guess there'd be 3 cows at each of them. (I have to actually build to my phone to get that far due to the controls being for mobile not PC) public class CowSpawn MonoBehaviour public GameObject bullPrefab public float spawnChance bool willSpawn false private GameObject bull Use this for initialization void Start() if (Random.value lt spawnChance) willSpawn true bull (GameObject)Instantiate(bullPrefab) bull.transform.position GetComponent lt GameObject gt ().transform.position Update is called once per frame void Update () |
0 | MissingComponentException when using Animator I followed some tutorials to add WASD movement to a character I managed to set up the animator thing and it works in the bottom right corner viewport. Next I tried adding the following C script with basic movements using System.Collections using System.Collections.Generic using UnityEngine public class AppleInput MonoBehaviour private Animator animator Start is called before the first frame update void Start() animator GetComponent lt Animator gt () Update is called once per frame void Update() animator.SetFloat( quot Horizontal quot , Input.GetAxis( quot Horizontal quot )) animator.SetFloat( quot Vertical quot , Input.GetAxis( quot Vertical quot )) Configured like so But then I get the error message MissingComponentException There is no 'Animator' attached to the quot action10Prob normalsDONEyet quot game object, but a script is trying to access it. You probably need to add a Animator to the game object quot action10Prob normalsDONEyet quot . Or your script needs to check if the component is attached before using it. How do I solve this error? |
0 | Combining meshes up to certain sizes I have the following spritesheet for types of terrain, with a transparent background. To draw it on my map, I thought of doing one mesh per type, and then combine them. This is the code. This gave me at first quite good results. But then I started trying maps of bigger dimensions, and after a certain point (I think it was 49x49), I got suddenly different results. As you can see, at this point only seems to render 2 kinds of terrain, and the others have disappeared completely. Size is the only factor that was changed. Materials, Sprites, settings... everything else is completely the same. Why could this be happening? |
0 | When load my unity scene on vmware windows virtual machine, the color lightening of the scene randomly changes? It turns pink Hi I have a unity scene doing all it is suppose to on mac but I had to load that scene on vmware windows virtual machine and when I did that, the color or the lighting of the scene was randomly changed and I don't know how to fix that. Any help will be highly appreciated. Thanks |
0 | Calculate the starting position of a turning aircraft with inertial force to make it stop at desired position and heading Continued from the answer here, I have some problem when the aircraft in my game has inertial forces after going forward and turning itself. To illustrate, from the following image (https imgur.com a Xvqu2A7) the aircraft is moving from the point A gt B gt C' gt D. I planned to maneuver the aircraft from the point C' which is the point that would make the aircraft stop at the point D after turning with its full performance (using minimum turning radius). The question is how do I calculate the position of the point C' to make the aircraft roughly stop at the point D with the desired position and heading (It is roughly since there is also an inertial force after stopping the aircraft's engine.)? Any suggestions and answers would be appreciated. |
0 | Animated Energy Combo Bar (Unity 4.6) How could I achieve the animated Combo bar effect used in Ski Safari Ski Safari Adventure time? Preferably with Unity 4.6 UI. General explanations also welcome! Links to videos showing the wanted effect https www.youtube.com watch?v CnfCkqiM890 t 4m46s and https www.youtube.com watch?v aqj61liRJ74 t 7m00s |
0 | Unity 2d coordinates I'm trying to get a 2d tilemap rendering but somethings not clicking with me about the 2d coordinates... Here's my basic tilemap class public class Map MonoBehaviour public Transform tilePrefab public int mapWidth public int mapHeight public Transform , map Use this for initialization void Start () map new Transform mapWidth, mapHeight for (int y 0 y lt mapHeight y ) for (int x 0 x lt mapWidth x ) Transform tile Instantiate(tilePrefab, new Vector3 (x, y, 0), Quaternion.identity) as Transform tile.parent transform map x, y tile But this is rendering the tilemap from the origin I want that tilemap to be dynamically centered on the camera like What I can't seem to work out is how to dynamically work out the coordinates to move that tilemap so that it's centered in the camera after it has been created? Any additional help, or pointers to some decent resources would be much appreciated, cheers. |
0 | Object not Augmenting on small marker I am new to Augmented reality. I am developing a jewellery try on app with vuforia using unty3D editor. What I want is to augment a ring on the marker. I download an image(attached bellow) and used it as my marker and it was working fine but when I resized the image in paint to fit to finger the marker stopped augmenting the object. any help. What should be the marker size or anything else which I am missing ? Please help me. |
0 | Coroutine only partially executing I have a Coroutine that I use to pull and spawn an enemy in my game. This coroutine works perfectly fine, with the exception of the very first call. I am fairly certain this is because I am probably loading something before it is ready, but I don't know enough to know where. This is my code (Note the Debug.Log entries). I have removed whatever I think is irrelevant code. EnemyHandler.cs public class EnemyHandler MonoBehaviour public int mob id IEnumerator LoadMob() Debug.Log("Checkpoint 1") WWWForm form new WWWForm() form.AddField("mob id",mob id) WWW www new WWW("my url here",form) yield return www Debug.Log(" Checkpoint 2 ") string webResults www.text.Split(' t') int returncode int.Parse(webResults 0 ) switch (returncode) case 0 Mob Loaded Successfully Mob variables are set here Debug.Log(" Checkpoint 3 ") break default Debug.Log("Error!") break public void CallMobLoad(int requested mob id) mob id requested mob id StartCoroutine(LoadMob()) Debug.Log("Coroutine called! Checkpoint 0") 2.GameManager.cs (This is my primary class) public class GameManager MonoBehaviour public GameObject spawnManager public static EnemyHandler thisenemy void Start() thisenemy spawnManager.AddComponent lt EnemyHandler gt () thisenemy.CallMobLoad(1) CallMobLoad is called once at Start, and every time a monster dies. It never works when called in Start(), but always works after that. Furthermore, the first call only calls the first 2 Debug.Logs "Checkpoint 0" and "Checkpoint 1", none of the other checkpoints are hit. Every subsequent call works correctly and hits all checkpoints. I really want to learn how why this happens, Any help is greatly appreciated! EDIT I have fixed this by turning Start into an IEnumerator, and adding a yield return to thisenemy.CallMobLoad(mobloadtemp) Still not sure if this is the best way to do this, so please do advise. |
0 | Zoom Camera from C in Unity I am creating endless running game. I want to zoom camera when player dies to the player. I have tried using camera.FieldOfView, but it does not work. Is there another way to zoom In camera to the object when particular condition becomes true. Thanks in advance. |
0 | Should I slow down my animation with co routines or update the animation state? I want to gradually stop the car animation as it collides with another car gradually speed up the car animation as it exits the collider I have two ways to achieve this. Update Co routine For co routine I used this piece of code IEnumerator IncreaseSpeedGradually1(AnimationControlSpeed lastGOHitScript) stop if decrease speed in progress StopCoroutine("DecreaseSpeedGradually") float decrementValue ((lastHitVehicleSpeed 2) 2) while (lastGOHitScript.Speed lt lastHitVehicleSpeed) lastGOHitScript.Speed decrementValue Time.deltaTime yield return 0 setting speed to the last speed lastGOHitScript.Speed lastGOHitScript.iniSpeeed and for the update based approach I just added this criteria to the method if (carAnimState carAnimationState.starting) carAnimState carAnimationState.running if (carAnimState carAnimationState.stoping) carAnimState carAnimationState.running These are the two ways I thought about using. I wanted to ask which is right way to do this job? To slow down animation speed and hence get my objective? I guess co routines can be problematic later in my game. Are there performance concerns for using one of the approaches? |
0 | Unity multiplayer (online) How to connect to a 'Client Host' without using Unity Paid Service I'm slightly annoyed with the official Unity guides here, because I have been following through some, and they have indeed helped me create a local network mulitplayer situation. However, at no point did they mention that using these methods (ie. UnityEngine.Networking NetworkManager NetworkManagerHUD NetworkIdentity) will require me to pay Unity for Pro, and a monthly server usage fee, if I wanted to play via internet. I've set up my own Rust server in the past and it was very simple. I just installed a Rust Dedicated Server on my desktop PC (which I have fibre internet connection) and ran the server. I could then have 20 people playing with me and we didn't notice any slow down or lag or any problems with it. (Rust is made in Unity I believe) I've tried searching lots on this matter, and there are many many differing voices of how I can do this (many out of date, and many explicitly stating its impossible without hiring a server) I disagree, and think I can make my desktop run the server, BUT I haven't a clue if I'm correct and also how I would be able to make it. Unity docs seem to be trying to hide this solution if it exists (perhaps I'm being paranoid). I have the NetworkManagerHUD all working and can play locally as I say. So, it appears that the NetworkManager allows a user to start my game in 'Client host' mode, it also allows another instance elsewhere to click "Connect Client" and has a space for IP address. Would I even need a dedicated server if a player has clicked to start as 'Client Host'? assuming I don't, how can I then connect to this host from another machine? Does typing the client hosts external IP allow this? Sadly, I don't have anybody to help me test this right now. If a dedicated server version is the preferable way to go, could anybody please help me in the direction of how to start creating this? For info The game at this stage is a very simple FPS shooter. The NetworkManager is assigning the 'isLocalPlayer' flag correctly to one instance of the player object. I see in the Editor Hierarchy that it is handling the game overall and has two player objects once I have logged in with two instances locally. |
0 | Move rigidbody using WASD keys but rotate it based on camera mouse movement I am very new to unity and my scripts are based on some scripts found on the web. I want to make a first person view so the camera is attached to my rigidbodys head. Then i want to move my rigidbody based on keyboard input (wasd) and rotate it using the mouse movement. Until now, i used the following code for moving my rigidbody void Update() calculate rigidbody movement movement new Vector3( Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized calculate mouse look to rotate the rigidbody mouseDelta new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")) mouseDelta Vector2.Scale(mouseDelta, new Vector2(sensitivity smoothing, sensitivity smoothing)) smoothV.x Mathf.Lerp(smoothV.x, mouseDelta.x, 1f smoothing) smoothV.y Mathf.Lerp(smoothV.y, mouseDelta.y, 1f smoothing) mouseLook smoothV void FixedUpdate() apply rigidbody movement from Update() transform.Translate( movement moveSpeed Time.deltaTime ) apply rigidbody rotation from Update() transform.localRotation Quaternion.AngleAxis(mouseLook.x, transform.up) apply camera rotation from Update() Camera.main.transform.localRotation Quaternion.AngleAxis( mouseLook.y, Vector3.right) I learned today that i dont have to move a rigidbody's transform but now i am totally confused and it seems i have to restart my whole (first!) project. So when i use MovePosition and MoveRotation, how do i rotate it based on the camera perspective mouse movement? I think the movement Vector is ok so i can simply rewrite the FixedUpdate to something like rigidbody.MovePosition(movement speed Time.deltaTime) but i am totally stuck on how to apply the camera rotation to my rigidbody to use it like void FixedUpdate() move the rigidbody rigidbody.MovePosition(movement moveSpeed Time.deltaTime) rotate the camera camera.transform.localRotation Quaternion.AngleAxis( mouseLook.y, Vector3.right) but how can i rotate the rigidbody based on the cameras rotation??? rigidbody.MoveRotation(?????) I hope its clear what i want, thank you! |
0 | Making a 2d sprite based game in Unity? I'm looking at developing a 2D sprite based platformer. Usually I make games in Gamemaker, because I find it very easy to use. I have never used Unity before but have heard a lot of good things. So, just wondering whether you can easily make this type of game in Unity? |
0 | Jagged Edges Even With Anti Aliasing 8x Multi Sampling I have an interior scene where I have imported a model for the apartment and many of the interior objects such as lamps, windows, etc. Unfortunately I have a lot of jagged edges on almost all the objects in my scene even on Fantastic Quality settings with Anti Aliasing pushed to its maximum. What else can I do to reduce the jaggies seen here Here are my quality settings And here are my model import settings |
0 | Faking a 3D object to decrease number of polygons I'm making a game in unity and I'm building a fence in blender but I want it to be as low poly as possible. My original design was too high poly so I thought, what if I could simply use a cube with some cleverly arranged textures. Like so You can see the edges are all looking good but the inside sections are not, i.e there's nothing there... so does anyone know if it's possible to fake those faces that would make it look as though it were a complete mesh. Here's what I'm tring to achieve |
0 | Name doesn't exist in current context in Unity I'm currently making a collectible heart in unity, the kind that updates your health bar when you collide with it, and I made two scripts This one is called 'healthmonitor' using System.Collections using System.Collections.Generic using UnityEngine public class healthmonitor MonoBehaviour public static int HealthValue public int InternalHealth public GameObject Heart1 public GameObject Heart2 public GameObject Heart3 void Start () HealthValue 1 void Update () InternalHealth HealthValue if (HealthValue 1) Heart1.SetActive (true) if (HealthValue 2) Heart2.SetActive (true) if (HealthValue 3) Heart3.SetActive (true) This one is called 'hearstscript' using System.Collections using System.Collections.Generic using UnityEngine public class heartscript MonoBehaviour public int Rotatespeed public AudioSource CollectSound public GameObject thisheart void Update () Rotatespeed 10 transform.Rotate(0, Rotatespeed, 0, Space.World) void OnTriggerEnter () CollectSound.Play () HealthMonitor.HealthValue 1 thisheart.SetActive (false) Here is a picture of my UI I made an empty game object and named it HealthMonitor and applied the healthmonitor script to it. Here's a picture of the inspector panel The problem is that with heartscript I get the following error Name "HealthMonitor" doesn't exist in current context. I believe it relates to this line HealthMonitor.HealthValue 1 P.S. I am trying to refer to the empty game object, not the script. |
0 | How can I prevent a component from handling collision events? In Unity, I can set the enabled flag of a component to false, and this prevents Unity from running the Update method of the component. However, Unity still runs other methods of the component, such as OnTriggerEnter2D. Is there a way to completely disable a component (without removing it), such that it does not get any events at all? Of course I can manually add a flag to my component, and check this flag from within the event handlers, but I would like to know if there is a built in solution. |
0 | Unity How many Raycasts per Sphere Collider? I understand that a simple sphere collider in Unity is a raycast in all directions with a certain length. How many Raycast events does a sphere collider trigger? At what degree increments are the rays cast? |
0 | Make CharacterControllers in Unity not collide with each other I'm trying to spawn a number of CharacterControllers and have them move around an area, but they keep getting stuck on each other. Is there a way to make them pass through each other while still respecting the terrain's obstructions? |
0 | vSync for gameplay in monitor and VR headset in Unity not being consistent? Following my previous question, I'm building a project, my monitor refresh rate is 60Hz, and in my project I have set my vSync value into 2 so I can get 30fps. QualitySettings.vSyncCount 2 It worked perfectly, I built my project and I got stable 30fps. But after I plugged my VR headset (HTC Vive) to play the same project, my framerate drops and only reach around 10fps. Why is this happening ? FYI, Vive's refresh rate is 90Hz. In this case, will vSync adjust itself to my monitor or Vive's refresh rate ? |
0 | UnityEngine.PlayerPrefs corrupts string? I need to use PlayerPrefs to store arrays of bytes for my game. For some reason, the string I save with PlayerPrefs doesn't come out with the same length. I.e. byte TestArray new byte 256 for (byte i 0 i lt 256 i ) TestArray i i char charBuffer new char TestArray.Length for (int i 0 i lt TestArray.Length i ) charBuffer i (char)TestArray i PlayerPrefs.SetString ("Storage", new string(charBuffer)) PlayerPrefs.Save () Debug.Log (new String(charBuffer).Length) Debug.Log (PlayerPrefs.GetString ("Storage").Length) Log 256 5 Is this possibly an issue with encoding? How do I fix it? |
0 | Applying a getButtonDown getButtonUp on a GUI button for touch input I have a GUI interface with a button for the character's attack, however I want to implement a defense button where the user can hold the button down to block incoming attacks, when the user stops touching the button then the player goes back to idle. Right now I have the attack button working correctly, whenever the button gets pressed, it triggers a method where the animator gets called and performs the action. I want to implement the getButtonDown("") and getButtonUp("") used commonly with the keyboard input. How can i implement such fucntions to a GUI button? |
0 | Trouble with LineRenderer with orthographic camera in Unity When a weapon is fired, I want to draw a line for the bullet's trajectory. I am using a LineRenderer to draw the trajectory with the code below void FixedUpdate () timer Time.deltaTime if (Input.GetButton ("Fire1") amp amp timer gt timeBetweenBullets amp amp Time.timeScale ! 0) Shoot () if (timer gt timeBetweenBullets effectsDisplayTime) DisableEffects () void DisableEffects () gunLine.enabled false void Shoot () timer 0f Set first point gunLine.SetPosition (0, transform.position) shootRay.origin transform.position shootRay.direction transform.forward gunLine.SetPosition (1, shootRay.origin shootRay.direction range) I am using an orthographic camera in the scene. The line will show up but at certain rotations the line will partially render or be completely hidden. Oddly, the line will always render in the scene view the problem only exists in the game view. Has anyone had this issue? |
0 | What information should be stored in a database for a MOBA game? I'm wondering what information should be stored in a database when developing a MOBA like game? For example the current item a unit has, how much gold a player has, etc... |
0 | How do I have multiple audio sources on a single object in Unity? I have an audio system set up wherein I have loaded all my audio clips centrally and play them on demand by passing the requesting audioSource into the sound manager. However, there is a complication wherein if I want to overlay multiple looping sounds, I need to have multiple audio sources on an object, which is fine , so I created two in my script instantiated them and played my clips on them and then the world went crazy. For some reason, when I create two audio Sources in an object only the latest one is ever used, even if I explicitly keep objects separated, playing a clip on one or the other plays the clip on the last one that was created, furthermore, either this last one is not created in the right place or somehow messes with the rolloff rules because I can hear it all across my level, havign just one source works fine, but putting a second one on it causes shit to go batshit insane. Does anyone know the reason solution for this ? Some pseudocode guardSoundsSource (AudioSource)gameObject.AddComponent("AudioSource") guardSoundsSource.name "Guard Sounds source" Setup this source guardThrusterSource (AudioSource)gameObject.AddComponent("AudioSource") guardThrusterSource.name "Guard Thruster Source" setup this source play using custom Sound manager soundMan.soundMgr.playOnSource(guardSoundsSource,"Guard Idle loop" ,true,GameManager.Manager.PlayerType) this method prints out the name of the source the sound was to be played on and it always shows "Guard Thruster Source" even on the "Guard Idle loop" even though I clearly told it to use "Guard Sounds source" |
0 | How to make it two seconds for Time.time? var targetscript Diamond var red Color var orange Color function Start () gameObject.camera.backgroundColor red function Update () if (targetscript.score gt 4) gameObject.camera.backgroundColor Color.Lerp(red, orange, Time.time) So right now, if the score is larger than 4 then it would change the camera background color to orange with lerp. But its too quick. I read on the internet that Time.time is 1 second. What is the alternative way but for 2 or 3 seconds? I tried this http answers.unity3d.com questions 328891 controlling duration of colorlerp in seconds.html I tried the code for the voted answer but it didn't work. It still lerps through quickly. Does anyone have any ideas? Thanks |
0 | How to achieve a dynamic soft see through hole effect in a wall with shaders? I'm looking for a way to create a dynamic soft see through hole effect for room walls. I know a few ways how to do it (for example multitexturing with second layer being the hole mask in screenspace), but all involve rendering walls with blending on which is too expensive for the mobile project I'm working on. Is there any way to do this without using blending on the whole geometry (the hole can appear in any place on any wall). Please see the attached image for a better illustration of the effect Also, I'm very open to any links to papers tutorials that might not be solving the exact problem but doing something close that might get me on the right tracks. Thank you! |
0 | Moving texture according to position in shader Divinity Original Sin have beautiful particle effect , When I move around game I see galaxy through particle that move according to my position.how can I make like it? you can see this effect here https youtu.be 4fIpQZ2sIAY |
0 | Unity Shadow shows on my Android device but NOT my Windows Mobile device Unity version 2017.1.1f1 Problem I'm using Directional Light. Shadow is not showing in my Windows Mobile device (Lumia 640 XL), but works fine when I run the exact same UWP project as PC (Local Machine) as well as Android. Attempted solutions 1) Quality Setting I even removed the rest of levels and left only 1 level of quality. 2) Both soft and hard shadows, 10 Shadow distance, Stable Fit of shadow projection, very high resolution, low resolution, No Cascade. 3) Tried realtime and mixed light mode. any idea? Thanks in advance for read my question. Screenshots Windows 10 Mobile (Lumia 640 XL) Android (Redmi Note 3) |
0 | Storing a List to PlayerPrefs Not Working I have a test database of 37 records and I have stored each column into a list and I am storing each record into PlayerPrefs. void storeStarData() Code to store star data in PlayerPrefs... PlayerPrefs.SetInt("totStars", NumOfStars) int i 0 while (i lt NumOfStars) PlayerPrefs.SetString(("starID" i), StarIDID i ) PlayerPrefs.SetString(("starName" i), StarName i ) PlayerPrefs.SetString(("starHIP" i), StarIDHIP i ) PlayerPrefs.SetString(("starHD" i), StarIDHD i ) PlayerPrefs.SetString(("starHR" i), StarIDHR i ) PlayerPrefs.SetString(("starGL" i), StarIDGL i ) PlayerPrefs.SetString(("starBF" i), StarIDBF i ) PlayerPrefs.SetString(("starRA" i), StarRA i ) PlayerPrefs.SetString(("starDec" i), StarDec i ) PlayerPrefs.SetString(("starMag" i), StarMag i ) PlayerPrefs.SetString(("starCI" i), StarCI i ) PlayerPrefs.Save() i PlayerPrefs.Save() Debug.Log(PlayerPrefs.GetString("StarID0")) Debug.Log(PlayerPrefs.GetString("StarID1")) Debug.Log(PlayerPrefs.GetString("StarID2")) Debug.Log(PlayerPrefs.GetString("StarID3")) startSimulation() First record in list StarIDID 0 1 Last record in list StarIDID 36 37 At the end, I've added 4 Debug.Logs that return the IDs of the first 4 stars. For some reason, only the first StarIDID is being stored into Player prefs. Here is the output of the Debug.Log As you can see, StarID0 is the only PlayerPref with a valid value stored, the other ones don't have any values stored in them for some reason. Is there a way to fix this and am I doing anything wrong here? |
0 | How do I smooth out the edges at the end of the threshold on noise? I'm making a terrain generator for a game and I need it to smooth down to a float, I've tried a bunch of different things with lerping but I can't figure it out. I need to stop this from happening by smoothing the height down to 1 once it gets to the edges. public LevelManager level public float noise public float oceanNoise public float mountainNoise public Transform water public Transform land public void Start() level FindObjectOfType lt LevelManager gt () public void Update() float landNoise noise oceanNoise noise SimplexNoise.Noise(transform.position.x level.deatalscale, transform.position.z level.deatalscale) oceanNoise SimplexNoise.Noise(transform.position.x level.oceanDetailScale, transform.position.z level.oceanDetailScale) mountainNoise SimplexNoise.Noise(transform.position.x level.mountainDetailScale, transform.position.z level.mountainDetailScale) if (noise gt level.thresh) land.gameObject.SetActive(true) water.gameObject.SetActive(false) else land.gameObject.SetActive(false) water.gameObject.SetActive(true) if (oceanNoise lt level.oceanHhresh) land.gameObject.SetActive(false) water.gameObject.SetActive(true) if (oceanNoise lt level.oceanHhresh) land.gameObject.SetActive(false) water.gameObject.SetActive(true) land.transform.localScale new Vector3(level.planeScale, Mathf.Lerp(noise level.height,1,noise) level.height level.addHeight, level.planeScale) if (level.landpos.Contains(transform.position)) Destroy(gameObject) This script goes on the terrain chunk and it uses its position to find value in noise, the level manager just holds a few settings. Any help is appreciated, thanks in advance. |
0 | Basic Moving Anim Script Unity CSharp So, I got this to do the anims for my sprite in Unity 2d... using UnityEngine using System.Collections public class Move MonoBehaviour public float Speed 2 Animator anim Use this for initialization void Start () anim GetComponent lt Animator gt () void FixedUpdate () rigidbody2D.velocity new Vector2(Input.GetAxis("Horizontal") Speed, 0) anim.SetFloat("HorizontalSpeed", Mathf.Abs(rigidbody2D.velocity.x)) if(transform.localScale.x gt 0 amp amp rigidbody2D.velocity.x lt 0) transform.localScale new Vector3( 1, 1, 1) if(transform.localScale.x lt 0 amp amp rigidbody2D.velocity.x gt 0) transform.localScale new Vector3(1, 1, 1) That works fine... then I add the script so he can move up and down. (the previous was moving left right) using UnityEngine using System.Collections public class UpMove MonoBehaviour public float VerticalSpeed 2 Animator anim Use this for initialization void Start () anim GetComponent lt Animator gt () void FixedUpdate () rigidbody2D.velocity new Vector2(Input.GetAxis("Vertical") VerticalSpeed, 0) anim.SetFloat("VerticalSpeed", Mathf.Abs(rigidbody2D.velocity.y)) Welll.. The second script doesn't do anything. I've been working at this (rookie noobness) for around an hour now.. so pls pls pls. |
0 | Unity higher Z position tiles rendered underneath When placing tiles in an isometric tile map in Unity, I try to place blocks on top using the quot Z Position Value quot However it looks like higher Z position values get rendered underneath. In this picture, the green cubes have a z position of 0 whereas the yellow cubes have a z position of 1. I want the yellow cubes to render on top, but they are underneath. I'm using an Isometric Z as Y tile map and have the Transparency Sort Axis set to (x 0,y 1,z 0.26). |
0 | How do I scale my spell target indicator to match the radius of OverlapSphere I have a spell system in which some spells have an Area of Effect. To get the targets I use Physics.OverlapSphere. I show the player an indication of the spell's radius by spawning a Unity plane primitive at the target position and scaling it to match the radius of the spell. How would I scale my spell target indicator visual to correctly match the radius of OverlapSphere? I have tried setting the scale of the plane's X,Y,Z to radius 2, but this does not seem to align with the overlap sphere radius. data.indicatorInstance.transform.DOScale(data.parent.radius 2, 0.5f) And just for completeness sake, below is the OverlapSphere call. Physics.OverlapSphere(targetPosition, data.parent.radius) |
0 | Unity 2d overlapCircle melee combat issue I have an issue with my overlapCircle melee combat in the game. I'm not good at such things, so I just copied that code from some YouTube tutorial. But the thing is that if the enemy is behind the collider, I can still damage and kill him. And I don't want this. Is there a solution to this problem except recreating the melee combat system from the ground up? Maybe changing circle radius when close to collider?... Here's a video clip that may help show the situation. void Attack() Collider2D hitEnemies Physics2D.OverlapCircleAll(attackPoint.position, attackRange, whatIsEnemy) foreach (Collider2D enemy in hitEnemies) Debug.Log( quot Melee hit quot enemy.name) if (enemy is BoxCollider2D) CinemachineShake.Instance.ShakeCamera(3f, 0.2f) SoundManager.PlaySound( quot Knife kill quot ) if (enemy.tag quot Melee enemy quot ) enemy.GetComponent lt enemy melee gt ().TakeDamage(attackDamage) else if (enemy.tag quot Gun enemy quot ) enemy.GetComponent lt enemy gun gt ().TakeDamage(attackDamage) animator.SetTrigger( quot Melee attack quot ) animator.SetBool( quot IsCrouching quot , false) animator.SetBool( quot IsJumping quot , false) |
0 | Draw rectangles on Cube and remove I have 3d object as Wall ( Cube with texture and width and height large ) with some texture and attached c ( Unity 5.3.2 ) script to that wall. I want to programmatically draw rectangles on that Wall with green semitransparent color and after 5 seconds remove them. I am new to Unity and found OnGui but it is not drawing in 3d space but in front of screen. How to achieve this to draw and remove rectangles on Wall ? |
0 | How do I make my prefabs spawn behind the UI? I'm making a game where three characters spawn in specific locations. I made three gameobjects called stations so I could take the transform positions and spawn the three caracters there. And I have a UI element that is supposed to stay in front of everything. But the problem is that when I hit play, the three characters spawn in front of the UI element. I already checked the positions related to the camera but it doesn't seem to be it. Does anyone know how to help me? |
0 | convert clock input into 24 hour format I have stuck in a logical problem I have a third party package of DayNight. It takes hours input(24 hour format) to show dayNight effects in scene My code is to transform 12 hours clock cycle into 24 hours is if (todsky.Cycle.Hour gt 0 amp amp todsky.Cycle.Hour lt 11.97) Debug.LogError("1st") var degree 360 hourniddle.transform.eulerAngles.z var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes ConvertMinutesToHours(degreeToMintues) else if (todsky.Cycle.Hour gt 11.97 amp amp todsky.Cycle.Hour lt 23.97) Debug.LogError("2ndt") var degree 360 hourniddle.transform.eulerAngles.z as rotation is anti clock getting rever degree var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes var MintuestTo24HoursMintueCoverstion 720 degreeToMintues add 720 mintues into current minute in order to get 24 hour format ConvertMinutesToHours(MintuestTo24HoursMintueCoverstion) void ConvertMinutesToHours(float mintues) result TimeSpan.FromMinutes(mintues) Debug.LogWarning(result.Hours " " result.TotalHours " " result.Minutes " " result.TotalMinutes) todsky.Cycle.Hour (float) result.TotalHours Debug.LogWarning("setted hours " todsky.Cycle.Hour) But it is not working correctly . have made a clock GUI(360 degree) and as you know it only show 12 digits format not 24. I am getting clock needle movement which can be change through mouse drag. Needle z position up to 320 degree which means one degree is equal to 2 minutes and i am taking it as input from GUI. I write below code to integrate my clock needle with my DayNight package in order to integrate GUI with package and passing hour parameter into the package but it not working correctly. Problem is that else condition is skipping. |
0 | Remove or skip splash screen from Unity Free Personal game binary for modding How can I modify a Unity game (Windows) binary to skip the 5 second Unity logo splash screen? I know how to mod game code using dnspy to modify Assembly CSharp.dll. I'm able to find isShowingSplashScreen but that appears to be irrelevant. I'm at a loss whether I can find the splash screen code in any .dll or if one would have to edit the game .exe or some other file. Looking at the game .exe in HxD (hex editor), I see multiple occurrences of unity SplashScreen but have no idea whether I can use this for anything. Background I'm modding a Unity game and I am not very good at it. I have to try a lot and start the game a lot. This means each time I test something, I lose five seconds because the game was made with the free Unity version. As a player I made no commitment to the Unity ToS. I also have no intent to distribute a modded file that removes the splash screen. However, I want to remove it during development. I am not asking how to remove the splash screen while building the game. I am not developing in Unity, I am modding a game made in Unity and I'm trying to streamline the process. I did see Unity remove logo in splash screen, Alternatives to remove Unity splash screen after developing a game with the free version?, Can I legally remove the default Unity splash screen by removing it from the APK?. They revolve around the question of removing the splash screen with intent to distribute, which is not the topic here. I had hesitations about asking this question, due to the answer being useful to developers willing to violate the ToS. However it seems on topic and legal. I would also argue that the solution to my problem is probably going to be too much effort for active game dev projects to bother using it (having to repeat the steps for each new update) and that quot bad apple quot devs would rather use pirated versions of Unity Pro. |
0 | Unity3d select empty gameobjects in scene I have a pathing system that I am creating in Unity. When you add nodes to denote the path, I create a empty GameObject and render it in OnGUI as a square. The problem that I have is clicking on the object in the scene view. I am trying to figure out what would be the best way to click the Node, so that I can move and rotate the Node. I had some ideas, like Creating a Cube or some other GameObject with a mesh, and change the layer to Node. Then make the camera cull out the Node layer. Only in editor mode, create a temp asset and delete it before runtime. Do a raycast and see what objects are near the click, then pick the closest one. I have a feeling that I am putting to much thought into it, and suggestions would be greatly appreciated!! |
0 | How does Unity Inspector handle values changing during play without any thread locks? First of all, I'm a Java coder. Usually, when you write a game, you run it on thread different than the UI one like pseudocode starts new Thread(new Runnable() Override public void run() while(someVolatileBoolean) input() physics() graphics() and then you declare some sort of listener for the input which usually works on application UI thread so you need to mark it as volatile, atomic or perform a basic synchro using the synchronized keyword (depending on the situation). Let's take a simple Unity script public class SomeMovementScript MonoBehaviour public Vector3 speed new Vector3(0.1f, 0, 0) void Update () this.transform.Translate(speed Time.deltaTime) If we then play the game, the object starts to move with speed 0.1f. Now, when the game is playing, we can change the speed variable through the inspector I thought from the UI coder point of view I'm changing a variable, which is being read each frame by the game thread. How does this happen, that I don't get some sort of ConcurrentModificationException if there's no visible synchronization at all. The variable is public, not being cached in any way. I know that this question should be asked on SO, but I thought that GD has more users specialized in Unity and it's mechanics. I came up with immutability. Variable is considered thread safe if it's state can't change. As components are immutable, and classes like Vector2 3 4 are immutable it would work. But... You can make your own class Serializable , mark their fields as public and the class is not thread safe but it is visible through the inspector. How does Unity Inspector perform these real time updates with all the classes you can think of? |
0 | Modifying an array of quaternions I have written the following function to inter change 2 specific elements of an array of quaternions private void ChangeRotations(Quaternion rotationsArray) Quaternion bone1Rot rotationsArray (int)Bone1ID Quaternion bone2Rot rotationsArray (int)Bone2ID Quaternion temp bone1Rot bone1Rot bone2Rot bone2Rot temp But when I use Debug.Log to see if this has taken effect, I realize that the 2 array elements are unchanged. What am I doing wrong here? |
0 | Unity C Invoke Function Freezes Program if(Input.GetKeyDown(KeyCode.G) amp amp ammo lt 9) ableS false while(ammo lt 9) Invoke( quot bulletplus quot , 0.5f) ableS true This is the main part I am having trouble with. Down there is ALL my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class gun MonoBehaviour Vector2 rotation new Vector2 (0, 0) public float rot 3 public Vector3 pos public Rigidbody Orb public Text ammoT public int ammo 10 bool ableS true void Update () Ammo if(ammo gt 7) ammoT.GetComponent lt Text gt ().color Color.green else if(ammo gt 4) ammoT.GetComponent lt Text gt ().color Color.yellow else ammoT.GetComponent lt Text gt ().color Color.red Rotation rotation.x Input.GetAxis ( quot Mouse Y quot ) rotation.x Mathf.Clamp(rotation.x, 70, 70) rotation.y Input.GetAxis( quot Mouse X quot ) transform.eulerAngles (Vector2)rotation rot pos new Vector3(transform.position.x, transform.position.y, transform.position.z) Shoot Choklats if(Input.GetMouseButtonDown(0) amp amp ammo gt 1 amp amp ableS) ammoT.text quot Ammo quot ammo.ToString() ammo 1 Rigidbody projectile Instantiate(Orb, pos, transform.rotation) projectile.velocity transform.forward 50f Reload if(Input.GetKeyDown(KeyCode.G) amp amp ammo lt 9) ableS false while(ammo lt 9) Invoke( quot bulletplus quot , 0.5f) ableS true void bulletplus() ammo 1 ammoT.text quot Ammo quot ammo.ToString() |
0 | Making object move in an angle I have a game with a beat em up perspective (think Final Fight, Streets of Rage) where movement is in X and Z. My movement logic consists of checking controller input of X axis for X movement and Y axis for Z movement. I use this logic to move enemy as well, using this method internal bool MoveTowardsPosition(Vector3 targetPosition) bool reachedPosition false bool reachedX false bool reachedZ false Determine x direction if (Mathf.Round(Mathf.Abs(targetPosition.x enemy.transform.position.x)) gt 0) if (targetPosition.x lt enemy.transform.position.x) Input.HorizontalMove 1 else Input.HorizontalMove 1 else reachedX true Determine z direction if (Mathf.Round(Mathf.Abs(targetPosition.z enemy.transform.position.z)) gt 0) if (targetPosition.z lt enemy.transform.position.z) Input.DepthMove 1 else Input.DepthMove 1 else reachedZ true if (reachedX amp amp reachedZ) reachedPosition true return reachedPosition So what happens here is that given a target position, I add to the HorizontalMove (X) and DepthMove (Z) until the enemy reaches the destination (these X and Z additions will be read on Update to do a transform.translate()). The enemy does move to the destination but in a unnatural path. So when Z is larger, it will reach the destination X first then traverse Z. So for example, X 2 and Z 5, it'll traverse with a path like this What I'm trying to do is for it to traverse a path like this I figured instead of adding fixed 1 1, I need to determine X and Z based on that angle but I'm lost on how to compute do it. Can you guys lend me a hand, please? |
0 | Rotate 3D object relative to the camera I really need the help of an expert. I'm trying to rotate an object in all 3 axes relative to the camera in response to the gamepad sticks. I have succeeded but with an unexpected error, depending on its orientation, the object can rotate in the opposite direction of the stick direction. For example, if the object is on its back, when I move the stick to the left the object rotates to the left. But, when the object is facing the camera, when I move the stick to the left the object rotates to the right. The same happens in all 3 axes, on each axis I have 180 degrees with the correct stick orientation and 180 degrees with inverted sticks. Also, both the camera and the object can freely move adding more complexity to this problem. I would like to find a way where the orientation of the rotation always follows the direction of the stick. This is solved with a minus sign applied to the angle according to the object orientation (relative to the camera) but I can't find out how. This is the code I'm using, it works fine except for the orientation problem. Can anyone find the solution to this problem? public void ObjectRotate(int dir, float angle) Object is defined elsewhere var rotate 360 Time.deltaTime angle var target Object.transform if(dir 1) target.RotateAround(target.transform.position, Camera.main.transform.right, rotate ) else if(dir 2) target.RotateAround(target.transform.position, Camera.main.transform.up, rotate) else if(dir 3) target.RotateAround(target.transform.position, Camera.main.transform.forward, rotate) |
0 | Why the plane is not black? I created a new material and changed the material colors to make it black R,G,B all value is 0 and A value is 255 The shader on the Plane is Legacy Shaders Transparent Diffuse But the Plane seems to be transparent. The main goal is put a plane in front of the camera the FPSCamera and then using a script to fade in out the alpha color. |
0 | Unity C Input Buffering So, I've got a fighting game with some pretty tight input windows, and I'd like to buffer the inputs for a few frames. Basically, if the fighter is in the neutral state, pressing attack should lead into an attack. It uses Input.GetButtonDown("attack") to get the button, and if it detects a press, transitions into attacking state. Now, let's suppose the fighter has just landed, and ends up hitting "attack" a few frames before the land animation ends and he transitions back into neutral. As of right now, nothing would happen, since he's not in the neutral state where the check is, and when he enters the state, the button press is no longer happening. Is there a way to store inputs for a few frames, so that I can read a button press a few frames back? So, instead of using Input.GetButtonDown("attack"), it'd be something like InputBuffer.KeyBuffered("attack",12) to see if the button was pressed within 12 frames? The example above is just a bit of a simplification, I know for the above situation I could just use GetButton instead of GetButtonDown, but for a fighting game, you can imagine that the necessary inputs to buffer would get significantly more complicated. |
0 | Rotate 3D object relative to the camera I really need the help of an expert. I'm trying to rotate an object in all 3 axes relative to the camera in response to the gamepad sticks. I have succeeded but with an unexpected error, depending on its orientation, the object can rotate in the opposite direction of the stick direction. For example, if the object is on its back, when I move the stick to the left the object rotates to the left. But, when the object is facing the camera, when I move the stick to the left the object rotates to the right. The same happens in all 3 axes, on each axis I have 180 degrees with the correct stick orientation and 180 degrees with inverted sticks. Also, both the camera and the object can freely move adding more complexity to this problem. I would like to find a way where the orientation of the rotation always follows the direction of the stick. This is solved with a minus sign applied to the angle according to the object orientation (relative to the camera) but I can't find out how. This is the code I'm using, it works fine except for the orientation problem. Can anyone find the solution to this problem? public void ObjectRotate(int dir, float angle) Object is defined elsewhere var rotate 360 Time.deltaTime angle var target Object.transform if(dir 1) target.RotateAround(target.transform.position, Camera.main.transform.right, rotate ) else if(dir 2) target.RotateAround(target.transform.position, Camera.main.transform.up, rotate) else if(dir 3) target.RotateAround(target.transform.position, Camera.main.transform.forward, rotate) |
0 | I installed Linux Build Support, but I need an archive to build, how can I get this? I m building a game for Mac, Windows and Linux, I builded the Windows and Mac game, but in Linux, says that need a x86 64 archive, like the image shows, what do I do? |
0 | Unity X axis back to front I'm using Unity 2018 and its really confusing me. I generate a plane mesh in code and when it comes to positioning (transform.position.x) it on the X axis I can't understand why moving it further to the right the X value decreases (into the negatives) and the X value increases to the left?? The Y axis works as expected, up increases the value (positive), down decreases (negative). The Z axis, away from camera negative and towards positive. (Just creating a basic 3D cube game object using the Unity Create tool, the same issue applies.) I need to figure if this is how Unity is set up now? Or I'm doing something wrong.. But I'm stuck on this!! create mesh code Mesh CreateMesh(float width, float height) Mesh m new Mesh() m.name "ScriptedMesh" m.vertices new Vector3 new Vector3(0, 0, 0.01f), new Vector3(width, 0, 0.01f), new Vector3(width, height, 0.01f), new Vector3(0, height, 0.01f) m.uv new Vector2 new Vector2 (0, 0), new Vector2 (0, 1), new Vector2(1, 1), new Vector2 (1, 0) m.triangles new int 0, 1, 2, 0, 2, 3 m.RecalculateNormals() return m build our first wall mesh obj var wallObj new GameObject("Wall " wallc.WallLengthCM " (" wallIndex ")") var wallMesh (MeshFilter)wallObj.AddComponent(typeof(MeshFilter)) wallMesh.mesh CreateMesh((float)wallc.WallLengthCM, (float)wallc.WallHeightCM) MeshRenderer wallRenderer wallObj.AddComponent(typeof(MeshRenderer)) as MeshRenderer wallRenderer.material ShedWallMat var wallMesh Instantiate( wallMesh, new Vector3 x 0, y ((float)wallc.WallHeightCM 2 wallIndex) vertSpace, z 0 , new Quaternion w 0, x 0, y 0, z 0 ) |
0 | Unlock levels using coins Unity I'm creating a game that has multiple levels. The first three levels are free but the others can be unlocked either using coins (collected during the game) or through IAP. For the coins, I'm using a binary formatter to store the number of coins. The reason I'm using BF is because it persits through all levels(so far this seems to work as the coin score is carried through to other levels). Here is code I have so far in the coinSystem public class CoinSystem MonoBehaviour public TextMeshProUGUI coinScoreText public int coinScore void Start() LoadScore() public void Save() coinScore coinScoreText.text coinScore.ToString() BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath quot TotalCoinScore.dat quot , FileMode.Create) CoinContainer coinContainer new CoinContainer() coinContainer.coinScore coinScore bf.Serialize(file, coinContainer) file.Close() public void LoadScore() if (File.Exists(Application.persistentDataPath quot TotalCoinScore.dat quot )) BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath quot TotalCoinScore.dat quot , FileMode.Open) CoinContainer coinContainer (CoinContainer)bf.Deserialize(file) file.Close() coinScore coinContainer.coinScore coinScoreText.text coinScore.ToString() Serializable public class CoinContainer public int coinScore This is code that I use to add to the coinScore. public class Player MonoBehaviour Rigidbody rb public CoinSystem cs public bool dead true void Start() rb GetComponent lt Rigidbody gt () . . . . void OnTriggerEnter(Collider col) if (!dead amp amp col.gameObject.tag quot Enemy quot ) die() if (!dead amp amp col.gameObject.tag quot Coin quot ) cs.Save() So now in the level select menu, I want to add a button that once clicked should enable the user to unlock a particluar level if he has enough coins. For example, if a level requires 500 coins and the user has 600, then on clicking this button the level is unlocked and the total coins now available are 100. And if the number of coins are less than what is required to unlock a level then the user should not be able to unlock that level. I'm not sure how to implement this. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.