_id
int64
0
49
text
stringlengths
71
4.19k
0
Combine all animation state into one clip (.anim) file in unity I have an animation controller where different animation states(clips) are available. Like this Now my aim is to convert all this states animation into a single clip (.anim file). Is this possible. ? I am able to copy one animation clips frame using this. But it very time consuming.
0
Using a script to draw an icon next to (i.e. inline with) a text label in Unity Suppose mystring is a string variable (whose value changes over time) and that myIcon is a texture or sprite of known dimension, say 32x32. Is it possible to write a Unity script that draws myIcon alongside myStringlike this example (where myString is "TURTLE" in this case) In particular, I have the following challenges I would like the whole construction (icon string) to be horizontally centered on the screen). The spacing between the icon and the text should be some fixed number of pixels. Since the pixel width of the string changes when the value of the string changes, the appropriate horizontal positioning of the icon and the text will also change and can't be easily calculated in advance. So, my question is how can I draw and center such a GUI element using a Unity script? The obvious way to do this would be to have myIcon inline in the text label, but I read that this isn't possible with unity's current GUI implementation. It also looked like this might be possible using a horizontal layout group, but I couldn't find a clear guide on how to implement that in a script.
0
SocketException No connection could be made because the target machine actively refused it I am working on connecting a client to a server using socket connection. I have a button, when I click on the button, it's giving the below exception in Unity. "SocketException No connection could be made because the target machine actively refused it.". What will be the issue? Can anyboady help me out? Below is the code I have written for connecting to the server internal Boolean socketReady false NetworkStream theStream StreamWriter writer StreamReader reader try connect new TcpClient (host, port) theStream connect.GetStream () writer new StreamWriter (theStream) reader new StreamReader (theStream) return true socketReady true catch(ObjectDisposedException) return false
0
Unity 3D Sound sounds weird if audio listener is moving fast If you place 3D Sound which is set to logarithmic falloff and move very fast, then it sounds extremly weird and plays way faster than normal. How can I prevent this? I made a short video https www.youtube.com watch?v bZJ7YS775E amp feature youtu.be
0
Main camera transform.forward becomes up and down when looking from above The camera script is a 3rd person orbit camera, when I look straight it does what it supposed to do which is walk in the direction the camera is pointing, but when the camera is looking down from above the player, the camera's forward is now up. This means when I press W to go forwards I go into the ground and when I press S it goes upwards. Here is my movement script private void FixedUpdate() float x Input.GetAxisRaw("Horizontal") float z Input.GetAxisRaw("Vertical") Vector3 moveDirection Vector3.zero moveDirection Camera.main.transform.right moveDirection Camera.main.transform.forward moveDirection.y 0 Rotation if (x ! 0 z ! 0) anim.SetBool("Walking", true) if (x ! 0) transform.rotation Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), 0.4f) else transform.localEulerAngles new Vector3(transform.localEulerAngles.x, Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z) else anim.SetBool("Walking", false) Moving if (Input.GetKey(KeyCode.LeftShift) amp amp !idle) anim.SetBool("Running", true) rb.position z Camera.main.transform.forward Time.deltaTime runSpeed rb.position x Camera.main.transform.right Time.deltaTime runSpeed else anim.SetBool("Running", false) rb.position z Camera.main.transform.forward Time.deltaTime moveSpeed rb.position x Camera.main.transform.right Time.deltaTime moveSpeed while I'm asking, the movement script gets doubled when two keys are pressed, how do I fix it while keeping the same functionality of my current movement script?
0
Prevent Unity from crashing your computer? Recently, I made a very dumb mistake that caused Unity to crash my computer. I could move the mouse sometimes, but everything else became completely unresponsive, leading to me having to shut off my PC. What happened I had an object, let's say an arrow, that could collide with another object, let's call it spawner. When the arrow collides with the spawner, it's supposed to destroy the arrow that activated the spawner. The spawner would then, as the name might imply, spawn more arrows. The problem was that I forgot to temporarily disable to collision on the newly spawned arrows, meaning that as soon as they would spawn inside the spawner's collision box, they'd spawn more arrows, and those arrows would spawn more arrows, and those arrows would... you get the idea. It was a very stupid mistake I realized the moment I hit play, but it was too late. Now, I know that was entirely my fault, but I was wondering if you could prevent Unity from sending your PC into a coma like that? (Besides not making a dumb mistake like that, of course...) I'll be honest, I kind of expected Unity would have some sort of fail safe for this kind of error. Is there a way to limit the object count for example?
0
Load scene without being in build settings and without using AssetBundle This is the closest I've gotten EditorSceneManager.OpenScene( AssetDatabase.GUIDToAssetPath( AssetDatabase.FindAssets( "t SceneAsset " MenuSceneName, new string "Assets" ) 0 ) ) However this generates an error at runtime InvalidOperationException This cannot be used during play mode, please use SceneManager.LoadScene() SceneManager.LoadSceneAsync() instead. I can't follow its suggestion because those functions require the scene to be in build settings or an asset bundle. So, is there any other option? I wonder how (and if) Addressables achieve this? Note I'm not willing to switch to Addressables I'm quite enjoying working with AssetBundles. Why? My game uses AssetBundles for general loading of EVERYTHING, so there's only one blank scene in build settings. However, during development I'd rather not have to continuously build and load from AssetBundles, so I'm trying to dynamically load scenes WITHOUT having to add them to build settings.
0
Why is unity's RaycastHit2D contact point is slightly off This is a small test I made, basically I have a simple BoxCollider2D that has the top surface aligned with the x axis. It's just a 1x1 cube placed at (0, 0.5). Now when I cast a ray down from position (0, 1) I would expect the resulting RaycastHit2D's contact point to be (0, 0) however when I log the contact point, it shows it is slightly over the actual surface at (0, 2.384186E 07). So the question is, why does this happen? Also, can it be fixed somehow (like tweaking settings or something)?
0
Prevent GUI Clickthrough I'm using NGUI to setup my UI in Unity. Attached to the MainCamera I do have a script to rotate the camera view by clicking and dragging. It does handle mouse events using Input.GetMouseButton(). The problem is that if I click and drag when the mouse is over a NGUI element (Button, Panel, Slider, whatever), NGUI handles all the mouse events correctly, but they also go through the MainCamera, and the camera rotate. I want to prevent that. If I use for example the Unity GUI.Button(), the mouse events are not transfered to the MainCamera and the camera does not rotate. I have to replicate that, but using NGUI. I have searched on their support forum, but i couldn't find a solution.
0
Play audio clip from where it left I spent some time playing with AudioSource.time amp AudioSource.timeSamples and read some posts about them. So I get that due to audio compression I can't rely on .time for accuracy so I need to use .timeSamples. Yet, when I printed some output of how .timeSamples work coudn't understand the idea behind it at all. I simply made a 30 sec audio loop and with first play it starts from 7526 and 2nd time 38 and every next time it loops, starts and ends with different timeSample values. Why? What I simply want to achieve is the thing I wrote in the header and also to be able to play the sound at for example the 5th or 10th or any second without losing the accuracy from the compression for android or ios. How can I do that?
0
Unity 3d Animation Flickering We are using 3d bus model for our game in Unity 3d.Animation works perfectly fine on Samsung s3 but some kind of texture flickering occurs on Nexus device.Please help us out how to solve this problem. Thank you
0
Optimal Way to Create Card Templates in Unity 2D I have a couple questions involving software architecture and best practices in Unity. Although I have some programming knowledge, I am just starting with Unity and C , and I would like some input from people with more experience than myself so I can learn Unity the right way and do not let bad habits take root. In a nutshell I am trying to put together a simple card drawing mechanic, where I would define a card layout (kind of like a class) and then initialise two three at a time with data pulled randomly from a data source. Cards would have standard attributes like, cost, image, name, etc. My first question is what would be the optimal way to define the card template? Off the top of my head, I would say that it should be a prefab. But I am aware that there are other options as well, such as scriptable objects. My other, related question, is what would be a good way to store card data with future expandability in my mind. If my idea ever comes to fruition, I would like to release new card packs periodically, expanding the main card stock bit by bit. So, I am guessing, storing it in a simple JSON is probably not the best choice from a software architecture point of view. Thank you for your answers!
0
Affecting all instances of a GameObject at once I want all instances of a prefab to change their velocity when one of them is clicked, and I think having each object constantly check a variable with a coroutine might not be the best solution. How can I reference all instances of the prefab in a script efficiently?
0
Unity Determine direction vector3 from a point in space and an angle in eulers I have a ball positioned as Vector3(x, x, x). I was able to get the direction of the ball to the mouse clicked position with Code (csharp) Vector3 direction Direction (clickPos2 startPos) Where the method is Code (csharp) public Vector3 Direction(Vector3 position) return new Vector3(position.x Length(position.x, position.y), position.y Length(position.x, position.y), position.z) Now I have an angle in eulers and I want that the ball goes to the direction of the angle. But how I calculate it? The game is played in 2d so actually only x and y is needed, z stays the same. Mirza
0
Is there a way to run an Android Unity game in Windows? I was wondering, given a generic Unity game built for Android (with no desktop version), if I could somehow run it on windows (not in an android emulator) by using the windows version of mono. The theory is that the script assembly (if the scripting was done in c ) is separate from the game engine. I tried replacing the Data folder of a windows game with the Managed folder from the Android apk but got this error Failed to load PlayerSettings (internal index 0). Most likely data file is corrupted, or built with mismatching editor and platform support versions. Is there some tool I can use to change the platform of a third party unity game in order to play it ? I'm not an unity developer myself but my concern is that games could use features not supported on desktop...
0
How do I add an "offset" to LookAt? I have created a Third Person Controller. The camera is behind the player I would like to make it so that the player aims at the mouse pointer position. To do that, I use the following code to rotate the chest towards the position var mousePos Input.mousePosition mousePos.z 10 Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) Chest.LookAt(aim) The hands do not perfectly straightly point forwards, so I need to add an quot offset quot to the LookAt. I tried this approach var mousePos Input.mousePosition mousePos.z 10 Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) aim new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0) Chest.LookAt(aim) Of course I do all rotation patching in LateUpdate(). In Update(), it would simply be erased by the animation itself. It does work, but when the model is rotated around the Y axis, something goes wrong The offset is quot wrong quot , it doesn't have the same effect. This surprises me because all I do is rotate the entire model. So I think this line is not correct aim new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0) Is this not the way to offset the LookAt results?
0
Changing the camera movement in unity I have a code that allows me to move the camera on the x axis. I need it to move on the y axis as well as the x. using UnityEngine using System.Collections public class orbit MonoBehaviour public float turnSpeed 4.0f public Transform player private Vector3 offset void Start () offset new Vector3(player.position.x, player.position.y 8.0f, player.position.z 7.0f) void LateUpdate() offset Quaternion.AngleAxis (Input.GetAxis("Mouse X") turnSpeed, Vector3.up) offset transform.position player.position offset transform.LookAt(player.position)
0
A terrain with underground tunnels The Terrain tool in Unity is great for constructing 3 D landscapes that are open from above. I am working on a game that happens entirely inside tunnels (specifically, blood vessels in a human body. But it can also be tunnels in an ant nest, or sewers below a city). There is nothing quot overground quot all movement is inside the tunnels. I am looking for a tool, similar to Terrain, for easily constructing this complex system of tunnels. One solution I thought of is to construct a terrain with quot half tunnels quot (i.e., open from above), then duplicate it, rotate 180 degrees, and quot glue quot on top of the first copy. But it can only handle one layer of tunnels, and in addition, for some reason I could not rotate the terrain. Is there a way to construct such underground tunnels with the Terrain tool, or with a different tool in Unity?
0
How to add a force to jump in unity I have created a simple player control. I have used "Vertical" and "Horizontal" axes as input to move. There is a character controller and I used this to move my player. But I don't know how to add a force as jump with space input. I am new to game development. Please help me to learn this. This is my script, public class PlayerControll MonoBehaviour public Animator anim public CharacterController characterController public Rigidbody rb public float Speed public float Direction Vector3 moveDir Vector3.zero float speedwalking 8 float gravity 8 void Start() anim GetComponent lt Animator gt () characterController GetComponent lt CharacterController gt () rb GetComponent lt Rigidbody gt () void Update() if (characterController.isGrounded) anim.SetBool("Grounded", true) if (Input.GetButton("Vertical") Input.GetButton("Horizontal")) Speed Input.GetAxis("Vertical") Direction Input.GetAxis("Horizontal") anim.SetFloat("Speed", Speed) anim.SetFloat("Direction", Direction) moveDir new Vector3(Direction, 0, Speed) moveDir speedwalking moveDir transform.TransformDirection(moveDir) characterController.Move(moveDir Time.deltaTime) moveDir.y gravity Time.deltaTime else anim.SetFloat("Speed", 0) anim.SetFloat("Direction", 0) else anim.SetBool("Grounded", false)
0
Why are setcolor and color not reset When I do a color exchange directly on the material in playmode, but then I go back to editmode, why do the settings still remain? For example mymaterial.SetColor( quot Color quot , blue) or mymaterial.color blue
0
Rotate an object smoothly by using Accelerometer Input in Unity There is a simple script where the object orientation is equal to the mobile devices orientation. it works but the object doesn't rotate smoothly. void FixedUpdate() float accelx Input.acceleration.x float angle Mathf.Asin(accelx) Mathf.Rad2Deg transform.eulerAngles new Vector3(angle , 0, 0) How to rotate an object smoothly by using Accelerometer Input ?
0
Check if OpenVR SteamVR OculusVR headset is mounted on your head The Oculus and the Vive have this light proximity sensor that detects whether you have your VR headset placed on your head currently or not. Is there any way to tap into that for our own game checks? E.g. We could pause or restart the game depending on whether the headset's being worn or not. I'm using Unity C , but any (driver API level) help is much appreciated.
0
What causes regions of improperly lit terrain when my pixel light count is below 4? My Unity3d game has a strange bug where if you have the pixel light count set below 4, these strange boxes appear on the terrain. Because this game is going to be for mobile, if I set the pixel light count too high, won't run fast enough. The screenshot will show you what I mean You can see this box on the left of the image where light is entering, I want light to enter all around the coin. How can I fix or prevent this?
0
What does SlerpUnclamped do? Unity has a Slerp method public static Vector3 Slerp(Vector3 a, Vector3 b, float t) Where it returns an interpolated position between a and b by the percentage of t. So if t 0.5, and a Vector3.zero, and b Vector3.one, it returns a Vector3 of (0.5, 0.5, 0.5). But what does SlerpUnclamped do? public static Vector3 SlerpUnclamped(Vector3 a, Vector3 b, float t) t is not clamped between 0 and 1. So what what is t relative to? How do you use this method?
0
Make a background Image to fit multiple objects? In the Hierarchy, I have a GameObject named "Buttons" to which I added an Image component. I would like that the ok sprite to cover (be background of) all the buttons START GAME, OPTIONS, CREDIT and EXIT. But the ok sprite is somewhere in the top left corner behind the START GAME button on its left side and is very small. This happened when I clicked in the Inspector in Image on Set Native Size. I want to make it big enough to cover all the buttons but I'm not sure how.
0
Creating a game with in game programmable AI I am looking to make a game where the player can access an in game terminal and then use this terminal to write AI logic in a programming language such as C or C , then they can compile the code and apply the AI to NPC characters. Of course if the code failed to compile error free then it would not be applied to the NPC. Mostly the code would be function calls with a few basic constructs available like int, float, bool etc. My question is how could I achieve this in say Unity or another game engine. Would I need to use a scripting language such as LUA or Python to create the AI or could I be done in real time on a separate thread in Unity somehow?
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
Setting the colour of a dynamically created tile does not work I have a function that takes in the position of a tile on a Tilemap and sets the colour. If I do not replace the tile with a dynamically created one, it works just fine. However, if I create a tile at runtime, set it's colour and add it to the tilemap, the tile does not change. In the preview window it appears black. The function can be found below private void CreateTile(Vector3Int tilePosition) var tempTile ScriptableObject.CreateInstance lt Tile gt () tempTile.flags TileFlags.None tempTile.color Color.green tilemap.SetTile(tilePosition, tempTile) Any help would be appreciated, I have spent a few hours on this problem. Thanks.
0
Instantiated prefabs dont trigger ontriggerEnter while prefabs created not on runtime, do I am new to unity and trying to make a bouble trouble game. I have enemy prefabs with BoxCollider with is triggered checked. I also have a shooting script. when I am trying to instantiate the enemy prefabs on runtime, they dont seem to trigger the OnTriggerEnter function, but if I am placing an Enemy prefab not ingame, it does trigger the funtion. I have no idea why. The on run time instantiate public class CreateBalls MonoBehaviour public Rigidbody prefab public Transform position1 void Awake() for (int i 0 i lt 1 i ) float random Random.Range( 45.08f, 44.41f) Vector3 vec new Vector3(random, position1.position.y, position1.position.z) Rigidbody ball Instantiate(prefab, vec, position1.rotation) as Rigidbody The funtion not being called public class DestroyBalls MonoBehaviour public Rigidbody potion public Transform posToSpawn private void OnTriggerEnter(Collider other) if (this.gameObject.tag quot Enemy quot amp amp other.gameObject.tag quot Bullet quot ) a code not relevent Any idea of why the funtion isnt being called? the bullets are tagged quot Bullet quot and the Enemies are tagged quot Enemy quot Update The funtion is triggered when colliding with another Enemy tagged, but not being trigged after collision with anyother tagged object Also, I have another component on the Enemy Prefab, which also instantiates enemies on run time and these trigger the function perfectly fine. very wierd. the code public Rigidbody ballToSpawn public Transform spawnPoint private void OnTriggerEnter(Collider other) if (this.gameObject.tag quot Enemy quot amp amp other.gameObject.tag quot Bullet quot ) if (this.gameObject.GetComponent lt Size gt ().size gt 1) Rigidbody small for (int i 0,y 1 i lt 2 i ,y 2) Vector3 vec new Vector3(spawnPoint.position.x y, spawnPoint.position.y, spawnPoint.position.z) small Instantiate(ballToSpawn, vec, spawnPoint.rotation) as Rigidbody small.gameObject.transform.localScale new Vector3(1, 1, 0) small.gameObject.GetComponent lt AutoMoveForBall gt ().GoToX this.gameObject.GetComponent lt AutoMoveForBall gt ().GoToX small.gameObject.GetComponent lt AutoMoveForBall gt ().GoToY this.gameObject.GetComponent lt AutoMoveForBall gt ().GoToY small.gameObject.GetComponent lt Size gt ().size this.gameObject.GetComponent lt Size gt ().size 1
0
Apply Secondary Normal Map to Standard Shader by Script I have a material with an existing normal map. I added a secondary normal map to represent damage via script. I assign to the appropriate texture property DetailNormalMap, assign the required keywords, DETAIL MULX2 NORMALMAP, and set a scale via DetailNormalMapScale. I have ensured there is a material in the resources folder with the same settings, to ensure that the variant is available in builds, though this shouldn't be an issue in editor. However, it does not show up, at least not initially If I do darn near anything with it in the editor, even alt tabbing, will cause the secondary normal map to show up I recall back in the day keywords were the issue, but I clearly have done that. I recall this working in the past. I am still using Unity 2018.4.6f1, so I would be surprised if there are any major changes. Thanks for your assistance.
0
Unity3D GUI what exactly it does when create controls and check their statuses? On unity3d website in the manual on this page http unity3d.com support documentation Components gui Controls.html I found an example of "GUI.changed" function usage(below). And it looks like it creates toolbar object on every frame. Am I right or not? GUI.changed example JavaScript private var selectedToolbar int 0 private var toolbarStrings "One", "Two" function OnGUI () Determine which button is active, whether it was clicked this frame or not selectedToolbar GUI.Toolbar (Rect (50, 10, Screen.width 100, 30), selectedToolbar, toolbarStrings) If the user clicked a new Toolbar button this frame, we'll process their input if (GUI.changed) print ("The toolbar was clicked") if (selectedToolbar 0) print ("First button was clicked") else print ("Second button was clicked")
0
Having trouble making game time pause and unpause I've been trying to make it where when the player does a certain task, the game's time will pause. When the player does another action, the game's time would unpause and continue. I had my code like so using UnityEngine using System.Collections using UnityEngine.UI public class timeScript MonoBehaviour uGUI Items public Text date public Text playerCash Times public static int week public static int month public static int year 1980 amount of cash public static int myCash 10000 public AlertBox alert public Text timeText bool timeActive true int time int day void Start() InvokeRepeating("Timer", 0, 1) public static void Timer() timeText.GetComponent lt Text gt ().text "W" week.ToString() "" year.ToString() playerCash.GetComponent lt Text gt ().text " " myCash.ToString() region YEAR Check if month equals 13 (allows for 12th month to be counted) if (month 13) year month 0 endregion region MONTH Check if week equals 5 (allows for 5th week to be counted) if (month 5) month week 0 endregion region WEEK Check if day equals 8 (allows for 7th day to be counted) if (day 8) week day 0 endregion region DAY Check if Time equals 5 (allows for 4 seconds) if (time 2) day time 0 else time endregion I tried using CancelInvoke(timeScript.Timer()) in another c file but all it did was give me an error that stated I couldn't convert from string to void.
0
Run some objc code very early in unity iOS game lifetime I want to hook up a crash reporting service to my unity iOS game. It's just one line of objC to add, as early into the app lifecycle as possible, but I'm not sure how to get it to run. I know I could make a native plugin and then call that from some Awake() function in C , but that's too late for my purposes. I'm not a native iOS developer, but I know enough to be dangerous. I have been able to google enough that I know I want something to with UnityAppController, probably preStartUnity(). But that's all. Has anyone got further resources on how to do this? Or another way, if I'm barking up the wrong tree? edit I'm on unity 4.6.
0
Creating a toggle button in unity3d Scene vs Scripting I am making my first GUI in unity, and I am not sure if should create the toggle buttons in the game scene by creating new UI elements or by scripting. Creating them in the game scene gives me more options but I have trouble to manipulate the input. Because of this I am scripting them in the monodeveloper but it seems more difficult to work the visual side (I am using a texture but can't get rid of the little box (that shows f the button is clicked or not). How do you make your toggle buttons and how do you develop your GUI? Any help appreciated.
0
Damping in Unity Shuriken Particle System Is there no damping functionality in Unity Shuriken Particle? "Velocity Over Lifetime" is different from damping. I try to find it on particle system, but can't. Or is there any other way to apply particle damping? I want to control each particle's velocity decrement? Update Add a poor art work )
0
Sprite won't change with direction I am making a top down Pacman game. I have two sprites one for facing up and one for facing left. When I press W, the sprite showing is still the one for when Pacman is moving left, but I want to see the up sprite instead. using System.Collections using System.Collections.Generic using UnityEngine public class pacman MonoBehaviour public int speed Vector2 dest public Transform points Start is called before the first frame update void Start() dest transform.position speed 25 Update is called once per frame void FixedUpdate() Vector2 p Vector2.MoveTowards(transform.position, dest, speed) GetComponent lt Rigidbody2D gt ().MovePosition(p) Check for Input if not moving if (Input.GetKey("w")) transform.position Vector3.MoveTowards(transform.position, points 0 .position, speed Time.deltaTime) gameObject.GetComponent lt SpriteRenderer gt ().sprite GameObject.Find("up").GetComponent lt SpriteRenderer gt ().sprite if (Input.GetKey("d")) transform.position Vector3.MoveTowards(transform.position, points 2 .position, speed Time.deltaTime) if (Input.GetKey("s")) transform.position Vector3.MoveTowards(transform.position, points 1 .position, speed Time.deltaTime) if (Input.GetKey("a")) transform.position Vector3.MoveTowards(transform.position, points 3 .position, speed Time.deltaTime) gameObject.GetComponent lt SpriteRenderer gt ().sprite GameObject.Find("left").GetComponent lt SpriteRenderer gt ().sprite
0
Flow effect to static water on a isometric city Hello everyone I want to give the idea that the river in my city is flowing but I am having an hard time to figure how. Do you have any idea of what I should look into to?
0
What does EventSystem.currentSelectedGameObject consider the current object to be? I've been working with UI in my project as of late and I can't figure out what Unity's event system is supposed to return for currentSelectedGameObject. if (EventSystem.current.currentSelectedGameObject ! null) Debug.Log(EventSystem.current.currentSelectedGameObject.name) With the code above I figured that it should return something when I'm moving the mouse across the various UI elements. Unity's documentation appears to be poor on this function stating The GameObject currently considered active by the EventSystem. maybe I'm just being stupid but does anyone know what triggers currentSelectedGameObject?
0
How to make sure two Tiles not overlap each other? I'm trying to make a Grid who will be easily convertible between 2D and 3D and I'm having a problem with overlapping prefabs in the case of the 3D generation. The thing is, the DataObjects (Tiles) actualy have inside them the prefab of the thing who must be in that tile, but the prefab is bigger than the Tile. As you can see in the image, i have 3 Tiles selected, Each Tile have a prefab and all of them have the same kind of prefab, they are in the scene highlighted by the orange borders right now in the image. Then you could imagine than, if the prefabs are equal between the 3 of them they should all have th same size, and that's exactly the case (i.e. in fact they have the same size) but the thing is they are overlaping each other, have that in consideration when looking at the image. So the question will be... How to make sure two Tiles not overlap each other? Based on a suggestion on working not with scale but pixels with units, I don't exactly how to do that, but searching on google make me try this, which actually doesn't work tile.tile GO.GetComponent lt Renderer gt ().bounds.size thisPrefab.GetComponent lt Renderer gt ().bounds.size It doesn't work because "bounds" is read only. Do you know a work around to solve this? Is there another way to achieve what I'm looking for? The idea is stop the overlapping, if you know a way to make one next to the other one, or even leave a gap between them in runtime, it will be also consider a valid answer. Thanks in advance. PS I'm using Unity 2017.1.0f3, scripting in C .
0
Unity's Profiler doesn't specify which of my methods take how much time? I'm working on a map generator, which is used in Awake(), so I couldn't see it in the profiler. So I created a new scene, where right clicking generates the map. Now I can see the generation process (Update method), but not the specific parts of it. Only GC.Alloc s, GC.Collect s and Mono.JIT s. Why?
0
Canvas UI elements out of place in Unity3d I placed all elements in the places I want to show in the Game mode, nevertheless, when I go to Game Mode they are shown in the wrong place as it was shown in the pictures (they go to the center). I tried different modes of render mode but no one seems to work in this case. I want the elements to be fixed in the window no matter monitor size.
0
Unity How can I enlarge the sprite to avoid the movement of the character when the pivot change? Changing the pivot to custom on all of the sprites is not a viable option for me Video showing the problem https youtu.be YpAdamkbhFA
0
Destroy a single list member im trying to destroy a single game object using the following script but it destroys all of them , not the ones I want. I want to destroy the ones that the transform that holds this script collides with. It's a 2D unity3d game btw. The script var keys List. lt Transform gt function OnTriggerEnter2D(coll Collider2D) for(var i 0 i lt keys.Count i ) Destroy (keys i .gameObject) I hope I was clear enough , don't hesitate to ask any questions. Thank you for your time.
0
Unity 2D Sprite Bending between Hinge Joints I've created a tentacle that consists of multiple game objects, each attached to eachother using HingeJoint2D's. Gameplay wise this multiple segmented approach is great because I can use Unity's built in physics, but it doesn't look very good art wise. Is it possible to 'bend' 2D sprites, so the tentacle segments look like they're attached to eachother? Or perhaps take a single image and bend it using splines of some sort? I would prefer to keep using multiple game objects to represent the tentacle.
0
Best way to handle tick based resource generation in an online multiplayer strategy game I'm building an online multiplayer strategy game. The game has no offline mode and requires syncing up to a server. Part of this game is constructing buildings which will generate resources each second. These resources would be generated whether the player is online or offline. If this was a purely offline game, this would be easy get the delta between when the app was closed and when it was opened again and multiply by resources per second and just fast forward everything. Since it's an online game, and other players can be affected by the resources an offline user has, these calculations have to occur on the backend. My question is if I have 10,000 players, each with 20 buildings generating resources on a per second basis, how on earth should I handle 200,000 things all at once and syncing to a database?
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 create transfer function for temperature in 2D space I am looking for ways that can transfer temperature from tiles to tiles in space such as in Rim World, when you click on a tile, it will display the temperature on that particular tile and you can regulate the temperature in a confine space by installing air conditioner. Wonder is there any method in unity that can perform such function? Would like to learn it by myself. I am new to programming so not even sure where should I start my search.
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
Unity unable to play audio clips simultaneously from within a coroutine I am using Unity 2017.3.1f1. I have created a co routine for a car engine controller which would play a car start sound once, and while it is fading, it would start a looping sound that would gradually increase its volume while the start sound is still playing. Here is what I have written public virtual IEnumerator PlayEngineSounds() float playtimeStarted Time.unscaledTime, startSoundLength startSound.clip.length startSound.Play() if (loopSound null) yield return new WaitUntil(() gt startSound.isPlaying) else while (startSound.isPlaying) var percent (Time.unscaledTime playtimeStarted) startSoundLength loopSound.volume percent loopSoundMaxVolume Debug.Log("Loopsound " percent, this) yield return null loopSound.volume loopSoundMaxVolume yield return null Basically I am taking the percentage of the start sound and I use that for the level of the loop sound. The more completely the start sound is played, the louder the loop sound should get. What I observe, is that my logged messages appear correctly in time, but the volume level of the loop sound is not affected. Then, when the start sound completes, the loop level gradually increases its volume. It behaves as if the volume updates are "delayed" and executed after the start sound is finished, instead of playing both simultaneously. The startSound and loopSound are separate AudioSource components, that reside in different game objects within the hierarchy of my vehicle. I am invoking the PlayEngineSounds corouine from my Start method like this internal void Start() StartCoroutine(PlayEngineSounds()) other code ...
0
Terrain (mesh) textures in Unity blurry? I've created a 3D mesh in blender which will be used as a terrain in Unity. Additionaly, I created a 900x900 texture which I'd like to apply as material to the mesh. However, unlike with the normal Unity terrain, the material is only blurry unrecognizable, not matter how many times I repeat the texture what import settings I set for the texture. Some googling brought up that it may have to do something with the shader, but I tried many with no results. current result texture
0
How do I run code for a period of time and then return to normal behavior? i wanna run a code for my special power for five seconds only and then return to my normal working. when that power activates i am changing my player's material and i wanna return to my old material after those five secs are over. this is the code i tried void Start () transform.GetComponent lt Renderer gt ().material.mainTexture texts 0 void Update () if (condition) for (int t1 0 t1 lt 5 t1 (int)Time.deltaTime) transform.GetComponent lt Renderer gt ().material mats 0 transform.GetComponent lt Renderer gt ().material.mainTexture texts 0 this code breaks the game i think because unity is freezing when the condition is being met.
0
Why is my player not giving a knock back when it stays at the right side of the enemy? So, I have this problem I am facing, for some reason my player does not get a knockback when it stays at the right side of the enemy but when it stays at the left side it gives a knockback. What's the problem? PLAYER MOVEMENT void Movement() THIS IS FOR WALKING if (isControlesEnabled) moveInput Input.GetAxisRaw("Horizontal") runSpeed myBody.velocity new Vector2(moveInput, myBody.velocity.y) PLAYER KNOCKBACK private void OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.CompareTag("Enemy")) health 0 if (health lt 0) gameObject.SetActive(false) else ContactPoint2D contactPoint collision.GetContact(0) Vector2 playerPosition transform.position Vector2 dir contactPoint.point playerPosition dir dir.normalized myBody.velocity new Vector2(0, 0) myBody.inertia 0 isControlesEnabled false Invoke("EnablePlayerControles", controlesDisablePeriod) myBody.AddForce(dir knockBackForce, knockBackForceMode) private void EnablePlayerControles() isControlesEnabled true
0
Unity too many batches There are 64k cubes, 64k 1 's materials are assigned to sharedMaterial of first cube. But unity is not batching them together. Only cubes themselves are batched. Static color(but different per cube) Dynamic position and rotation per cube How can I force unity to batch them all so it sends all cube data with only an array then draw once instead of drawing 64k times? Each cube has a constructor as public class Test MonoBehaviour public static System.Random r get set Use this for initialization public static Material m null void Start () if (r null) r new System.Random() sayac if (m null) m GetComponent lt Renderer gt ().sharedMaterial else GetComponent lt Renderer gt ().material m GetComponent lt Renderer gt ().material.color new Color((float)r.NextDouble(), (float)r.NextDouble(), 1) var mesh GetComponent lt MeshFilter gt ().mesh var vertices mesh.vertices var colors new Color vertices.Length var i 0 while (i lt vertices.Length) colors i new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble()) i mesh.colors colors mesh.UploadMeshData(false) mesh.Optimize() and they are instantiated from a cube as for(int i 0 i lt 1024 64 i ) var pos new Vector3(i 64, (i 64) 64, (i 4096) 64) pos 2.5f var cu Instantiate(ref cu, pos, Quaternion.identity) cu .name "cube " i After deleting 'material.color' lines, batching has started. But now cubes are not easily seen as with different colors. I need them different colored but not changing. Static color but different per cube. How it looks now its not easy to see individual cubes. public class Test MonoBehaviour public static System.Random r get set Use this for initialization public static Material m null void Start () if (r null) r new System.Random() sayac if (m null) m GetComponent lt Renderer gt ().sharedMaterial else GetComponent lt Renderer gt ().material m
0
UI background animation makes camera render beyond canvas, need fix? I have a background animation for a menu where I have to make the background larger than the canvas and drag it over it. Even though I am using a panel the same size as the canvas as a mask, this causes the camera to render beyond the canvas. How can I get this same effect while only rendering what's on the canvas? w o mask (so you can see how big this background is) w mask running in editor (looks good) running build of the game from executable (camera shows more than it should but nothing was changed) The camera bounds are fixed to the canvas, as it should be, if I remove the animated background, so that is the major cause. (BTW, I know the gifs look crappy but the animation is seamless I just had to crop the gifs to reduce file size.) Also, you guys might not be able to see, but the tiling pattern has a slight white border where the tiles meet (the sprite it uses is only like 227x227 on "repeat"), does anybody know how to avoid that? UPDATE 1 12am PST upscaling turd texture to 256x256 eliminates white border, as suggested by trollingchar.
0
Calculating gameObjects hit by a directional light source I am trying to figure out in my current game whether a gameObject is lit by a directional light or not. Below is my image inside the Unity game engine As my game runs around a Day Night cycle, I need to constantly check which hex tiles are lit and which are not. I am using one directional light source in my scene and I am rotating it around the x axis for the day night cycle. Currently, I am using the dot product to calculate if the tile is lit by the directional light but its not very accurate. Vector3 forward Light.transform.TransformDirection(Vector3.forward) float dot Vector3.Dot(forward, (tile.transform.position Light.transform.position)) Is there a better way to do check this inside Unity??
0
Unity saving and loading of images in game So I'm planning out this game for unity but I don't know how feasible it will be with all of the image loading and saving. I've worked with some other coding, and while I am in the process of learning C and Unity I don't have a very informed base for my opinion. Basically the game will be inspired by the base mechanics of the Chaotic tv show where you have to adventure to take scans of creatures and these scans will be used in another aspect of the game as cards. The creatures will be randomly generated. The problem is I want the scans to be like actually taking a picture (A picture that includes all the stats of the creature). This means I want to be able to save a picture of the scene with the creature in it as well as the stats associated with said creature which means I would have to have some sort of data base capable of storing hundreds (Possibly thousands if you include player made and prebuilt cards) of cards and the data associated with them. The scans take a picture and record the stats of the creature at that point in time so they're only highly usable for the game when the creature is in near perfect condition (Not yet defeated or attacked). I would have to be able to store scans of creatures, scans of the environment, and possibly scans of items found while adventuring. I think it would work best if only a small picture of the actual scene is saved with the stats instead of the full card and the stats, with it rebuilding the card each time it's loaded into memory. The small picture would also cut down on storage space (Possibly so small as to be high res pixel art) Would it be unrealistic to save all of this data? Aswell, does Unity C even have the capabilities to take screenshots from specifically defined areas of the screen players view and then reuse them in another area of the game instead of saving them in some predefined screenshot area? (This game will be entirely offline so no data will need to be transferred to a different system) (Said game will also be 3d with the card playing area in 2d)
0
Sampling procedural texture generated in shader? We have a custom Unity surface shader which generates some procedural patterns. However we are getting very bad moire effects when the pattern frequency is too high (made worse by distance, surface angle). I would like to apply some kind of blur on the texture to reduce this moire effect. All of the shader blur examples I can find rely on sampling surrounding pixels from the texture bitmap. Since we've generated the pattern procedurally per pixel, such a bitmap doesn't exist. Does anyone know how we might introduce some kind of blur effect in this case, to reduce the moire? Thank you.
0
Runtime Issues on 144Hz Monitors I've recently finished my first ever Unity game. The game runs okay in my end but two of my friends had issues with the game. They both have 144hz monitors and the issues are solved when they lower the refresh rate to 60Hz. The problems are that any object who has a velocity depending on Time.deltatime, it gets halved. Is there a way to fix this on code so that nobody has to reduce their refresh rate when playing? Here is an example code of a snowball projectile's behaviour. The snowball usually stays alive for 3f seconds and that allows him to go across the whole screen but in 144hz runtime, the snowball goes really slow and it does not last enough to even get across the half of the screen. using System.Collections using System.Collections.Generic using UnityEngine public class Snowball MonoBehaviour SerializeField private float speed 20f SerializeField private Rigidbody2D rb SerializeField private GameObject impactEffect Start is called before the first frame update void Start() Destroy(gameObject, 3f) void Update() rb.velocity transform.right speed Time.deltaTime 75 void OnTriggerEnter2D(Collider2D hitInfo) if(hitInfo.CompareTag( quot Player quot ) hitInfo.CompareTag( quot Enemy quot )) Destroy(gameObject) Instantiate(impactEffect, transform.position, transform.rotation) Here is my game if anyone is interested in further examination itch.io link
0
Periodic updates of an object in Unity I'm trying to make a collider appear every 1 second. But I can't get the code right. I tried enabling the collider in the Update function and putting a yield to make it update every second or so. But it's not working (it gives me an error Update() cannot be a coroutine.) How would I fix this? Would I need a timer system to toggle the collider? var waitTime float 1 var trigger boolean false function Update () if(!trigger) collider.enabled false yield WaitForSeconds(waitTime) if(trigger) collider.enabled true yield WaitForSeconds(waitTime)
0
How to play a movie on top of a webcam texture I've been through the Unity docs, searched here, and on stackoverflow I have not found any good information about using the WebCamTexture for my purposes. So here goes, how do I play a movie asset such as an mp4 clip so that it appears to be on top of the captured webcam image? Lets assume the movie is semi transparent.
0
Trouble Positioning Object In World I have a lightning effect that travels from point A to point B, I am having trouble placing placing point B correctly. As you can see from the object hierarchy the points (LightningStart, LightningEnd) are nested 3 levels deep. parentReaction.affectorWidget.transform.positionis the position I would like the object to be at. As you can see below I have tried setting the position equal to the other widgets transform, I have also tried using transform.InverseTransformDirection and transform.TransformDirection in varying combinations, I have tried many options the code below is just me going back to basics to see what I missed. I am not sure even which object I am supposed to call TransformPoint from, the Widget with the effect )(Point A) or the Widget at Point B? Given the above scenario how would I position LightningEnd so that is at the same position as parentReaction.affectorWidget.transform.position? I understand this is a very common question and I have read many previous questions related to this but two hours later, I would just like to know how its done so I can understand where I am getting this wrong. Thank you. Edit controller is the Widget Running this effect, since it spawns as a child of this I dont need to worry about its position. public override IEnumerator Do(Widget controller, WidgetReaction parentReaction) effect controller.GetComponent lt Widget Effect Comp gt ().AddEffect(effect) while (true) start effect.effectPrefab.transform.Find("LightningStart").transform end effect.effectPrefab.transform.Find("LightningEnd").transform Debug.Log("End Position " effect.effectPrefab.transform.Find("LightningEnd").transform.position) Debug.Log("Widget World Pos " controller.transform.position) Debug.Log("Widget Local Pos " controller.transform.localPosition) Debug.Log("AffectorWidget World Pos " parentReaction.affectorWidget.transform.position) Debug.Log("AffectorWidget Local Pos " parentReaction.affectorWidget.transform.localPosition) effect.effectPrefab.transform.Find("LightningEnd").transform.position parentReaction.affectorWidget.transform.position Debug.Log("End Position " effect.effectPrefab.transform.Find("LightningEnd").transform.position) yield return new WaitForSeconds(2f) public class WidgetEffect ScriptableObject public string effectName public GameObject effectPrefab public WidgetEffect AddEffect(WidgetEffect widgetEffect) if (!activeEffects.ContainsKey( widgetEffect)) GameObject go Instantiate( widgetEffect.effectPrefab) go.transform.parent effectContainer.transform go.transform.position Vector3.zero go.transform.localPosition Vector3.zero activeEffects.Add( widgetEffect, go) return widgetEffect return null Edit Removed Extended Explanation not related to initial question! ! enter image description here
0
Parent Child position mathematics What is the math theory when a child object moves with the parent transform? I am doing an angle indicator which shows a field of view, which works fantastic when the angle is static. But I cannot get the field of view indicators to play nice with the angle changing. Everytime I change the angle, the indicators are reset to default positions and then the direction indicator and FoV indicators are out of sync. There is of course a ghetto way of resetting the whole thing when changing the angle, but I'd prefer not to do it that way. The red circles are the points which are used to draw the FoV lines and they are childed to the white sphere. If the angle is not modified after start they follow the white sphere nicely and show the FoV correctly. Here is how it looks after trying the dynamic angle changing. The FoV lines should be pointing to the right and the white sphere should be in the middle. Currently I am changing the red circles' position based on the angle given(transform is the green square in the middle.) leftAngle.transform.position transform.position new Vector3(Mathf.Cos(firstLineRendererAngle Mathf.Deg2Rad), 0, Mathf.Sin(firstLineRendererAngle Mathf.Deg2Rad)) 10 rightAngle.transform.position transform.position new Vector3(Mathf.Cos(secondLineRendererAngle Mathf.Deg2Rad), 0, Mathf.Sin(secondLineRendererAngle Mathf.Deg2Rad)) 10 How do I add the position of the FoV direction sphere to emulate parent child relationship with the objects?
0
Initiated a animation in unity via use of an animator component I've written a coroutine that starts an animation. GameObject.FindWithTag(names number ).GetComponent lt Animator gt ().StartPlayback() This is the line of code that I wrote to start the animation. However, the animation does not start. I've even replaced the GameObject.FindWithTag(String) method with a reference to the actual object by declaring a GameObject in the script and setting it to a particular object in Unity's IDE. The animation still didn't start. Also, I must say the GameObject does have an animator component, you can see it in the inspector panel. No error messages can be seen in the console during play mode. What can I do to get the animation to play when I want it to play.
0
How do I draw a line from a set of points in unity to use as terrain in a 2D game? I'm trying to make a 2D game in unity. My terrain is randomly generated and what I'm trying to do is make a bunch of points with different x coordinates and then draw a line through them to use as my ground terrain. Originally I wanted to make a polygon out of the points by specifying two additional vertices which would basically be the camera bounds and fill the whole thing in, but I'm not sure that's feasible, so I'll settle for just having a line as a platform. How would I go about doing this?
0
Apk file installes two instances of a Unity game I created an apk in Unity (4.6) and when I install that apk on the device it creates 2 instances of the game (2 icons are visible in the screen). Both icons start the same game, and when I uninstall the game it removes both icons. In previous builds this didn't happen, so I'm assuming that the changes I made to the Android Manifest have something to do with it. I included the Game Analytics SDK and it caused some problems when I tried to build the game for Android (with the message that the incompatible manifests can't be merged). So I commented out the part of the manifest that was causing the problem and now I have the problem with multiple instances of the game. I did some research and found that this happens when there are multiple activities in the manifest that are marked as LAUNCHER this is not the case in my app, only one activity has that property. Also, as far as I can see, there is only one AndroidManifest.xml file in the Unity project (only one appears when I type it in the search). This is the part of the manifest that I needed to change lt activity android name "com.unity3d.player.UnityPlayerActivity" android label " string app name" android configChanges "fontScale keyboard keyboardHidden locale mnc mcc navigation orientation screenLayout screenSize smallestScreenSize uiMode touchscreen" gt lt activity gt lt ! lt activity android name "com.unity3d.player.UnityPlayerNativeActivity" android label " string app name" android configChanges "fontScale keyboard keyboardHidden locale mnc mcc navigation orientation screenLayout screenSize smallestScreenSize uiMode touchscreen" gt lt meta data android name "android.app.lib name" android value "unity" gt lt meta data android name "unityplayer.ForwardNativeEventsToDalvik" android value "false" gt lt activity gt gt If the commented out part is included, Unity throws the "incompatible manifest merge" error in the building process Error Temp StagingArea AndroidManifest main.xml 4, MyGame Temp StagingArea android libraries unityads AndroidManifest.xml 19 Trying to merge incompatible manifest application activity name com.unity3d.player.UnityPlayerNativeActivity element UnityEditor.HostView OnGUI() Did anyone have any similar problems and how did you fix it? Thanks
0
IOS OpenGl transparency performance issue I have built a game in Unity that uses OpenGL ES 1.1 for IOS. I have a nice constant frame rate of 30 until i place a semi transparent texture over the top on my entire scene. I expect the drop in frames is due to the blending overhead with sorting the frame buffer. On 4s and 3gs the frames stay at 30 but on the iPhone 4 the frame rate drops to 15 20. Probably due to the extra pixels in the retina compared to the 3gs and smaller cpu gpu compared to the 4s. I would like to know if there is anything i can do to try and increase the frame rate when a transparent texture is rendered on top of the entire scene. Please not the the transparent texture overlay is a core part of the game and i can't disable anything else in the scene to speed things up. If its guaranteed to make a difference I guess I can switch to OpenGl ES 2.0 and write the shaders but i would prefer not to as i need to target older devices. I should add that the depth buffer is disabled and I'm blending using SrcAlpha One. Any advice would be highly appreciated. Cheers
0
unity apply item animation to character I'm trying to change the attack animation of my player in relation to the attack animation for the item he has in his hand. For example, the default attack animation of my player is puching and once he picked up a sword I want his attack animation to be sword attack, for a hammer a hammer attack, etc .. I searched a lot on the internet but didn't find much, I saw a few post talking about AnimatorOverrideController but I'm not sure if it's what I need because it overrides every animation clip of the AnimatorController. In my case I just want to change the attack Animation Clip. So if you cloud give me some tips about the right way to do it, I would really appreciate because I'm a bit confused. Thanks Edit BTW, I'm in Unity 3d
0
Why is Unity UI Image color not being animated? Animation is changing the color of an UI Image but the color only changes only in the inspector but not Game Scene view. In this video I demonstrate the problem clearly.
0
Design pattern for menu transitions in C (Unity) I am working on my first project in Unity using C and I am currently trying to design a menu system that does the following sequence of events when a user clicks a button Button does some effect for some milliseconds (for example, flashes) Menu1 does its closing sequence for some milliseconds (for example, buttons fly off screen) Menu2 does its opening sequence for some milliseconds (for example, buttons fly on screen) The exact animations of the UI elements don't matter for the purpose of my question. So far, the only design pattern I've found to achieve this kind of sequence is by using coroutines. So I ended up with something like the following void OnStartButtonClick() StartCoroutine( OnStartButtonClick()) IEnumerator OnStartButtonClick() yield return start button.GetComponent lt ButtonController gt ().DoEffect() StartCoroutine(MenuTransition(main menu, data menu)) IEnumerator MenuTransition(GameObject menu1, GameObject menu2) main menu to data select if (menu1 main menu amp amp menu2 data menu) yield return CloseMainMenu() yield return OpenDataMenu() public Coroutine OpenMainMenu() return StartCoroutine( OpenMainMenu()) IEnumerator OpenMainMenu() main menu.SetActive(true) main menu opening sequence here yield return null public Coroutine CloseMainMenu() return StartCoroutine( CloseMainMenu()) IEnumerator CloseMainMenu() main menu closing sequence here main menu.SetActive(false) yield return null public Coroutine OpenDataMenu() return StartCoroutine( OpenDataMenu()) IEnumerator OpenDataMenu() data menu.SetActive(true) open data menu sequence yield return null public Coroutine CloseDataMenu() return StartCoroutine( CloseDataMenu()) IEnumerator CloseDataMenu() data menu closing sequence here data menu.SetActive(false) yield return null And the code on my button likewise utilizes coroutines public Coroutine DoEffect() return StartCoroutine( DoEffect()) IEnumerator DoEffect() imagine some code that does the effect yield return new WaitForSeconds(1f) This seems to work well enough and allows me to completely control the effect gt close gt open sequence. But it's getting a bit unwieldy as I build it out for more menus and transitions between them, resulting in a ton of methods with Coroutine return type wrapping IEnumerators (which I've been prefixing with underscore). I can't help but feel like there's a more elegant way to do this, and that I am using coroutines as a crutch ... So my question is whether there is a more suitable or efficient design pattern that can allow me to achieve the kind of sequencing of events that I want without the proliferation of Coroutines amp IEnumerators? Or are Coroutines amp IEnumerators exactly the devices to solve this kind of problem?
0
Smooth Rotate Object While Orbiting I am working on a 3D game where you can control an object that orbits a sphere with an on screen virtual joystick. So far I have that part working, but the object follows the joystick angle perfectly and "snaps" into the angle, rather than smoothly interpolating to the new angle of the joystick. I would like to redo this and have it interpolate the values. I have it very close using the following code angle Mathf.Atan2(joystickY, joystickX) Mathf.Rad2Deg Quaternion targetRotation Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, currentAngle) transform.rotation Quaternion.Slerp(transform.rotation, targetRotation, TURNING SPEED Time.deltaTime) This works great on one side of the sphere, but as soon as I move the object halfway around the sphere, the rotation is now mirrored and the object rotates 180 degrees until it reaches the other side again. What am I missing here? I am basically trying to calculate the joystick angle, then apply that to the object as it orbits, but do this smoothly using slerp. Let me know if you need any further information. Thanks!
0
Unity DontDestroyOnLoad not always working after Android build I've been using this small script as a component to any object I want to not be destroyed at scene loading. public class DontDestroy MonoBehaviour void Start() DontDestroyOnLoad(gameObject) It has been working fine. It works for my GameOver canvas which I've been using for a long time whilst making the game. Today I added the same script to a new AndroidControls Canvas I made. In the Editor it worked fine. Then I built it for Android to run on my physical phone (Galaxy S10). It gave me a Null exception. It turned out to be caused by the AndroidControls Canvas being destroyed between scene loading (even though as I say, I tested in Editor for a few runs and it didnt get destroyed). And it gets a little weirder because after the attempted build to APK, and fail on physical device, it then failed to work in the editor. It continues to not work in each test after this in Editor, however if I remove the component and add it again, the entire process then repeats. Please help as I don't have a clue how to start fixing this. The only thing I can imagine it being wrong is it started as soon as I used this script on two canvas's simultaneously. (I highly doubt I am correct but it's the only thing I could notice at all that might be causing this). This picture actually shows my DontDestroy component is attached to Canvas AndroidControls, but in the Hierarchy you can already see that it is not in the DontDestroyOnLoad section (excuse the pink overlay for play mode) Maybe relevant, here are some of my specs Win 10 Unity 2020.3.5f1 (Just downloaded NDK SDK for Android today via Unity Modules) Android 11 (Samsung Galaxy S10)
0
Using 4096 4096 background image in uinty tk2d I am new to Unity and I am developing a game using unity its a 2d game i am using tk2d framework. I have a big background image(4096 4096) how can I load this background so only visible part of the background has to be rendered so it wont effect the performance. How can I achive this in unity amp tk2d?
0
Unity Animated Player Character Rotation Glitch I was wondering if anyone experienced this issue in Unity with Mecanim animated characters ... I have an animated player character with a third person camera control (Game Camera from the asset store, even though I think it isn't really related) and if the character is standing at the default y rotation angle I can orbit around her with the camera and she will always face the same direction, as it should be. But if the character stands with an arbitrary other transform y rotation (for example 90.0001 or 180, etc.) and I orbit around the character, the character's Y rotation is ever so often randomly changed. I don't know what changes the Y rotation. Game Camera doesn't touch it as long as I don't move the character so I suppose it is related to Mecanim, even though i'm not sure about that either. I was hoping somebody has more familiarity with this issue and know what causes this. This glitch is definitely a problem in gameplay.
0
Unity2D move rigidbody object with collision How do I move and collide my object (position given by touch or click), by Using rigidBody2D.MovePosition i can only teleport my character, and by using velocity, my character keeps moving, I want him to stop at the position given Ilustrations
0
GetMouseButtonUp TouchPhase.Ended doesn't work properly I'm trying to make a game where your tap doesn't count until you've released your click, or stop tapping. The weird thing is, it doesn't work in game, but it works for animation. public class Swipe MonoBehaviour public Animator anim public bool tap, swipeUp, swipeDown, swipeLeft, swipeRight, hold public bool isDragging false public Vector2 startTouch, swipeDelta public float animTime public Life life private void Update() tap swipeUp swipeDown swipeLeft swipeRight false anim.SetBool("Hold", isDragging) region Standalone Input if (Input.GetMouseButtonDown(0)) isDragging true startTouch Input.mousePosition Debug.Log("Tapped") else if (Input.GetMouseButtonUp(0)) tap true isDragging false Reset() endregion region Mobile Inputs if (Input.touches.Length gt 1) if (Input.touches 0 .phase TouchPhase.Began) tap true isDragging true startTouch Input.touches 0 .position else if (Input.touches 0 .phase TouchPhase.Ended Input.touches 0 .phase TouchPhase.Canceled) tap true isDragging false Reset() endregion calculating the distance swipeDelta Vector2.zero if (startTouch ! Vector2.zero) if (isDragging) if (Input.touches.Length gt 0) swipeDelta Input.touches 0 .position startTouch else if (Input.GetMouseButton(0)) swipeDelta (Vector2)Input.mousePosition startTouch did we cross the deadzone? if (swipeDelta.magnitude gt 125) which direction? float x swipeDelta.x float y swipeDelta.y if (Mathf.Abs(x) gt Mathf.Abs(y)) left or right if (x lt 0) swipeLeft true else swipeRight true else Up or down? if (y lt 0) swipeDown true else swipeUp true region Animation if (Tap) anim.SetTrigger("Tap") if (SwipeDown) anim.SetTrigger("Down") if (SwipeUp) anim.SetTrigger("Up") if (SwipeLeft) anim.SetTrigger("Left") if (SwipeRight) anim.SetTrigger("Right") endregion public void Reset() startTouch swipeDelta Vector2.zero isDragging false public Vector2 SwipeDelta get return swipeDelta public bool Tap get return tap public bool SwipeUp get return swipeUp public bool SwipeDown get return swipeDown public bool SwipeLeft get return swipeLeft public bool SwipeRight get return swipeRight
0
Unity Re import doesn't re import fbx So I have an fbx file with animations and materials on it. Simple stuff. But when I change something on the fbx, like adjusting some animation, then re export as fbx, Unity does not re import the fbx when I do RMB gt Re Import. It shows the loading bar but doesn't actually effect the current mesh by re importing. Is this normal? Is there a way to re import the fbx while keeping the modification I made on the mesh. Like, I changed the Scale Factor and some other things, so I want to keep these while re importing.
0
Unity Raycast not hitting to BoxCollider2D objects I'm working on 2D and I have a Quad as background. And some wall sprites over this quad I'm instantiating wall prefab sprites over quad when user click to somewhere. But I don't want to instantiate a wall over another wall, so I'm sending a ray from camera to click point and if hit object is a wall object I won't instantiate. Here my code RaycastHit hit Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) Physics.Raycast(ray, out hit,Mathf.Infinity) If it hits ground, not another objects (like walls) if(hit.transform.name "GroundQuad") Instantiate (wall, Input.mousePosition, Quaternion.identity) But it's still creating wall objects. Tried Debug.Log() to print hitted object's name to console and moved pointer all over game screen, it's always GroundQuad. So ray not hitting to wall objects. Can you tell me what is I'm missing? Is it a problem with Layer Collision Matrix ?
0
How to hide player when in Shadow using Unity 2D Light System? I have been looking for this for a couple of days now and cant find an answer how can I hide a player when they are in the shadow when am using Unity 2D Light System? I know I can choose not to cast light on objects, but when I do it still shows the object in the shadow. What am looking for is hiding the player completely when they are in shadow, and when the light hits them it would reveal the player. This effect is in the game Among Us, I know that they are using some sort of shaders and they didn't have 2D light when they were developing it. So am assuming this would be a shader as well where it would reveal the player when they are in the light and hide them when they are in the shadow. Below are pictures of what I have and what I want it to look like. This is what I have in Unity So you can see that the player is not hidden in the shadows, but rather its blacked out. But this is what am looking to recreate You see how the top half of the body which is in the shadow is hidden while the bottom half is revealed because its in the light? This is the effect that I want to recreate. Is there some sort of Shader or code that can do this? I really been looking for something like this for so long and couldn't find it. Any help will be really appreciated.
0
How can I communicate user information from a website to a hosted Unity game? I have a Ruby on Rails website running which provides a log in system and dashboard for users. I am building a small game in Unity which is much like an inventory management system. But, the inventory is specific to a user and the user can make changes to it. The user sees the game as a part of his dashboard. What I'd like is for the moment the user lands on his dashboard, the Unity game should load with the inventory of the signed in user. How can I get this user information from the Ruby dashboard over to Unity?
0
Unity Simple pass through geometry shader I would like to implement a geometry shader that does nothing, just for the purpose of learning and to go ahead with that and do something useful with it. I currently have A compute shader creating "particles". A vertex shader doing the transformation A fragment shader... This is the shader file StructuredBuffer lt float3 gt particles struct fsInput float4 pos SV POSITION fsInput vert(uint id SV VertexID) fsInput fsIn float3 worldPos particles id fsIn.pos mul(UNITY MATRIX VP, float4(worldPos, 1.0f)) return fsIn maxvertexcount(1) void geom(point fsInput p 1 , inout TriangleStream lt fsInput gt output) fsInput fsOut (fsInput) 0 fsOut.pos p 0 .pos output.Append(fsOut) float4 frag(fsInput fsIn) COLOR return float4(1.0, 0.2, 0.2, 1) I'm drawing my particles with this call Graphics.DrawProcedural(MeshTopology.Points, NUM PARTICLES) In my understanding, which is quite limited due to the perfect documentation of geometry shaders, my geometry shader should do nothing. Just forward the points to the fragment shader. However, if I use that shader (comment in those lines), I wont see my particles anymore. Without the geometry shader, I can see every particle. So the first question is, where is the error? The second question is Can I, starting with points and using the geometry shader, go from points to a, for example, cube? Or should I do it in the compute shaders? But if so, which MeshTopology should I use to draw the data from the compute shader as Cube, Sphere, etc...? Thank you for help!
0
Change width and height of 2D object based on pixel size and count I'm working on a shooting simulator with shooting goals that need to be in real world size. I know the certain size of screen display and pixel counts. Is there anyway to change their size based on screen information? let me explain more about question. its a real shooter simulator with real guns. image of unity simulation is projected on a wall or... by a video projector. I want to scale goals as real ones. I know size of screen and even size of every pixel. so I want to scale my rectangular goals with size of real ones. I think the question now is obvious
0
Null Reference Exception error occurs when trying to override AndroidManifest file in unity? So I Created A manifest file in Assets Plugin Android . The File contains lt ?xml version "1.0" encoding "utf 8"? gt lt manifest xmlns android "http schemas.android.com apk res android" gt lt activity android name "com.unity3d.player.UnityPlayerActivity" android windowSoftInputMode "stateHidden" gt lt activity gt lt manifest gt Error Occurs when building NullReferenceException Object reference not set to an instance of an object UnityEditor.AndroidManifest.SetApplicationFlag (System.String name, Boolean value) UnityEditor.AndroidManifest.SetDebuggable (Boolean debuggable) I followed the docs from here, about Overriding the Android Manifest. The apk builds fine when the manifest is removed. Complete Error NullReferenceException Object reference not set to an instance of an object UnityEditor.AndroidManifest.SetApplicationFlag (System.String name, Boolean value) UnityEditor.AndroidManifest.SetDebuggable (Boolean debuggable) UnityEditor.Android.PostProcessor.Tasks.GenerateManifest.PatchManifest (UnityEditor.Android.PostProcessor.PostProcessorContext context, System.String manifest) UnityEditor.Android.PostProcessor.Tasks.GenerateManifest.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (BuildPostProcessArgs args, UnityEditor.BuildProperties amp outProperties) UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTargetGroup targetGroup, BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at C buildslave unity build Editor Mono BuildPipeline PostprocessBuildPlayer.cs 286) UnityEngine.GUIUtility ProcessEvent(Int32, IntPtr) UNITY 2018.3.4f1
0
Need Help with Hovering Mouse Code I am new to Unity and C . I have a script here for a card game where my card is supposed to move up and down when the pointer is hovered over the card. But when my point hovers over each card, they all move up together and not separately. They also move when they touch other UI elements, regardless of what they are. I am doing something wrong but I don't know what. Here is my code My Codes I needs help on. using UnityEngine using System.Collections using UnityEngine.EventSystems public class Mouse Detector Temp MonoBehaviour public bool hovered Use this for initialization void Start () hovered false Update is called once per frame void Update () This checks to see if you are hovered over. if (EventSystem.current.IsPointerOverGameObject ()) Debug.Log(gameObject) if (hovered false) transform.Translate(0,10,0) hovered true else if (hovered true) transform.Translate(0, 10,0) hovered false Additional Information This code is run UI elements that are part of a Canvas (only way to do it, so that should be obvious).
0
Is it possible to tell Unity3d to ignore part of its hierarchy? One aspect of the game I'm making is each level is made up of room objects, which contain the sprites, physics objects and so on. When you enter a level the whole level is deserialsed and loaded into memory but only the room you are currently in is considered, nothing else is drawn, updated or whatever. I was wondering how I would achieve this in Unity3d. I can imagine having a hierachry with lots of rooms with the various room contents as children, can I tell unity to ignore everything (for updating, drawing, physics and so on) in the hierarchy but the current room and its children?
0
Collision from the underside of a cylinder (Unity C ) A quick introduction to my problem at the moment I am currently having trouble with checking whether or not a cylinder is grounded. I am using a mesh collider (octagonal prism) as my main collider for the object, however I can't seem to get a reliable ground detection beneath it. I have tried using a trigger and raycasting, but neither seem to work correctly. It would be a great help if you could either provide a method of correctly raycasting the cylinders base, or an alternate method (bearing in mind the object rotates on all axis). Many thanks in advance. (terrible diagram below)
0
Plugins for creating and styling custom Editor Windows like C C Form Designer or Web Inspector ? Unity3d allows to construct window with custom UI. Just need to use EditorGUI EditorGUILayout classes and their static methods. Example of custom window The problem is that all the components have to be added manually via script. Then need to save, switch to Editor, wait for little compile things, and then we can see the result. In web development people use Web Inspector (for example, we can press F12 in chrome, Tab Elements Styles). We can add all needed properties to element and can see the result in real time. EDIT. another example (better than previous) we know C winFormApp, C MFC e.t.c, which has form designer. We can choose any elements and set their properties It would be nice to have similar plugins for Unity So. Does Unity3d have similar tools, utilities, plugins? Utilities to inspect code and editing styles (position, margin, padding, background, width, height, color e.t.c.)?
0
Get the current time of animation using script Unity3d I want to know the current time of the played animation using script in Unity3d. I tried using currentState.normalizedTime but this time is not the time of the animation, like it's the time of the runtime I think. Any advice please?
0
When I shoot from a gun while walking, the bullet is off the center, but when stand still it's fine. (Video Included) I am making a small project in Unity, and whenever I walk with the gun and shoot at the same time, the bullets seem to curve and shoot off 2 3 CMs from the center. When I stand still this doesn't happen. This is my main Javascript code script RequireComponent(AudioSource) var projectile Rigidbody var speed 500 var ammo 30 var fireRate 0.1 private var nextFire 0.0 function Update() if(Input.GetButton ( quot Fire1 quot ) amp amp Time.time gt nextFire) if(ammo ! 0) nextFire Time.time fireRate var clone Instantiate(projectile, transform.position, transform.root.rotation) clone.velocity transform.TransformDirection(Vector3 (0, 0, speed)) ammo ammo 1 audio.Play() else I assume that these two lines need to be tweaked var clone Instantiate(projectile, transform.position, transform.root.rotation) clone.velocity transform.TransformDirection(Vector3 (0, 0, speed)) I just started Unity, and I might have a difficult time understanding some things. EDIT Here is a video http www.screenr.com 2pxH (If there are any more mistakes in my code, feel free to edit it.)
0
Why I cant change the GUILayout.Button color to green when click on a button? I used a break point and it's getting to the line style.normal.textColor Color.green But not changing the color of the clicked button. And there are no any errors or exceptions. using System.Collections using System.Collections.Generic using System.Diagnostics using System.Linq using UnityEditor using UnityEngine using System.IO public class Manager EditorWindow MenuItem("Tools Manager") static void Manage() EditorWindow.GetWindow lt Manager gt () private void OnGUI() var style new GUIStyle(GUI.skin.button) style.normal.textColor Color.red style.fontSize 18 string assetPaths new string 2 string 0 "Test" string 1 "Test1" foreach (string assetPath in assetPaths) if (assetPath.Contains(".test") var i assetPath.LastIndexOf(" ") var t assetPath.Substring(i 1) if (GUILayout.Button(t, style, GUILayout.Width(1000), GUILayout.Height(50))) style.normal.textColor Color.green
0
How do I force Unity to reload editor scripts I am working of some editor scripts for Unity but have found that it is difficult to force Unity to reload my editor scripts. My scripts are modelled on the static constructor approach and perform some manipulation of the Tag Manager. Currently the static constructor is called when either Unity is launched, or Changes to a script (any of them) are written to disk While verifying that the tag manipulation performed by the script is correct I am manually setting the tags via the GUI and then triggering script by saving a trivial change to the file. This is clearly a clumsy workaround, is there a better way to force Unity to reload editor scripts?
0
Breaking up List into sublists by multiple values I'm trying to break up a C List lt InventoryItem gt into multiple lists based on two different values InventoryItem.name and InventoryItem.isStackable. I want the list to be broken up into multiple lists for the purpose of populating my UI with the data while keeping non stackable items in their own list (one item per item slot in UI terms.) If this is the input InventoryItem name apple, stackable true InventoryItem name apple, stackable true InventoryItem name carrot, stackable true InventoryItem name knife, stackable false InventoryItem name knife, stackable false I should get this output InventoryItem name apple, stackable true InventoryItem name apple, stackable true InventoryItem name carrot, stackable true InventoryItem name knife, stackable false InventoryItem name knife, stackable false I'm successfully separating by name alone (see below), but I'm not sure how to take isStackable into account. I'm also using LINQ which I'd prefer to avoid if possible. var itemsByType new List lt List lt InventoryItem gt gt () var inventoryByItem inventory.GroupBy(x gt x.name) foreach(var v in inventoryByItem) var itemList v.ToList() itemsByType.Add(itemList)
0
Unity Export Package Taking Too Long I'm trying to export a Unity Package and it's taking far too long (it just keeps counting, and doesn't end). I'm not sure why it continues to count in the PackageImporter.Tick but I'm wondering if others have noticed performance issues. Unity Version 2020.2.3f1 OS Windows 10
0
Global variables in a multiplayer environment I would like to know what's the best approach to solve this problem. In a racing game, i need to create the final result chart. In a single environment i've tought something like private string arrivalOrder void playerArrived(string playerName) arrivalOrder arrivalOrder.getLength() 1 playerName I would like to know how to do in a multiplayer environment. How the client can communicate to server "my player finishes the racing"? Thanks
0
Reuse and Interact With Multi Layer Tile Maps I'm new to game development and try to make a game where buildings are created in tile maps. My problem is that I need to interact with these buildings and I want to reuse the buildings I created. Now I would like to export these two layers to a single sprite or prefab to create multiple buildings and to make them clickable. Is there a way to achieve this or do I have the wrong approach? EDIT My current setup looks like this Two tile maps One tile map contains the wall of the building. Another tile map contains decoration like door or window. My problem is, that I am not able to export these tile maps as one prefab to reproduce it or to attach scrips. I am looking for a way to combine these two layers into one resource ( The building with all its decorations, doors, windows), so that I can place them anywhere I want and make them clickable as a game object.
0
Draw LineRenderer gradually, rather than all at once I'm drawing a line with a LineRenderer. It works, but now I would like it the line to be drawn gradually, instead of appearing all at once. How can I modify my code to achieve this? using System.Collections using System.Collections.Generic using UnityEngine public class LineController MonoBehaviour private LineRenderer Ir private Transform points private void Awake() Ir GetComponent lt LineRenderer gt () public void SetUpLine (Transform points) Ir.positionCount points.Length this.points points private void Update () for (int i 0 i lt points.Length i ) Ir.SetPosition(i, points i .position) Debug.Log (points i .position)
0
How to create spaceship 'ion trails' that can be curved in Unity? I'm working on a simple space combat game (single player) with the goal of having 100 fighters and capital ships in a single battle. To keep system requirements down I'm using a minimum of effects. One that I do wish to include, however, is that of 'ion trails' from the rocket engines of the spacecraft and missiles. Ideally it would look something like the images below. The trail won't have to be very long, but I do want it to curve to show the spaceship's path, acting as a visual aid in a dogfight. My question is, how to implementing such trails efficiently?
0
Destroying a networked projectile and creating a client side visual for all clients in Unity? I'm making a shooter in Unity with UNET, and of course I handle projectile (like arrows) collision on the server. The arrows are Networked rigidbodies with NetworkBehaviours, and I would like to spawn a Non networked, eye candy like client side prefab at the collision point. Current solution protected override void OnServerFixedUpdate() var distanceSincePreviousFrame Vector3.Distance(positionAtPreviousFrame, rb.position) Collider collider Vector3 impactPoint if(CheckForImpactInNextFrame(distanceSincePreviousFrame, out collider, out impactPoint)) transform.position impactPoint DoImpactEffect(collider) GetComponent lt Rigidbody gt ().isKinematic true NetworkServer.Destroy(gameObject) positionAtPreviousFrame rb.position void OnDestroy() var go Instantiate(ClientSidePrefab, transform.position, transform.rotation) The rigidbody flies on the server (rigidbody synced), and CheckForImpactNextFrame checks collision by raycasting. (needed so projectiles won't go through things due to simulation errors). If it collides, then it does its impact effect, then destroys itself on the network. Clients instantiate a client side, non networked prefab for visuals when the networked projectile is destroyed. At the server side this works well, "client side arrow" is instantiated at the impact position, but at clients, it's instantiated at its previous position, because the transform.position impactPoint in the if isn't synced before it is destroyed on the clients. How could I make those client side visuals appear at the correct position? Could I call a "force sync" before destroying? I can't call an RpcCreateVisuals(position) method, because the entity may be destroyed on the client when the Rpc message arrives. (because the destroy message was faster.) I could call an "always alive" object's Rpc, like a ProjectileManager's method, and I think that it will always arrive, because destroying the projectile has no effect on it. But it feels hacky, non OOP. Doesn't it? How should I solve this solution? What is the common approach for this problem? The same problem described by someone else https answers.unity.com questions 1636182 client objects not traveling same distance as on s.html Maybe I could disable them, and subscribe them to a "GarbageCollector" system, which destroys them only after a delay? Is this a well designed solution?
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
Networking and physics Context I have been implementing my own networking for a third person multiplayer game, but controls and physics will be ala old school FPSs. I'm using Unity's transport layer, which allows me to send and recieve raw data between server and client. I used this model as reference, in order to implement better client response http www.gabrielgambetta.com client server game architecture.html Implementing prediction, and interpolation was no problem, but I'm having a problem implementing reconciliation, even though I successfully implemented for normal ground movement. I do the following each tick Client The client sends the server the delta updates on the player position, and the server validates this movement and updates the player accordingly on the server. Server I send a snapshot to all clients with all players' positions. Each client interpolates the rest of the players, and reconciliates it's own position. Reconciliation Ground movement seems easy, because each frame the player input determines how the player moves Each FixedUpdate, the player moves a certain distance. This makes reconciliation really easy, since knowing which was the last input the server has received, your client just needs to consider the rest of the inputs yet to be processed. Reconciliating jumping But I don't know how to deal with jumping. Jumping is an input that has an impact on the player's position over several frames while it's airborne (and for a few frames, as the placer decelerates in case his air speed was high). This means I can't just rely on the input "jump" to recalculate my client's position, since depending on the moment I'm present, I could be ascending, or descending. Even more, if I jump and collide with the roof, killing all my vertical speed, the movement would be completelly different. This lead me to think I should be sending to the server each update on the player's position Instead of sending "hey, im jumping here", I could send "I'm moving up 1 unit"..."I'm moving up 0.9 units".... describing the players parabole. But I feel this method is not enterily secure, since the client could be sending "I'm moving up 1" ever single time, allowing the player to just fly away. So the server has to be the one handling the physics on the jump. Other scenerios This problem is also present in anything physics related When the player is pushed away by an external force set up by the server or the client itself. If the client recieves a message saying has been affected by an explosion, I could set the client's speed accordingly, but If I have any kind of air control (which I want to have), I need to tell the server the change on air speed If the server makes a correction on the physics made, I need to be able to predict and reconciliate the position AND speed. For example If I collide against a wall in the server, which for some reason, is not present in the client, I also need to kill the player speed or it will keep slamming into an invisible wall. Posible solutions There are several solutions I was thinking about, but I'm not really satisfied with any of them As said earlier, I could could let the client handle the air movement by sending the position update back to the server, but this feels insecure since th client could technically make himself fly around, and make himself immune to being pushed away. Besides sending the player positions, I could also send the players' speed, storing this information could make reconciliation easier and more reliable, but it will also increase the size of snapshots and network usage. Maybe I'm missing a clever alternative, but I don't really see any other option. Any ideas?
0
How to Stop Background Music When The Game is Over? I am working on a 2D Angry Birds type Unity game. I Created Menu Scene and Level One Scene and all the required scripts are added. After adding background music to Level One, when the game is over and return to Menu I can't stop the music. The Menu scene has its own music and when the level one is over, it continues with its own music and gets mix with the menu scene music. I tried to add Destroy() function to level one GameObject but Level One music became silent after I restart with my menu scene. Here is my code for the attached music game object public class background sound MonoBehaviour public static bool soundBreaker false public void Start () if (!soundBreaker) AudioSource myAudio GetComponent lt AudioSource gt () myAudio.Play () DontDestroyOnLoad (myAudio) soundBreaker true And here is the Menu Script public class MenuScript MonoBehaviour public void StartGame () SceneManager.LoadScene ("Level One") ... Here is the code that loads the Menu Scene.. public void GameOver() musicObject.setActive(false) startCoroutine(restTime()) IEnumerator restTime() yield return new WaitForSeconds (3) SceneManager.LoadScene("Menu")