_id
int64
0
49
text
stringlengths
71
4.19k
0
Trying to make a button in Unity which spawns a character each time it's clicked I have a simple 2D game, I want a UI button to respawn the character (if it's not already present). The first problem I encountered is that the button only works once. I can't go any further before I solve this, so for now it doesn't spawn anything, I just want it to print debug text every time it's clicked. It only does that once, unfortunately. How do I make it call the function each time I click it? using UnityEngine using System.Collections using UnityEngine.EventSystems public class Button Restart MonoBehaviour public Canvas Canvas void Awake() public void Restart() Debug.Log("Restart button was clicked") EventSystem.current.SetSelectedGameObject(null)
0
3D Menu Attached to an Object? So I'm gathering information for my project, and one of the things I want to achieve is to create a very sophisticated crafting system and weapon modification but I want the weapon customization to look in a specific manner. A very good reference would be Crysis weapon attachments system, where if you open it, your character tilts the weapon and there are few menus popping up, all attached to the weapon, so you can see the menus moving around as your weapon is moving (due to you breathing for example, or walking). Here is a quick image reference So 1st thing comes to my mind is, how in the name of god should I approach this? Pardon if this is quite easy thing to do, I'm just completely new to Unity. (I have solid C background so programming isn't the obstacle) Edit 1 To be precise, I'm wondering how to work out the positioning of the menus in relation to the weapon. So the menu is moving with the weapon and eventually even turn slightly to give that 3D'ish effect.
0
How do I program procedural generation with objects that must fit together in specific ways? I'm working on a game where I have to procedurally generate a large open room building. I'm using Unity, but I think this applies to any engine. The room is made up of different wall segments. What makes this difficult for me is the ends of the segments have to join with a similar end of another segment. There are 2 types of ends. Flat and angled. The purpose of the angled ends is to create an outside corner. Meaning for example a flat wall then turns into a hallway it would use angled ends to make the transition. The method I tried initially was to define each segment type and what the follow up modules could be. Meaning SegmentA can be followed by SegmentB, SegmentC, and SegmentD. Then I would randomly select which of those to add and place it, then move on and repeat. It works ok, but I feel like there is a better way to do it. It's pretty unwieldy and is kind of prone to bugs. I also run into issues trying to close the loop and return to the original segment.
0
How do I tell if an object is currently colliding with another object? I can't figure out how to tell if a GameObject is currently colliding with another in Unity. I've looked online and can't find any tutorials or answers that work. Also, what's the difference between a Collision and a Collider w.r.t. Unity? My dilemma I have a third person controller set up and want it to wall jump. I already have an isGrounded function, I just need to test if I'm hitting anything other than the floor. Otherwise I want it to wall jump backwards. I've already tried if (this.OnCollisionEnter) ... if (Collider.OnCollisionEnter) ... But it did not work. I now tried function OnCollisionStay() Debug.Log("Collision") I checked my logs, console and still can't find anything.
0
How to destroy a clone of an effect attached to an object? I want to use some particle effects into a bonus object that will be destroyed upon contact with the player object. This object as its name suggests will add a certain benefit for the player for a certain amount of time. I was following a tutorial on Youtube. The code from the Tutorial worked fine but there is one problem I was not able to solve the explosion will not be destroyed after the object is collided with player and after the script is triggered because it seems that it was cloned into the scene. The instantiation created a clone of the effect's prefab I referenced into the script. After looking into the internet, I tried to affect the instantiation of the effect into a variable called clone and then destroyed it after the bonus is over but the problem was still present. I researched and I really did not obtain any answer. bonus.cs using System.Collections using System.Collections.Generic using UnityEngine public class bonus MonoBehaviour public float multiplier 2.0f public GameObject pickup effect public float duration 10 private GameObject clone private void OnTriggerEnter(Collider other) if (other.CompareTag("Player")) StartCoroutine( pickup(other)) IEnumerator pickup(Collider player) Debug.Log("You picked a bonus!") spawn cool effect clone Instantiate(pickup effect, transform.position, transform.rotation) apply effect yo the player our.score value 10 player.transform.localScale multiplier GetComponent lt MeshRenderer gt ().enabled false GetComponent lt Collider gt ().enabled false wait x amount of seconds yield return new WaitForSeconds(duration) remove the effect from theplayer player.transform.localScale multiplier Destroy(gameObject) Destroy(clone,4f) I tried disabling the "loop" option in the effect's particle system options but it gave the same results. I disabled the "Play on Awake" option and the effect will not play at all. The script is added directly to the object that is a simple 3D cube with MeshCollider, Mesh Renderer and Box collider. The effect I used is a BigExplosionEffect taken from Unity Particle Pack 5.x from the Asset Store. I would like to know what is exactly wrong? Is it probably related to the effect itself rather than the script? Or is there a far better solution?
0
In Unity3D, try to load a png into a Texture2D in an Editor script and then run PackTextures, but they need Readable flag to be set I am trying to automatically create a texture atlas from a set of generated png files in an Editor script. The problem is that I can't seem to be able to load a png into a Texture3D without it being inaccessible by the PackTextures method. I have tried a few different ways to load the PNGs, such as Resources.LoadAssetAtPath(...), AssetDatabase.LoadAssetAtPath(...) and a few more. Since all of this is done in OnPostprocessAllAssets, I don't want to have to do any manual editing of the textures. I just want to be able to drop a PNG into a certain folder and get an updated atlas. Answers such as this seem to suggest manual editing. The actual error message is "Texture atlas needs textures to have Readable flag set!". So the question is, is it possible to do this kind of post processing in Unity3D? Is there any way to import a PNG into a Texture2D with the Readable flag set, without having to manually change it?
0
Understanding Physics Materials I have been reading the documentation about Physics materials, and it really seems very incomplete to me. When I try to work with it, I get so many questions... Maybe can someone help me wrap my head around how it works? Why is there a physics material field for the Rigidbody2D, but also another in the BoxCollider2D? Do they work differently, depending on which you put it? What happens if you put different materials, one on the RB and one in the collider with different settings? If a player is standing in a platform, and you want it to bounce, or slide... do you set that on the player? Or in the platform? Update As suggested in the comments, I did some experimenting and this is what I saw When I put contradicting materials in the RigidBody2D and the Collider2D, the one in the collider seems to take precedence. Not sure what is the purpose of the one in the Rigidbody. If both are the same, well, they just behave like one of them alone. The value isn't added
0
Mesh Path reduction to simulate traveled path to target I generate that kind of mesh during runtime to display the path to follow to a target (think at something like the path your GPS shows you when you are travelling) I need to reduce the displayed path going from one end to the other to simulate the travel the player did. What can I do to achieve such effect? I can think about vertex modifications at runtime directly from a Monobehaviour class, or a shader(?). Are there any other (smarter?) moves to do here? Is Vertex modification the wiser choice for that kind of case? Thanks.
0
Unity multiple servers for rooms I have an FPS game that I'd like to make multiplayer. It would need to support multiple matches at once with about 10 players in each. However I want physics to be server authoritative so that means running a Unity instance. How do I have multiple Unity processes running on a server, creating destroy them as needed, having players connect to the instance they need, and so on? How does this vary between uNet Sockets LLAPI Photon Bolt etc? There just seems to be an atrocious lack of information on Unity networking and when people ask online there's almost never any answer, or it's too vague to be useful.
0
Unity White outline around seams in my character, make it stop! so once upon a time I made a really cool character for my game project and he looked great. Then at some unspecific point in time, my character's UV seams got these awful white outlines around them I assumed the problem was that during some texture revision, I didn't paint past the island seams, so I compared the texture file with an image of the UV output, but in fact I did paint past the seams, so that isn't the problem. I have heard that this may have something to do with antialiasing, but I don't want to turn that off if I can fix the problem another way. Also, notice that the enemy character in the above gif does not suffer from the same problem. What could be causing this? How can I fix it?
0
Split a region into arrays based on point region I have an array of points forming a grid. I want to split this array into multiple arrays that each contain a region of point. Let's say each point as a value like on this image The points having the same value and being connected would go into the same array. If it was only an array of all the 8 or all the 7, it wou d be easy, but in thsi case I need the arrays to contain connected equal values. For example, the purple region of 1 would make an array, the 8 region on the left would make an array and the one on the right too, but a different one. I just don't know how to use a loop to navigate in the grid and affect each point to an array based on they relation with other points of the same value. As this is the objective, think of the values as biome that I want to assign to an array.
0
Make one object rotate to face another object in 2D In my 2D project, I have an object that is sometimes above or below another object. Once the primary object comes in close proximity with the secondary object, I want the object to rotate on the z axis so that the front of the primary object is facing the secondary object. (Here, following Unity's default setup, the z axis is the axis pointing into the screen)
0
How to Fill the Gap Between Camera Clip Plane And Skybox? I'm talking about the brown greyish area i marked with blue. How can i fill it with something that does fit the environment? I'm looking for a solution like this plugin.
0
Unity Shadergraph to CPU code? I read that you in theory can get vertex offsets from GPU shader in CPU by transpiling the shader to CPU callable code or creating a compute shader that calls the shader code (are there more ways?). I am wondering how one should approach this if one wants to use a shader from shadergraph. Can I get the same noise textures on CPU as on the nodes in shadergraph (GPU) for example? They can be important in driving the result. I think it is possible to export as hlsl so maybe transpiling can be done automatically.
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
How to play and pause animation I want to make play and pause buttons to play and pause sound and also I want it to play and pause animation ,how should I do that? function public void TogglePlay() if (audio.isPlaying) audio.Pause() else audio.Play()
0
Camera rotation according to target direction I am facing issue when camera is following to my target and target rotates to 90 degree or 90 degree than camera is not rotating.i want smooth rotation according to target when target is change the direction of movement.please help me if you can..thanks in advance.
0
How to make (or where to get) a half sphere mesh that textures properly? I'm making a game in Unity that involves lots of spheres. Said spheres will have lighting applied to them, but will also be viewed from only one camera angle. Right now, the full spheres look something like this when textured, normal mapped, and lit This is correct. The spheres in my game will only be seen head on, thus I only need to render their top halves. However, if I use the same material on only half a sphere (with a lower resolution, mind you), I get something like this (It's not the exact same material, but it's close enough, and shows the same problem.) This is incorrect. The weird part is I only encounter this issue in compiled builds of the game in the editor, the hemisphere is textured exactly as I expect. At the request of a commentator, here is one of the textures I'm using I'm also using it as a normal map. My question is thus how can I make (or where can I find) a hemisphere that can be properly textured, and why does my current hemisphere mesh only render properly in the Unity editor?
0
Should I use Coroutines to change variables in inspector smoothly? I want to change the aperture of the depth of field in the camera smoothly by using Mathf.SmoothDamp and a Coroutine, however, since I'm new to game development, I don't know if this is the right way to do it. Any suggestions? Code using System.Collections using UnityEngine using UnityEngine.UI using UnityStandardAssets.ImageEffects public class GameStartController MonoBehaviour public Button startButton public GameObject cubeSpawner Use this for initialization private void Start() startButton startButton.GetComponent lt Button gt () public void StartGame() EnableCubeSpawner() SpawnStartingCubes() HideStartMenu() StartCoroutine("FocusCamera") PlayBackgroundMusic() Enables the cube spawner, so it can start spawning cubes private void EnableCubeSpawner() cubeSpawner.SetActive(true) private void SpawnStartingCubes() cubeSpawner.GetComponent lt CubeSpawner gt ().GenerateStartingCubes() private void PlayBackgroundMusic() var audio GameObject.FindWithTag("Audio").GetComponent lt AudioController gt () audio.PlayBackgroundMusic() private void HideStartMenu() startButton.transform.parent.GetComponent lt CanvasGroup gt ().interactable false startButton.transform.parent.GetComponent lt CanvasGroup gt ().alpha 0f private IEnumerator FocusCamera() var camera GameObject.FindWithTag("MainCamera").GetComponent lt Camera gt () var velocity 0f while (Mathf.Abs(camera.GetComponent lt DepthOfField gt ().aperture) gt 0.001f) Debug.Log(Mathf.Abs(camera.GetComponent lt DepthOfField gt ().aperture)) camera.GetComponent lt DepthOfField gt ().aperture Mathf.SmoothDamp(camera.GetComponent lt DepthOfField gt ().aperture, 0f, ref velocity, 0.3f) yield return null camera.GetComponent lt DepthOfField gt ().aperture 0f
0
Simple animation text color change I apologize in advanced if this is a trivial ask, but I am wondering if it is possible to use an animation to change the color of a Text element from teal white without any lerp, i.e the color instantly changes. My current animation is only the one frame at 0 00 where I do the switch, but you can still see that the color is lerping even though it is the first and only frame. Am I missing something simple or should I just script the change? Fixing the problem is easy (Trivial to script), but I am just curious if there is something in the animation I can change to not have the color lerp? I posted the question here as well, but I never have any luck posting on the Unity forums.
0
Basic rigidbody movement This is a noob question but, what is the rigidbody movement equivalent of transform.position transform.right speed Time.deltaTime
0
How do I create a toggle button in Unity Inspector? I want to create a tool similar to Unity's Terrain tool, which has some nice toggle buttons in the inspector How can I achieve similar design to this? I know how to create normal buttons and other UI components in the inspector, but I can not find enough information to make the buttons toggle. So far I have used normal toggles that produce a checkbox var tmp EditorGUILayout.Toggle( SetAmountFieldContent, setValue ) if ( tmp ! setValue ) setValue tmp if ( setValue ) smoothValue false tmp EditorGUILayout.Toggle( SmoothValueFieldContent, smoothValue ) if ( tmp ! smoothValue ) smoothValue tmp if ( smoothValue ) setValue false Setting the toggle GUIStyle to "Button" does not produce the wanted result. The text or image content goes on left of the button instead of inside. var tmp EditorGUILayout.Toggle( SetAmountFieldContent, setValue, "Button" ) Also none of the options found in GUISkin does not seem to help.
0
C Network flooding I just created a simple MMO in unity3d, then me and my friends test it via LAN and the result is very smooth. But when I hosted it in public (100ms ping) the server became unresponsive and causes random disconnection. Host Setup 1gbps 32gb ram 256 ssd off firewall Server Setup max of 100 players every 100ms update no other updates, just only X and Y location of player by index c sockets w async Server Flow when 100ms tick reaches, server sends position of player base on index in a loop. ex. if (gtick gt 0.1f) for (x lt maxPlayers x ) check ifs couples of ifs here... send sendToWorld(x ... player x .posX ... player x .posY) somewhere, gtick 0, then counts up again... then the result is delay, unresponsive, and random disconnection. maybe it flooding itself, I don't know. but when we test it locally (10 players), it is very smooth and no problem at all. My question is, How can I update all players every 0.1 without server flooding itself?
0
How to change the virtual joystick Input direction depending on camera rotation so the player moves to its current forward direction? I have a scene set up where the player moves and rotates with Virtual Joystick Input. I have button which rotates the camera to the back of my player at that point I want to change the joystick input direction so it moves my player to towards its current forward direction. The joystick Scripts 1) script to handle events public class joystickEvents extends EventSystems.EventTrigger var position Vector2 Vector2.zero public var joyStickHolder Transform private var pointerUp boolean false function Update() if(position! Vector3.zero amp amp pointerUp) position Vector3.Lerp(position,Vector3.zero,5 Time.deltaTime) public function OnDrag(data EventSystems.PointerEventData) position data.position joyStickHolder.position public function OnPointerUp(data EventSystems.PointerEventData) pointerUp true public function OnPointerDown(data EventSystems.PointerEventData) pointerUp false 2) script for joystick movement public class joystick extends MonoBehaviour var joystickEvents joystickEvents var joystickHolder RectTransform var dir Vector3 private var maxDist float private var direction Vector3 private var magnitude float function Start() maxDist joystickHolder.sizeDelta.x maxDist maxDist 2.5 function OnGUI () if(joystickEvents.position.magnitude gt (maxDist)) magnitude maxDist else magnitude joystickEvents.position.magnitude direction joystickEvents.position.normalized transform.localPosition direction magnitude dir direction (magnitude maxDist) The player controller script takes the variable dir to move around the world. I think this value must changed somehow to so that move the player moves towards its current forward based on joystick input when camera is rotated. Here some part of playerController responsible for player movement public class charcterController extends MonoBehaviour private var controller CharacterController private var moveDirection Vector3 Vector3.zero var speed float 6.0 var joystick joystick reference to the joystick script function Start() controller GetComponent. lt CharacterController gt () function Update() var joyInput Vector3 joystick.dir the dir in joystick script dir Vector3(joyInput.x,0,joyInput.y) if (controller.isGrounded) moveDirection dir moveDirection speed controller.Move(moveDirection Time.deltaTime) rotate() function rotate() if(dir! Vector3.zero) transform.rotation Quaternion.LookRotation(dir)
0
UDP client code throwing a very nonspecific exception so I'm writing a UDP server and client on a couple of the machines in my virtual reality environment to allow (in this case) data from the location in the environment to trigger some air nozzles. The air nozzles I can control from the computer I have them plugged into, but I need to be able to control them from my machine running Unity. As far as I know, my server is functioning correctly, but I wrote a secondary listener script just to test it on the same machine and the error I'm getting is Exception System.Net.Sockets.SocketException An invalid argument was supplied. not 100 what this means, as I'm fairly new to Unity and software coding. my Client code is as follows public class udplistener MonoBehaviour public IPEndPoint ipep public UdpClient udpListener public int port 13722 Thread udpThread private Process process Use this for initialization void Start () ipep new IPEndPoint (IPAddress.Any, port) udpListener new UdpClient() udpThread new Thread (new ThreadStart(startProcess)) udpThread.IsBackground true udpThread.Start () Update is called once per frame void Update () try while(true) byte recBytes udpListener.Receive (ref ipep) string data System.Text.Encoding.ASCII.GetString (recBytes) UnityEngine.Debug.Log ("Recieved data " data) catch (Exception e) UnityEngine.Debug.Log("Exception " e.ToString()) void startProcess() process new Process() process.StartInfo.UseShellExecute false process.StartInfo.RedirectStandardOutput true process.StartInfo.RedirectStandardError true process.StartInfo.RedirectStandardInput false process.StartInfo.CreateNoWindow false process.StartInfo.WorkingDirectory WorkingDirectory process.StartInfo.WorkingDirectory "" UnityEngine.Debug.Log("Starting client. Stand by...") process.St process.Start() UnityEngine.Debug.Log("Started client") Commented out for thread closing. Not used any more because of UDP client server while(true) ReadStdOut() if (programStopped) return I'm really confused, because I lifted this code out of another portion of our software to create a "backdoor" into the dSPACE (the physical controller portion) machine so I wouldn't have to change a lot of serial communication that is already in place. What is the Exception referencing and what do I need to change?
0
How to mouse click an object in scene view to select it from editor I have several game objects with colliders in my game. I have enabled Always Show Colliders to keep all of them visible in my scene view. Because the objects are a lot, selecting them from the hierarchy window is a bit cumbersome and really slowing down my workflow. How can I select an object by left mouse clicking on it in the scene view of an editor?
0
Blending Modes in LWRP Particles I created a particle effect using a material created from Particles Simple Lit shader with an image of white circle tinted red through Start Color setting. On the left I have Alpha Blending Mode and on the right Premultiply Blending Mode. Why do I get black lines on the left?
0
Creating charging particles using Shuriken I've been trying to create a charging effect using the Shuriken Particle system for the longest time, and I've had little to no luck with it. I've tried setting different curves for the Force over Time and Color over Time, but I always come up empty. However, I've seen examples all over the place for charging particles. The most recent example of charging particles I've seen is from the Space Cowboy game jam entry LOS CUERVOS. The game has a ship with a laser that requires the player to hold a button down before it fires. It looks like this when charging and firing. I'm specifically talking about the particles surrounding the ball of light that's slowly growing in size over time. I was wondering if anyone here knew what I may be doing wrong when going about setting up the particle system. Any suggestions relative to the question would be much appreciative.
0
Unity 3D Confine a gun rotation within certain degrees I am having troubles making my gun rotate up and down, and have limits, for example, I want the down limit to be 0 degrees, and the up limit to be 90 degrees. Currently I can't figure out how to define that, and when the gun gets to one of the extremes, it gets stuck there and doesn't want to go back. Whats wrong? Here's how I rotate the gun using an on screen joystick float lookAxisX CrossPlatformInputManager.GetAxisRaw("VerticalLook") if ((transform.localEulerAngles.x lt 360 amp amp transform.localEulerAngles.x gt 270) (transform.localEulerAngles.x gt 0) ) transform.localEulerAngles new Vector3( lookAxisX 2f, transform.localEulerAngles.y, transform.localEulerAngles.z) Debug.Log("transform " transform.localEulerAngles) Also right now, when the gun is at the default rotation (facing forward, its X angle is 0, and when it rotates up, it goes from 0 to 359,9, and then at 270 it gets stuck
0
How can I get separate caches for different coroutines? (Unity) I want to fade out an image, so I have a coroutine FadeOut(). However, I want to have a separate image each time I call FadeOut. If I try to do something like this IEnumerator FadeOut(GameObject image) SpriteRenderer render image.GetComponent lt SpriteRenderer gt () yield return null Ignoring all the color changing code which I took out, how do I make it so that I can save a separate cache for each image I add? I don't want to run GetComponent() each frame, because I'm running on mobile and because I want to think of a clever way to stash the renderer. For example, if I declare the renderer at the top like this private SpriteRenderer render and want to cache it on the first frame of the coroutine, there's the chance that calling FadeOut() on another object will change the renderer to a new object and the first FadeOut() will cancel. Can I make the method static? Will that cache a private version of renderer?
0
Score does not increment by 1 in Unity I have made a simple code where once the player moves through the collider that acts as a trigger then Unity adds a score. However, it increases by increments of 8 and I am not sure why. using System.Collections using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public int Score 0 void Start() Update is called once per frame void Update() private void OnTriggerEnter2D(Collider2D other) AddScore() void AddScore() Score
0
How to enable CrossPlatformInput in Unity? I'm new to Unity but not a complete programming novice. I'm trying to use the CrossPlatformInput component from the "Car" prefab from Standard Assets. I can't see it appear and when reading the notes file it says this Importing the CrossPlatformInput package adds a menu item to Unity, "CrossPlatformInput", which allows you to enable or disable the CrossPlatformInput in the editor. You must enable the CrossPlatformInput in order to see the control rigs in the editor, and to start using Unity Remote to control your game. So, What is "a menu item" and where do I find it in the Unity UI? How do I enable CrossPlatformInput? I have dragged the prefab called DualTouchControls into my scene but I can't see anything and I'm not sure how to link it to the actual car object.
0
Difference between Object.Destroy() and GameObject.Destroy() in Unity What is the difference between using Object.Destroy() and GameObject.Destroy() in Unity? I found the following info about that here and here, but it did not answer my question. So, could someone explain the matter foolproof, please?
0
how to modify multiples BoxCollider on a same game object? I have an game object with multiples BoxCollider attached to it, is there a way to get all the BoxCollider to an array so that I could modify their value individually ?
0
Wrong contineous rotation to car In my 2d game, I want to rotate car face based on collision detected. But at present after 3 to 4 collision its doing continuous rotation only rather than moving straight after collision. Here is my straight movement related code myRigidbody.MovePosition (transform.position transform.up Time.deltaTime GameManager.Instance.VehicleFreeMovingSpeed) For better collision purpose, I have used Rigidbody position change approach. Here is my collision time code public void OnCollisionEnter2D (Collision2D other) if (other.gameObject.CompareTag (GameConstants.TAG BOUNDARY)) ContactPoint2D contact contact other.contacts 0 Vector3 reflectedVelocity Vector3.Reflect (transform.up, contact.normal) direction reflectedVelocity if (direction ! Vector3.zero amp amp pathGenerator.positionList.Count lt 0) float angle Mathf.Atan2 (direction.y, direction.x) Mathf.Rad2Deg Quaternion targetRot Quaternion.AngleAxis (angle 90f, Vector3.forward) transform.rotation Quaternion.Slerp (transform.rotation, targetRot, 0.1f) if (Quaternion.Angle (transform.rotation, targetRot) lt 5f) transform.rotation targetRot direction Vector3.zero Rotation get applied within other code so that car was changing its face correctly and that method not affecting here that I have checked by placing debug statement. Share you side thought for this.
0
How can I set the radius the object will rotate around the target? using System.Collections using System.Collections.Generic using UnityEngine public class TargetBehaviour MonoBehaviour Add this script to Cube(2) Header("Add your turret") public GameObject Turret to get the position in worldspace to which this gameObject will rotate around. Header("The axis by which it will rotate around") public Vector3 axis by which axis it will rotate. x,y or z. Header("Angle covered per update") public float angle or the speed of rotation. public float upperLimit, lowerLimit, delay upperLimit amp lowerLimit heighest amp lowest height private float height, prevHeight, time height height it is trying to reach(randomly generated) prevHeight stores last value of height delay in radomness Update is called once per frame void Update() Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update transform.RotateAround(Turret.transform.position, axis.normalized, angle) time Time.deltaTime Sets value of 'height' randomly within 'upperLimit' amp 'lowerLimit' after delay if (time gt delay) prevHeight height height Random.Range(lowerLimit, upperLimit) time 0 Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition) transform.position new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z) Now it's rotating in a constant radius. I set the variable axis to 0,1,0 But if I want the object to rotate around the turret very close to it or very far ? I want to add a radius variable so I can change and set the radius.
0
Unity UI subpixel rendering antialiasing with Image.fillAmount? I'm using DoTween to tween the fillAmount of a UI Image. When I check the value, it changes smoothly, and in the scene view it appears to transition smooth. However it appears jerky in the game view, and seems to step for each pixel, so it seems resolution dependent. Is there any way to have the UI render subpixels (?) or antialiased so it uses colors between green white to have it appear to move more smoothly? Thanks!
0
Unity How do I change the color of the "Screen" based on the Object's depth's (as a Screen Effect)? Yesterday I asked and solved my problem Unity How do I change the color of an object based on its depth? Today I tried to change the script(from yesterday) and apply it to the camera and it did not work. Every pixel which is printed on the Display has a depth (float), is that right? Based on that Depth I want every object to fade grey, relative to the screen distance to that "pixel". Is this possible? Or do I have to use that vertex fragment shader on every single Object and Plane and Sky and everything in the world?
0
Need help with my on collision restart program I tried using the program using UnityEngine private void OnTriggerEnter(Collider other) if (other.tag "setting object tag") Application.LoadLevel(Application.loadedLevel) But the OnTriggerEnter command came up with an error saying "a namespace cannot directly contain members such as fields or methods". And the Application.LoadLevel(Application.loadedLevel) program had an error saying "application.loadedLevel is obsolete, use sceneManager to determine what scenes have been loaded".
0
Unity3D animation trigger reset How can I reset conditions for animations using an animation controller? I have a door that will open when a boolean property in a script is set to true. This then calls setTrigger on the animator to play the open door condition and then reset the boolean property to false. After 5 seconds I then close the door. However when I change the boolean to true again to open the door, either the setTrigger isn't working again on the animator, or the trigger for the door close is conflicting. How would I resolve this? Is there a way in the animator to set a condition to false when a particular animation has finished? Initially I was using a boolean condition in the animator but ran into the same problem. I looked at the 2D sample project which used trigger instead and assumed this would only fire once. However I guess something else could be wrong. The code in my script is as follows (where anim is the animator component) void Update() if (open) OpenDoor() open false void OpenDoor() anim.SetTrigger ("OpenDoor") Invoke("CloseDoor",5) void CloseDoor() anim.SetTrigger ("CloseDoor") As I say the animation fires correctly the 1st time but not on subsequent times. I'm just trying this by changing the public "open" property in the inspector thanks
0
How can I detect a long press then activate an animation? How can I detect a long press on a touch screen then activate an animation? And when the finger is released, play another animation smoothly? Let's take for example the main character in Crossy Road when the user presses down, the chicken "squats" and when the user releases their finger, the chicken jumps. Same concept. C .
0
Preventing Unity from writing to the registry? I see that Unity automatically writes some info to registry when it launches the game. Several people have this problem too Preventing Unity from writing to the registry. How to disable writing to Windows registry? It seems several years have passed but I still can't find how to prevent Unity from writing to registry. I just want to make Unity save amp load settings from file in document folder.
0
How to render the sprites for a 2D soft body physics system This is not a question as to how to achieve soft body physics, but rather if I have a mass spring system how to modify a sprite with that information. I am using unity so I dont have access to vector based graphics.
0
How to use a .mtl file in Unity? I want to use a .mtl file to draw my objects in unity. Can I somehow convert a .mtl file into a normal Unity material? My .mtl file is like this newmtl phongE1SG illum 4 Kd 0.00 1.00 0.00 Ka 0.00 0.00 0.00 Tf 1.00 1.00 1.00 Ni 1.00 Ks 0.50 0.50 0.50 Is this the same as a Unity material which has the sliders "albedo", "metallic", "smoothness", etc? Or is there any shader to do it?
0
how to prevent call on OnValidate() when running game I need OnValidate() to be called only when I am designing my level (placing game objects at their respective positions and setting properties before running the project). But I don't want it to be called when I run the project. I can manually comment it out, but that will take a lot of time, since I have several OnValidate() calls. How can this be done, if it is possible?
0
RaycastHit2D.point is acting weird when used with circlecast2d When I make circleCast2d intersects with another circle collider, I get a RaycastHit2D.point that doesn't point at the tip of the collision as it states in the documentation. Instead it always points at the centre of the intersected junction or pointC as shown in the figure below. I checked this numerous times with different values to make sure the error was not from my end. Is this intended? If so is there another way where I can actually find the closest point from collider(B) to the centre of collider(A) which corresponds to point(D) in the figure? This is a picture of what looks like A circleCast B collided object C where RaycastHit2D.point is pointing at D where I'd like it to point.
0
Follow behaviour with transform.LookAt on Unity2d So i've been trying to make an enemy follow my player on Unity2d using transform.LookAt. While it does follow the player, It also rotates the enemy as well in 3D but my sprite is made for 2d so the sprite just vanishes. Any ideas? follows player transform.position Vector2.MoveTowards(transform.position, target.position, speedEnemy Time.deltaTime) make enemy look towards player transform.LookAt(target)
0
Rotating an object towards a target on the Y axis I am attempting to rotate a 3D object on its Y axis towards a target it is looking at. I have always struggled with rotations so I would like to try to avoid using Unity's built in functions, i.e transform.LookAt() in order to get used to using rotations. Gotta master the basics first, right? Vector3 currentOrientation transform.rotation.eulerAngles Vector3 directionVector3 transform.position target.transform.position float angle Mathf.Atan2(directionVector3.z, directionVector3.x) Mathf.Rad2Deg currentOrientation.y angle transform.rotation Quaternion.Euler(currentOrientation) However when I do run this, the character is not looking in the correct direction at all! Here is a screen shot with the character's parameters The target object belongs in a hierarchy, where it's position in world space is (150,0,500) Does atan2 somehow behave differently in 3D space vs 2D space? I ask because I've made 2D games where I would just use atan2(y,x) for a character's rotation.
0
Can't correct perspective of Main Camera in Unity 3D without losing field of view I have been trying to create a space based rails shooter game following a particular online course and I find a tilt(roll) on my spaceship as I move it towards the left and right ends of the screen. https imgur.com Kkg8hp2 (A normal screenshot of my spaceship at default position) This is due to perspective of the camera as I have been told and apparently dragging the camera farther behind the spaceship and decreasing its field of view helps. https imgur.com 0oXJff7 (The tilted spaceship when it's at an end of the game window) But, doing that neutralizes the illusion of speed caused by a greater field of view. I have found a middle point between the two to balance both aspects of the game but I would like to know if there is any way to get higher field of view without making the ship look like it's tilted. Things I have considered doing Added a positionRollFactor which gives the ship some additional roll in the opposite direction of the tilt. (This still doesn't fix the perspective issue in which one half of the ship is more enlarged than the other). Tweaking the field of view by trading off a little of each feature.
0
Adding Openai's GPT3 to a Unity project? I have a text based project and it has a slot open for Openai's GPT3 model. My project has a terminal module where the user receives emails, I want to go a step further and allow the user to respond to such emails and get some unique response. Here is a rundown of how I want it to work User receives quot email quot , they respond to it, GPT3 steps in and feeds a response into a new quot email quot . So how would I approach this? I think this could be pretty interesting as GPT3 hasn't been implemented in any games yet. I am aware that some beefy hardware may be required but my development computer is quite beefy enough. P.S. Sorry if my title isn't specific enough, closest thing I could think of for this situation.
0
Should my terrain be one big mesh or several medium ones? While creating a subterranean level with probuilder (irregularly shaped rooms and corridors), I was wondering if I should merge all "terrain" meshes into one or keep them as separate meshes? What are the good practices ? I'm creating each room as I go and its not hard to create openings and align doors vertices (with progrids) but once I start moving them around (like with polybrush) I'm sure it will soon be a nightmare. I can see pros and cons for both. Separate meshes would be easier to edit, duplicate or replace, probably better performances but at the risk of overlaps or holes because it would get hard to keep connected cleanly. I guess with one mesh you take the risk of having it eat memory and computation time, or having it too big to edit easily. I settled on each mesh consisting of a room and all half corridors going out of it, to hide the stitching and keep it simple. Still I wonder if there's a consensus.
0
sample project that mix unityscript and c I like the simplicity of unityscript, at same time I also like the plenty of c library and open source projects. I prefer to put my model controller logic flow in unityscript using standard unity3d sdk and invoke c extension library. Is there any sample project demonstrate how to mix the two scripts in one project? Your comment welcome
0
RTS Pathfinding without collision between units Options Ever since I made my units move to a certain location a problem has popped up that of course if I try to make two or more units go to the same place they fight for the same spot. Am I just being stupid and unity already has a way around this or do I need to do something specific? I have looked into flow field path finding but no way on how to implement it. I dont want to have to use a ready made script but some pointers and other options are more than welcome.
0
How to custom UI Slider with Unity UGUI I want to use Unity UGUI to custom a slider and the final looking show be like this And the images I use are But I found it hard to accomplish The handle will be screeched and the fill will not be fully filled with the handle Can somebody tell me how I could accomplish this?
0
How can you make a jump to a point using the Character Controller? I found an example with which the CharacterController can jump, but it does not work to remake it so that it jumps to a certain point distance, and the jumpHeight itself was calculated for speed and gravity, I found this article on Wikipedia, but I don't even know why to begin. public class ExampleClass MonoBehaviour public float speed 6f public float jumpHeight 8f public float gravity 20f private Vector3 moveDirection Vector3.zero CharacterController controller void Start() controller GetComponent lt CharacterController gt () void Update() if (controller.isGrounded) moveDirection new Vector3(Input.GetAxis( quot Horizontal quot ), 0, Input.GetAxis( quot Vertical quot )) moveDirection transform.TransformDirection(moveDirection) moveDirection speed if (Input.GetButton( quot Jump quot )) moveDirection.y jumpSpeed moveDirection.y gravity Time.deltaTime controller.Move(moveDirection Time.deltaTime) Method for jump, calling from other script. void Jump(float pointX) I can't find examples for the Character Controller, although I did find one for the Rigidbody.
0
What's the "right way" to open a websocket connection inside WebGL? The official Unity documentation says that, to run websockets in the WebGL player, you should use this plugin on the Asset Store. Unfortunately, following that link leads to a notice that this asset has been deprecated and is no longer available, with no explanation as to why or what should be done to replace it. With that unavailable, how should I implement WebGL websockets in my game?
0
Can not access GUIText in instantiated prefab I have a prefab with the following component structure Block Quad RawImage GUIText When I instantiate it and try to access the GUIText, I get the output of 'null'. Here is the code, I am using to access the GUIText public GameObject Block GameObject obj Instantiate(Block, position, orientation) as GameObject GUIText myText obj.GetComponent lt GUIText gt () print(myText) How do I fix this?
0
Standard Asset package import in unity 2018.3 I am using iMac, I don't see any for import standard package in unity. My working project need to import standard packages. I use unity version unity 2018.3.0f2. Please guide me from where I get the unity standard asset package. Thanks.
0
How to stop a jump midair and remove y velocity in the process What I want to do is to cut a jump midair by turning off the y velocity when the player releases the jump button (like in Hollow Knight). I managed to do that with rb.velocity new Vector2(rb.velocity.x, 0f) My problem is when I cut the jump and I am midair, if I repeat the release jump button process, the whole thing happens again, the character staggers as long as I am releasing the jump button continously. I would like to be able to do that only once when I am off the ground. I am a noob when it comes to coding so I don't really know what to do. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Events public class PlayerController MonoBehaviour public Animator animator private Rigidbody2D rb public float speed private float moveInput public float jumpForce private bool isGrounded public Transform feetPos public float checkRadius public LayerMask whatIsGround private float jumpTimeCounter public float jumpTime private bool isJumping private bool facingRight true public float jumpDownForceY 0 void Start() rb GetComponent lt Rigidbody2D gt () void Update() isGrounded Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround) if (Input.GetButtonDown( quot Jump quot ) amp amp rb.velocity.y 0) rb.AddForce(Vector2.up 700f) if (Mathf.Abs(moveInput) gt 0 amp amp rb.velocity.y 0) animator.SetBool( quot Running quot , true) else animator.SetBool( quot Running quot , false) if (rb.velocity.y 0) animator.SetBool( quot Jumping quot , false) animator.SetBool( quot Falling quot , false) if (rb.velocity.y gt 0.2) animator.SetBool( quot Jumping quot , true) if (rb.velocity.y lt 0) animator.SetBool( quot Jumping quot , false) animator.SetBool( quot Falling quot , true) if (isGrounded true amp amp Input.GetButtonDown( quot Jump quot )) isJumping true jumpTimeCounter jumpTime rb.velocity Vector2.up jumpForce if (Input.GetButton( quot Jump quot ) amp amp isJumping true) if (jumpTimeCounter gt 0) rb.velocity Vector2.up jumpForce jumpTimeCounter Time.deltaTime else isJumping false if (Input.GetButtonUp( quot Jump quot )) isJumping false rb.velocity new Vector2(rb.velocity.x, 0f) void FixedUpdate() moveInput Input.GetAxisRaw( quot Horizontal quot ) rb.velocity new Vector2(moveInput speed, rb.velocity.y) Flip(moveInput) private void Flip(float moveInput) if (moveInput gt 0 amp amp !facingRight moveInput lt 0 amp amp facingRight) facingRight !facingRight Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale
0
How to use touch screen for movement instead of keyboard narrow keys I wrote this code and run the game on my desktop, now I need to build this game for android and I need to change to touch to move the player, what it should be changed in the following code and what is the necessary steps to build my desktop 2D game to be run on android device, the following is the player code pragma strict var speed int 5 function Start () function Update () if(Input.GetAxis("Horizontal") gt 0) if(collided with ! null) if(collided with.tag "Right") collided with null return transform.Translate(Vector3(Input.GetAxis("Horizontal") speed Time.deltaTime,0,0)) if(Input.GetAxis("Horizontal") lt 0) if(collided with ! null) if(collided with.tag "Left") collided with null return transform.Translate(Vector3(Input.GetAxis("Horizontal") speed Time.deltaTime,0,0))
0
Disable system sounds in Unity? I've got an editor script in Unity 5 that uses the cursor position in the scene view to change objects in the scene when you press the space key. This all works perfectly, except that Unity thinks that space isn't a valid key to press, so it makes the system "boop" sound to let you know that it's invalid or that nothing happened. So, focus is on scene view, I press space, my script triggers, and the mac system "boop" sound activates. It spams the sound if you hold it down. Is there a way to Disable the system boops in Unity or Add space to registered hotkeys stop unity from triggering the system sound for a specific key (just to be clear, the script works, I'm just wondering about disabling the sound)
0
How do I make my 3d cube move left and right with buttons in Unity with RigidBody.AddForce? How do I make my 3d cube move left and right with buttons in Unity with RigidBody.AddForce()? I can't figure out how to do this in Unity! I'm trying to make my game playable on Android but I can't get my cube to move with buttons!
0
How to give the effect on the obstacle? I want to the obstacle Scale In and Scale Out using Dotween PlugIn? means some effect?? See this link https www.youtube.com watch?v Tq4t0gx49g amp t 569s Image I want to give a effect on the obstacle? script Obstacle.cs void Update() goTopToDown() void goTopToDown() foreach (Transform item in GetComponentsInChildren lt Transform gt ()) if (item.tag "obstacleobject") some obtsacle slow item.localPosition Vector3.down speed Time.deltaTime move top to down object if (item.tag "movefastobject") some obstacle fast item.localPosition Vector3.down movefastobjectspeed Time.deltaTime move fast object
0
Unity problems with OnTriggerStay and Input.GetKeyDown Background information Some weeks ago, I start by creating my own platform game. You control a character, that can collect logs and should hold all the campfires on in the game. When the user has collect more then one log, the player have to use this log to hold the fire on. So you should walk to the campfire and should press E to give the log to the fire. Problem What the problem momently is, is that when I press the E key, it will fired the input more then one time. This is because I use a OnTriggerStay2D function, to check every second if my Player is collide with the campfire object. Do some search on the internet, results in people with the same problem. So one of the solutions was to create an bool and set it to true on OnTriggerEnter2D. But this isn't working for me. The same problem as before will occur. Is there another solution to fix this conflict. When the user press the button, it should be fired ones. Below script is linked to the campfire object. Also tried it with if(Input.GetKeyDown(KeyCode.E)) isTrigger true and the same for GetKeyUp, but then isTrigger false My current working code public Animator anim public int campfireStatus bool inTrigger false Use this for initialization void Start () anim GetComponent lt Animator gt () Update is called once per frame void Update () anim.SetInteger("Intensity", campfireStatus) void OnTriggerEnter2D(Collider2D other) inTrigger true void OnTriggerExit2D(Collider2D other) inTrigger false void OnTriggerStay2D(Collider2D other) If player comes in contact with gameObject if (other.gameObject.tag "Player") print ("player") if(Input.GetKeyDown(KeyCode.E)) print ("E Pressed") if (WoodBehaviour.count gt 0) campfireStatus So when the Player is collide with the campfire object AND the player pressed the E key AND you have more then one logs (this counter will be set in the WoodBehaviour script, that is linked to the player object ) than it should increase the campfireStatus with plus one. The problem is, that the if statements will fired more then one times when pressing the E key.
0
How can I write an additive mesh shader that splits the RGB channels while accounting for depth? I'm trying to create a sort of "hologram" effect. So far, what I have is an additive, three pass shader that uses ColorMask for each pass to separate the RGB channels. The problem is that doing so requires ZWrite to be off (first image) so that each pass doesn't intersect the others (second image). However, doing so means that the model geometry overlaps itself, which I don't want. I've tried the various methods of taking depth into consideration with transparency (This, for example) but they all cause problems when trying to separate the RGB channels. Is there some way to have each pass take depth into consideration within itself, but not with the other passes?
0
Is it possible to use nav mesh in 2d game in Unity? I'm working on game that needs navigation and obstacle avoidance. I've used nav mesh on 3d project before but now I'm trying to use it in 2d sprite game but it seems like it doesn't work. I want to know if really it doesn't work and, if it doesn't, what would be a good replacement for a 2d project for the navigation of entities. I'm looking for free tools.
0
Projecting grid textures to select parts of the terrain (Unity) So I'm trying to be smart and not use 500 some tile prefabs to make a grid, and so far the back end portion has gone swimmingly. I initially used a dedicated mesh to represent the grid, but as I'm now opting for 3D terrain (and not tilemapping), I figured that was a lot of unnecessary vertices especially if I want to have the grid conform to the terrain. My shader inexperience, on the other hand, is causing me to stop and overthink this. Using FE as inspiration, I'm thinking about projecting the transparent grid texture onto a base terrain layer. If I wanted parts of the terrain to not be covered by the grid (such as the water area in the picture), would I simply use the world coordinates to tell the shader don't do anything there? The most confusing part for me, however, is how to go about highlighting tiles. I want movement and attack tiles to also be 'painted' onto the terrain in specific colors, but obviously they only affect an even smaller portion than the terrain than the grid. Would I simply be using the same shader to grab world coordinates once again and more or less start stop overlaying the movement attack texture over the grid terrain? And if I'm really being efficient, those textures belong to the same png and I just use UV's to switch between them like a sprite sheet? Is this even a good practice for shaders in the first place? Redrawing and adding textures to only parts of a material? Should I be redrawing and updating the whole texture instead? I guess I get thrown off because I'm only familiar with a 1 1 mesh to material design, so the so the thought of a single mesh but multiple textures on discrete parts that may or may not overlap makes somewhat sense on paper but implementation in Unity is just above me atm. Thanks!
0
When and where and how to turn on back the Player first person when loading a scene on button click ? In the Build Settings I have two scenes at index 0 and index 1 Then in the Hierarchy I have the two scenes The active scene is the MainMenu In the StartGameButton I added to it a script component. In the script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class LoadSceneOnClick MonoBehaviour public void LoadByIndex(int sceneIndex) SceneManager.LoadScene(sceneIndex) And this is the StartGameButton Inspector I dragged the script on the OnClick I selected the function LoadSceneOnClick And set the index to 1 When the game start and I click on the button it stay on the Main Menu scene and not loading anything. The problem I guess is that I'm getting error in the game No cameras rendering The problem is that when I'm running the game and it start from the main menu scene in the space station scene I'm enable false the Player and the Player is a first person character with a camera You can see in the Inspector that the Player is unchecked the Player is not enabled. If I will enable the Player and even if the main menu scene is the active one it will show me the player and the player camera and not the main menu. So I had to turn off the Player. The question now is where by script do I enable back the Player when it's loading the scene ? Inside the LoadSceneOnClick script ?
0
How to retrieve the coordinates of an animated object? On Unity, I created a script in C to animate a cube. I am trying to create a script in C which, once the animated object and in support of a key of the keyboard (for example F) returns to me the coordinates of the object at the moment when I pressed F Can you give me this script? Thank you for your help
0
How can I instantiate in the current rotation in Unity 2d? Backstory I'm currently working on a 2D sidescroller platform game as a hobby, and I just started recently. Followed a few tutorials and such I managed to wrote my own code for basic command like walk, jump, health and so on. However my basic code wasnt perforning as I would expect, I needed a more "Tight" feeling with the movements so I followed a suggestion to use a physics based controller (Prime31's PC2D, Acrocatic or even Corgi Engine...) Well, now the movements are what I feel is good, So I kind of dived in the scripts to add remove customize some code. Question I'm stuck now on a simple issue, I added these lines public Transform weaponMuzzle public GameObject projectile float fireRate 0.5f float nextFire 0 then in my Update() if (Input.GetButtonDown("Fire2")) animator.Play.Weapon() fireProjectile () and here is the problem I have void fireProjectile () if (Time.time gt nextFire) nextFire Time.time fireRate if ( motor.facingLeft) Instantiate (projectile, weaponMuzzle.position, Quaternion.Euler (new Vector3 (0,0,180f))) else if (! motor.facingLeft) Instantiate (projectile, weaponMuzzle.position, Quaternion.Euler (new Vector3 (0, 0, 0))) The prefabs are also physics based and they are fired with no problems, however they don't want to follow the current rotation of the player, they always go in the right X axis. First of all, the facingLeft on my code is what I understand is the reference to the character controller motor, I tried with motor.normalizedXMovement gt 0 and motor.normalizedXMovement lt 0 (normalizedXMovement 1 is full left and 1 is full right) this just make it that you can only fire while moving, not stopped and the problem still persists. I also tried with Quaternion.Identity instead of Euler and it's the same. For a full source code https github.com prime31 CharacterController2D I'm kinda lost and it would means a lot if you can help me out on this issue. Ps I already searched here and other related forums but cannot find the answer, this is not a repost.
0
Why do I get these "Invalid command android" errors trying to build for Android in Unity? Trying to move a unity project over to android using gradle as the build system. I get the following 3 errors Error Invalid command android CommandInvokationFailure Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details. Library Java JavaVirtualMachines jdk1.8.0 91.jdk Contents Home bin java Xmx2048M Dcom.android.sdkmanager.toolsdir " Users joeljohnson Library Android sdk tools" Dfile.encoding UTF8 jar " Applications Unity PlaybackEngines AndroidPlayer Tools sdktools.jar" stderr Error Invalid command android stdout exit code 64 UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.HostView OnGUI() and Error building Player CommandInvokationFailure Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details. Library Java JavaVirtualMachines jdk1.8.0 91.jdk Contents Home bin java Xmx2048M Dcom.android.sdkmanager.toolsdir " Users joeljohnson Library Android sdk tools" Dfile.encoding UTF8 jar " Applications Unity PlaybackEngines AndroidPlayer Tools sdktools.jar" stderr Error Invalid command android stdout It turns out a lot of people have been having this problem and the most common solution is to move to an earlier version of the apk. When I tried that, I still received the same three errors. I moved down to api level 23 from the most current. I am one a mac. exit code 64
0
Physics2D.Raycast not hitting any colliders I am making a topdown 2d game and want to get the x,y of mouse clicks so I can move the character to that location. I am writing a CharacterController script which performs the mouse click check and raycast in the Update function void Update () if (Input.GetMouseButtonDown (0)) RaycastHit2D hit Physics2D.Raycast(Input.mousePosition, Vector2.up) if (hit.collider ! null) Debug.Log (hit.point) This runs whenever I click the mouse, but the if(hit.collider ! null) condition is never met. I've looked around for other solutions, such as Unity Raycast not hitting to BoxCollider2D objects, but when I change my code to the one used in that answer RaycastHit2D hit Physics2D.Raycast( Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector3.back ) then the if(hit.collider ! null) block is always true, even if I click on empty space, and it always returns the same coordinate. To illustrate this, here is a video of me clicking the game view. The green area has a 2d box collider that is very closely mapped to its boundaries. You can see that the logged hit.point is always the same. video is here https i.imgur.com uhNp8wC.gifv screenshot
0
Unity splash is starting in progress after white screen When I export my Unity project (on Windows), there is a brief white screen before the Unity splash screen renders, already in progress. Discretely cutting to the already in progress splash screen looks pretty bad, so I'd like to fix this. Here is a video showing what I mean. After some googling, I did find other reports of a white screen, but only on Android. My project is very simple and I am not loading anything intensive on boot, so I'm not sure what is causing this white screen. Does anyone know what might be causing this issue or have ideas to troubleshoot it?
0
How should I manage my data that needs to be associated with rank (Unity) So I am making a game with a similar content progression to Clash Royale. Essentially u have ranking points (Identified as Trophies), and the number of trophies you have will determine what content you will have access to in the game. So for example every 100 ranking points, you will be able to find new types of cards in chests, new chests in general or new maps. In my game, I want it to be somewhat similar, but I also have some other data that changes based on rank points that is more specific to my game, such as army supply. I'm trying to figure out how I can implement this in a manageable way. Maybe this is overkill, but this is my design so far Basically I have my RankContentItemBase class which has a ranking points int and an IsUnlocked method that returns whether or not the passed in rank is gt than the rank passed in. Then I extend this with classes with classes that add the data type I wanna work with (Int, Troop, Map, w e). I then have a Generic base container class that has a method for getting all unlocked item in the list of T contents that is extended to contain the concrete RankUnlockItembase types. I've basically structured things this way so it's easy for me to add new types of items that I want unlocked by rank without having to do much work. Also it prevents things from being coupled together. Just curious what ppl think of this setup, and what kinda setup you would go with? One concern I have with this design was that if I wanted to see whether a troop was unlocked or not, I can't just say troop.IsUnlocked(). Instead I have to create a new means of determining whether or not a troop is unlocked yet, like for example maybe a method on the RankUnlockedTroopContainer that determines this. Maybe this is ok? I feel like I'm sacrificing simplicity for the sake of maintainability flexibility. Thanks
0
How to express AI area ownership? Situation Big open world ish level Different types of real estate Houses including some land around it Just houses without land Flats on different floors How to express AI ownership of any of those types that I could use in game logic? My first thought was to use collider around the area as a trigger that I could use to detect if "guest" enters the area and program AI to only react if certain criteria is met (e.g sees the guest, friend vs enemy) but Most areas are pretty complex I would need to use mesh colliders It would get rather expesive if I had many areas around the player active (urban environment) I also need the concept of "my area" for other logic e.g pathfinding, place items etc
0
Animation rotates model but I don't see how I have 2 animations. In the following animation preview, the same model is being used. As you can see in the animator, there is no significant rotation difference. However, one animation rotates the model 90 degrees to the left. I have inspected all the rotation values in the animation tab. I just don't see any difference. What causes this signifant rotation difference? Thank you!
0
Two Points Rotating Around Circle? Currently I am working on a 2D game just like duet game, it is my first game (Unity 2D). When I press left key both points rotate fine. But when I press right, the points are not rotated. So my problem is why do both points rotated only in one direction Code public class TouchControll MonoBehaviour float movespeed 3 float angle 45 void Update() if (Input.GetKey(KeyCode.LeftArrow)) when i m press leftarrow both point should be rotate fine transform.Rotate(Vector3.forward Time.deltaTime Input.GetAxis("Horizontal") angle movespeed) Debug.Log("moveleft") if (Input.GetKey(KeyCode.RightArrow)) problem is here when i m press right arrow key both point are not rotated transform.Rotate(Vector3.forward Time.deltaTime Input.GetAxis("Vertical") angle movespeed) Debug.Log("moveright") Output create a empty gameobject first circle second circle
0
Why doesn't my SpriteRenderer's color change when setting .color new Color(166, 33, 33)? I need to change the color of my SpriteRenderer, and so I looked up how to do it and come up with this code spaceOne.GetComponent lt SpriteRenderer gt ().color new Color(166, 33, 33) (In case you are wondering, yes I checked that 'spaceOne' is correctly linked to a GameObject.) This should change the color, but it doesn't. As I was writing this, I found that replacing new Color(166, 33, 33) with Color.red actually does change it to red. So now I am wondering, why does the new Color(166, 33, 33) code not work, and how can I fix it? P.S. I made sure that it wasn't something simple, like it being RGBA rather than RGB, but no, it still doesn't work with new Color(166, 33, 33, 255) .
0
Unity Texture Problem http www.gfycat.com FlawedLimpingGrizzlybear http www.gfycat.com UnawareQuerulousHawk Every texture and shader has the same problem. It seems like the problem has nothing to do with either. Tried all the things my friends suggested I should, reimported everything, restarted my machine, nothing seems to work.
0
How to display a text in the impact point position In my 3d game, i would like to display a text 'near' the impact point of a bullet. I think i'm having problems setting properly text position. This is my code. The script is attached to an object Canvas. position is the Vector3 impact position. GameObject obj new GameObject () Text text obj.AddComponent lt Text gt () text.transform.position position text.text message text.fontSize startSize text.color color I'm pretty sure i've to convert from a world space to a 'user interface' space. Thanks
0
AndroidManifest file was deleted by accident I deleted the AndroidManifest file of my project which was located in Assets Plugins Android , so I tried creating new project and copying the Assets and everything but it seems that something is missing ,it's perfectly working in the editor , but as apk there are few things aren't working, I can't figure out why, and there isn't even a Plugins folder in my new project !
0
Make Build and Run faster Is there a way to build an apk faster? (by disabling some shader compilation, for example Hidden Post FX Uber Shader takes most of the build time) p.s. Yes I know about Unity Remote and use it this time I need exactly Build and Run.
0
Why the camera is not moving only up but also to the right? using System.Collections using System.Collections.Generic using UnityEngine public class CameraMove MonoBehaviour public float smoothSpeed 3f Use this for initialization void Start() Update is called once per frame void Update() private void FixedUpdate() transform.localPosition Vector3.MoveTowards(transform.localPosition, new Vector3(0, 500, 0), smoothSpeed Time.deltaTime) The script is attached to the Main Camera. I want the camera to move directly up and a little bit also to the back. But the way it is now it's moving up but also to the right. Why it's moving also to the right ? I tried transform.localPosition and also only transform.position
0
Difference between Unity's Camera.ScreenPointToRay and Camera.ScreenToWorldPoint? What is the difference between Unity's Camera.ScreenPointToRay and Camera.ScreenToWorldPoint. And where we can use these. I've watched some tutorial and documentation but I didn't get a clear understanding.
0
Why i'm not getting the FPSController Rotation values? using System.Collections using System.Collections.Generic using UnityEngine using UnityStandardAssets.Characters.FirstPerson public class RotateObject MonoBehaviour public UnityStandardAssets.ImageEffects.Blur blur public UnityStandardAssets.ImageEffects.BlurOptimized blurOptimized public FadeScript fadescript SerializeField Quaternion targetRotation lt summary gt Rotation you want to achieve. lt summary gt SerializeField private float s lt summary gt Rotation duration. lt summary gt private Quaternion initialRotation lt summary gt Your GameObject's initial rotation. lt summary gt private float t lt summary gt Your 't' reference. lt summary gt private FirstPersonController fpcscript void Awake() fpcscript.enabled false fpcscript transform.GetComponent lt FirstPersonController gt () initialRotation transform.localRotation void Update() if (fadescript.alphaZero true) if (t lt 1.0f) transform.rotation Quaternion.Lerp(initialRotation, targetRotation, t) t (Time.deltaTime s) Each 60 frames optimally t reaches 1, divided by your duration, it will reach 1 on 'x' seconds. else Your rotation ends here reset 't' if you please , and reset 'initialRotation' initialRotation transform.rotation blur.enabled false blurOptimized.enabled false fpcscript.enabled true The script is attached to FPSController. In the Inspector the Rotation of the FPSController is X 7 Y 112 Z 31 But when i'm using a break point on the line in the Awake initialRotation transform.localRotation I see that initialRotation values are ( 0.2, 0.8, 0.2, 0.5) What i want to do is to rotate the transofrm from X 7 Y 112 Z 31 to rotation 0,0,0 That is why i also didn't set any values to targetRotation since i want it to rotate to 0,0,0
0
Model colors look much better in blender than Unity (LWRP), how to fix bad colors in Unity LWRP? I made some models in blender 2.8 After importing them to Unity, they look much worse Still the same material as in blender, I use the LWRP and have had nothing but issues with it, the lack of AO being one. Is there something I'm missing because it should not look this much worse in the Game Engine?
0
How to remove a component of an object in a script? I want to remove a Sphere Mesh Renderer component from a certain gameobject. I want to do this in a script. How do I do it? I do not want to destroy the sphere itself, just the component
0
How to calculate 2D viewport coordinates in a shader? In Unity, I use the following shader to calculate 2D viewport coordinates Shader "Foo" SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag struct vertInput float4 pos POSITION struct vertOutput float4 pos SV POSITION float4 uv TEXCOORD0 vertOutput vert (vertInput input) vertOutput o o.pos mul(UNITY MATRIX MVP, input.pos) o.uv mul(UNITY MATRIX MVP, input.pos) return o fixed4 frag (vertOutput output) SV Target float2 viewport output.uv.xy output.uv.z return float4(sin(viewport.x 10.0), sin(viewport.y 10.0), 0.0, 1.0) ENDCG At first, it seems to work great. Here is results However if I move camera very close to the surface, the following unexpected glitch occurs
0
Drawing visibility polygons in Unity (for vision cones with occlusion) I'm currently trying to create an effect like the one displayed below in Unity However, it seems that I can't do this with any of Unity's built in light objects, and I simply cannot find anything online that talks about this. Is there a way to achieve this in Unity? 2D or 3D solutions are fine, as I'm sure that they're both very similar to each other,
0
Photon Realtime, StripKeysWithNullValues cause heavy GC Alloc In our current project, we use Photon room properties to sync entities. and i noticed some heavy GC Allocs while deep profiling the game and it always ends down to this method. Have anyone faced this issue before ? or attempted to fix it ? here is the source code of that method. lt summary gt This removes all key value pairs that have a null reference as value. Photon properties are removed by setting their value to null. Changes the original passed IDictionary! lt summary gt lt param name "original" gt The IDictionary to strip of keys with null values. lt param gt public static void StripKeysWithNullValues(this IDictionary original) object keys new object original.Count original.Keys.CopyTo(keys, 0) for (int index 0 index lt keys.Length index ) var key keys index if (original key null) original.Remove(key)
0
How do I roll a ball with a Rigidbody? I have a ball in a game that rolls around just fine with Rigidbody.AddForce(). I have other non physics balls, however, that I control directly with Rigidbody.MovePosition(). It seems that no matter what I do, no matter how interpolation and collision detection are set, the ball does not "roll" when moved with Rigidbody.MovePosition(). It teleports, but IsKinematic is not set , as instructed by the documentation. How do I get the ball to roll properly with Rigidbody.MovePosition()? Alternatively, if that's not possible, how do I calculate the rotations manually?
0
When creating a UI scene in Unity, should I render the canvas in camera space? I'm working on a scene that is strictly going to be used for character creation. Can anyone explain what the best practice is for a scene like this? Should I render the canvas to the camera, or should I render it in world space, or as an overlay?
0
Unity3D Problems drawing on duplicated texture I'm trying to load texture from assets folder create a clone of said texture that will be manipulated during runtime set pixels on cloned texture I have successfully set pixels on the original texture (ie. discarding the code in the start function), but I cannot seem to be able to draw to the duplicated version. void Start () canvas gameObject.GetComponent(typeof(SpriteRenderer)) as SpriteRenderer Sprite oldSprite canvas.sprite Texture2D oldTex oldSprite.texture Rect oldRect oldSprite.textureRect tex new Texture2D(oldTex.width, oldTex.height, TextureFormat.RGB24, false) tex.SetPixels32(oldTex.GetPixels32()) tex.Apply() Rect r new Rect(oldRect.x, oldRect.y, oldRect.width, oldRect.height) Vector2 pivot new Vector2(oldSprite.pivot.x, oldSprite.pivot.y) float pixelsPerUnit oldSprite.pixelsPerUnit Sprite sprite Sprite.Create(tex, r, pivot, pixelsPerUnit, 0, SpriteMeshType.FullRect) canvas.sprite sprite public void draw(Tool tool, Color32 color, List lt Vector2 gt locations) Color32 pixels tex.GetPixels32(0) for(int i 0 i lt pixels.Length i) pixels i color tex.SetPixels32(pixels) tex.Apply() Please ignore the unused vars, I'm just trying to set the whole texture's color for now. Anyways, any help is always appreciated thanks )
0
Fading Text in one character at a time I'm a Unity game developer. I have a bit of a conundrum. I have two enumerators, one that displays text one character at a time, and the other takes the whole text and fades it in over time private IEnumerator FadeTo(float aValue, float tValue) float alpha GameText.GetComponent lt Text gt ().color.a for (float i 0 i lt 1.0f i Time.deltaTime tValue) Color alphaChange new Color(1, 1, 1, Mathf.Lerp(alpha, aValue, i)) GameText.GetComponent lt Text gt ().color alphaChange yield return null private IEnumerator CharXChar(string text) for (int i 0 i lt text.Length i ) yield return new WaitForSeconds(0.1f) GameText.GetComponent lt Text gt ().text GameText.GetComponent lt Text gt ().text text i The problem is, I do not know how to get the FadeTo enumerator to modify each character individually. I just need a step in the right direction. Any help would be greatly thanked.
0
Make an animation repeat X times I am using Unity Mecanim and I would like an animation ( walking animation about 2 seconds longs ) to repeat X times before moving to the next animation. How can I achieve this?
0
How can I change the list of enum options displayed in the inspector? I have an array of enums using UnityEngine public class EnumsInInspector MonoBehaviour SerializeField public EnumType myEnums new EnumType 3 public enum EnumType A, B, C I want it so that if the enum at index 0 is B, then when selecting the enum at index 1, only A and C are options, and B is no longer available. How can I achieve this?
0
Change unity physics engine speed Is there a simple way to change the speed of unity's physics engine like in the game SuperHot? Any script language is ok but javascript is preferred. I am not sure if speed is the correct term.
0
Unity 3D, Making contiguous looking worlds Im currently involved in making a third person cooperative mobile game in Unity and in said game there will be an area for players to walk around in with various elevations and whatnot throughout the field. Its designed to be set up with 4 biomes in the area to go along with the games theme but I was wondering what would be the best way to mask the "boundaries" or "cut off points" in this area? From certain vantage points its pretty obvious that the terrain used to make the world simply stops and I was wondering if anyone knew any tips and insights on how to best mask these boundaries without too much "padding" in the game area in order to keep it relatively less taxing on a mobile device. Thank you in advance.
0
Inflating a balloon while the user touches holds the screen I'm trying to create a simple balloon which will enlarge as the user touches and holds the screen. So I wrote something like this while ( Input.GetMouseButtonDown(0) ) transform.localScale new Vector3(1, 1, 1) yield return new WaitForSeconds(1) It causes a compiler an error The body of 'enlargeBalloon.Update()' cannot be an iterator block because 'void' is not an iterator interface type How can I fix this?
0
Anchor a health bar to a character enemy I have a game I'm working on where the player can see the health bars of the player's avatar and other creatures in the game. I want this health bar to always follow the character creature around. However, I can't figure out how to do this. I thought having the position change when the respective object moved would do the trick, but apparently, it doesn't. When watching the health bar's transform, however, it shows that it is moving with it's respective object but I don't see it on the game screen. Can anyone explain how I go about accomplishing this? Here's the Dropbox link to the project. HealthBar Script public class EnemyHealthBar MonoBehaviour public Texture2D healthBar public Texture2D health public Rect healthBarPosition public Rect healthPosition public GameObject monster void Start() void Update() transform.position new Vector3(monster.transform.position.x, monster.transform.position.y, monster.transform.position.z) Debug.Log(transform.position) void OnGUI() GUI.DrawTexture(healthBarPosition, healthBar) Video of what's currently happening Dropbox Link