How do I set the Jump distance and height of my sprite in C I have been able to make my sprite jump for a platformer I am making in unity. I can't seem to be able to make him jump a certain height or distance though, every time he jumps it's like he's jumping on the moon, any suggestions? Here's my code using UnityEngine using System.Collections public class playerScript MonoBehaviour public bool grounded true public float jumpPower 190 public float jumpSpeed 100f private bool hasJumped false Use this for initialization void Start () Update is called once per frame void Update () Do something if(!grounded amp amp GetComponent lt Rigidbody2D gt ().velocity.y 0) grounded true if (Input.GetKey(KeyCode.Space) amp amp grounded true) hasJumped true GetComponent lt Rigidbody2D gt ().AddForce(Vector3.up jumpSpeed) void FixedUpdate () if(hasJumped) GetComponent lt Rigidbody2D gt ().AddForce(transform.up jumpPower) grounded false hasJumped false Any help would be greatly appreciated )


Having the same camera in all scenes I have 100 scenes, each scene has a camera, but I want only the camera from scene 1 to exist in each scene that I appear in. I use the function DontDestroyOnLoad() to make the camera exist in each scene but I always find my self with another camera that I don't want. Any ideas? thank you in advance.


Unable to Set Up unity remote? I have installed Android Studio and set the path in unity. And I am able to build apks with no problem. But when I try to test in unity remote unity gives an warning as Set up Android SDK path to make Android remote work I don't know what is happening. If Android SDK path is not set then how am I able build the apks. I tried to solutions like enabling usb debugging mode , running unity editor first then opening Unity Remote , installing Google USB driver component of Android SDK but none of them worked for me.


How to securely retrieve game stats from clients in a p2p game network? I'm working on a P2P game and I know I should never trust the clients. I my architecture, there is a "Master Server" that stores game room (host) informations. Players can create their own rooms (hosting) and play with together. There is another server that is "Info Server", it stores character informations like inventory, level etc. Now, I need to make a stats table with kills deaths and I have to get these kill death events from host player (host player event master server). But I think host player can send a lot of kill events because it is authoritative, so master server will process handle all events from the host player. How can I trust these events? Can't a server just send fake kill death events?


Changing alpha of Sprite I'm using OnGUI to draw a rect when I "box select" or "drag select". The texture that gets drawn is a PNG file made in Paint.Net with the opacity alpha channel set quite low. In Unity however, when I go to box select, the texture is completely opaque. How do I get Unity to honor the alpha set in Paint.Net? I also wouldn't mind using Unity itself to adjust the opacity, but I haven't found such an option in the import texture part of the inspector.


Questions about Jrpg NPC events (Unity C ) So, I'm trying to wrap my head around something. I've got my basic quest system up and running for my rpg style game. Right now I'm taking a look at NPC events and triggers that as I see it have two distinct styles The classic floor panel trigger that rpg maker uses or have a listener class for quest active event active My questions are thusly what's the best way to go about activating the event and what's a good way to define the event? Like set movement patterns etc would it be feasible in json? Or should I use scriptable objects?


How can the Server send a message to a single Client? I'm trying to send an Rpc, or any sort of message, to a specific client instead of to them all. I'm completely at the loss trying to associate a NetworkConnection with its own authoritative spawned player (from playerPrefab). If I let the NetworkManager auto spawn it, then I don't know how to get the connection from the player object. If I override OnServerReady and I spawn it myself, then it has no authority on the client and I don't know how to give it. I've browsed all sort of documentation but I couldn't find anything useful. Obviously there must be a way to do that, but I really can't find it.


How can I make an object move in a certain direction depending on its spawning point? I'm currently developing a 2D game and I couldn't find a way to figure this out. In the game, I have 4 different balls and 4 different spawning points. Every 2 seconds, a random ball spawns at a random spawning point. What I want to achieve is, as I tried to describe above, lets say a ball spawns on right side, I want it to move towards left, if it spawns upside, I want it to go downwards etc. Here is my spawner code using System.Collections using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public Transform spawnPoints public GameObject balls public float timer 2.0f void Update() timer Time.deltaTime SpawnBalls () void SpawnBalls() int spawnPoints num Random.Range (0, 4) int balls num Random.Range (0, 4) if (timer lt 0) Instantiate (balls balls num , spawnPoints spawnPoints num .position, spawnPoints spawnPoints num .rotation) timer 2.0f And here is my ball movement code using System.Collections using System.Collections.Generic using UnityEngine public class Balls MonoBehaviour public Game game public float speed 0.25f void Start () game FindObjectOfType lt Game gt () void Update () Some if statement transform.Translate (Vector3.left Time.deltaTime speed) else if transform.Translate (Vector3.up Time.deltaTime speed) else if transform.Translate (Vector3.right Time.deltaTime speed) else if transform.Translate (Vector3.down Time.deltaTime speed) I've tried giving spawnpoints tags and creating if statements with gameObject.tag and stuff but couldn't find a way to work it. How can I make it check which spawnpoint the ball spawned at so I can make it move accordingly? Thanks for help.


Have several classes with a common interface, but still able to access MonoBehaviour methods through that interface? In our project we used to have a PlayerObject class and then Unit and Building derived from that class. We recently started taking a look at Bolt, which requires classes that define objects that may have different states to inherit directly from a Bolt class. So Unit and Building can no longer inherit from PlayerObject. This turns out to create a few problems, a significant portion of our game uses PlayerObject rather than Unit or Building to perform actions that are the same for both. Separating them would really throw a wrench into the program, since you now have to have methods that use both Unit and Building instead of just PlayerObject. I thought making a common interface IPlayerObject, and defining common properties and methods in the interface and making Building and Unit both derive from IPlayerObject would do the trick. I did not think it through enough and came to find out that if I use IPlayerObject I can no longer access MonoBehaviour methods and fields (such as transform, or render). Can I make this in such a way that I can use the IPlayerObject type, with a Unit or Building type and still have access to MonoBehaviour through that interface? If not, is there a proper way to do this, past just adding in extra methods to handle Unit and Building types separately.


RTS Unit AI When to let the unit stop (due to local avoidence) I am developing an RTS like game, that have units that move and attack. I implemented path finding and local avoidance. One problem is when multiple units being ordered to the exact same position, they can never reach the position due local avoidance and collision. Only this will make the units scratch each other, this will also cause the unit not able to STOP, as the unit might be still far from the target position. And whether stopped or not is important for battle (unit can only attack when stopped). I studied how SC2 handles this, it appears that the units will stop after a few seconds of scratching. PS, I have used group formation to avoid the situation, but it can not be avoided, when the group are ordered to goto some impossible position, and they would cluster at the edge of the valid navmesh.


How to handle assets in Unity? Here's what I have in our little Unity game If an asset (mostly a prefab or a texture) has to be accessed (e.g. to instantiate a game object), it is often passed as SerializeField to the script component. Scripts that are not components get their assets through the constructor so the assets are passed down until the class where they are needed. It's ugly. If a lot of assets are needed (like textures of an animation), they are moved into a folder called "Resources" and accessed through the Resources class. The documentation explicitly says "don't use it". What I want To access assets through a name or path to create objects at run time. What I found The AssetDataBase class looked promising until I couldn't locate it and found out it is deprecated (and the documentation does not tell how to replace it). Nothing on Google but a lot of outdated things Asset bundles look promising too, but they are quite complicated and there are no really good migration tutorials and I don't know how to use them. Any suggestions? How do small mid sized bigger Unity games handle their resources?


How can I create a precise touch in Unity Is there a way so that I can touch an object precisely? I have these aerial cars and there pretty tiny like 32 by 32 and it's hard to touch them using a raycast. I thought I'd spawn an object with a circle collider on it on the first touch and destroy it after the touch.


How do I pause play animation in Unity without the animation getting cut off I'm trying to achieve a common game behavior that when you hit an enemy, then whatever the enemy's action (animation) is, when the hit happens, the enemy pauses a bit, then continues with the animation. So everytime you hit the enemy, the enemy pauses for a bit. I currently have this code IEnumerator StopStartMotion() animator.speed 0 yield return new WaitForSeconds(.2f) animator.speed 1 Problem is, sometimes, when I hit too early in the enemy's animation (like at the beginning of a punch), the enemy pauses, and then doesn't continue the animation where he paused for a bit. Is there a better way of doing this? I tried animator.enabled as well, but the animation also jumps.


Artifacts in unity shading I created block of 3x3x3 cubes, disabled shadows, set directional lighting color to white and ambient to black. And I'm getting this Any idea what is going on and how to fix it? Effect is visible when object isn't moving but with a lot less artifacts. It doesn't matter what is moving, camera or cubes. I would guess that this is precision problem but is there anything that can be done about it? EDIT Here is a screenshot of cubes Also this is how it looks after static batching (this happens because of Lightmap Static in Mesh Renderer is on)


Is the Microsoft recommendation to use C properties applicable to game development? I get that sometimes you need properties, like public int Transitions get set or SerializeField private int m Transitions public int Transitions get return m Transitions set m Transitions value But my impression is that in game development, unless you have a reason to do otherwise, everything should be nearly as fast as possible. My impression from things I've read is that Unity 3D is not sure to inline access via properties, so using a property will result in an extra function call. Am I right to constantly ignore Visual Studio's suggestions to not use public fields? (Note that we do use int Foo get private set where there is an advantage in showing the intended usage.) I'm aware that premature optimization is bad, but as I said, in game development you don't make something slow when a similar effort could make it fast.


How can I reduce the size of bundled Unity DLLs on Android? I have created a simple project (I am a Unity beginner) for Android but the apk size is around 18 MB! I checked the documentation. One way to decrease the apk size is to check the editor log. Then I discovered that imported DLLs have a size of 3.9MB. I only used UnityEngine and Collision packages. So how can I avoid to import the other big DLLs?


Generate 4 vectors rotated in cardinal directions from a central vector There is some unit vector, which is a coordinate in a spherical space. It is necessary to obtain from it 4 vectors diverted in different directions (right, left, forward, backward) by a certain number of degrees. For these actions I use the following code Vector3 center point Vector3 left Quaternion.Euler( 30, 0, 0) center Vector3 right Quaternion.Euler(30, 0, 0) center Vector3 back Quaternion.Euler(0, 0, 30) center Vector3 front Quaternion.Euler(0, 0, 30) center The problem is that this works when point is equal or close to Vector3.up. When deviating from the vertical position, the lateral vectors begin to "stick together". Here is a visualization of what I need Test code is attached using System.Collections using UnityEngine public class Test MonoBehaviour public GameObject centerGO public GameObject leftGO public GameObject rightGO public GameObject backGO public GameObject frontGO ArrayList list new ArrayList() void Start() SetCenterPoint(Vector3.up) void Update() DrawDebugRays() Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) SetCenterPoint(hit.point) void SetCenterPoint(Vector3 point) Vector3 center point Vector3 left Quaternion.Euler( 30, 0, 0) center Vector3 right Quaternion.Euler(30, 0, 0) center Vector3 back Quaternion.Euler(0, 0, 30) center Vector3 front Quaternion.Euler(0, 0, 30) center centerGO.transform.position center leftGO.transform.position left rightGO.transform.position right backGO.transform.position back frontGO.transform.position front list.Clear() list.Add(center) list.Add(left) list.Add(right) list.Add(front) list.Add(back) void DrawDebugRays() for (int i 0 i lt list.Count i ) Color color Color.red switch (i) case 0 color Color.green break case 1 case 2 color Color.blue break Debug.DrawRay(Vector3.zero, (Vector3)list i , color)


How to pass an argument with ref keyword to a local funtion how to work around it? Unity 2019.3 I am writing a few extension methods to make my life a little bit easier, but this one is bogging me down. I am loading stuff with Unity's Addressable system, and I would like use it by extension methods. I am passing in my variables (reference type amp value type, doesn't matter) to my extension methods, hoping to set them and and hide some complexity and source of bugs, and errors. It seems to me they are passed by value, because when I am trying to use them outside the extension methods, they are not set, null, etc. Not working. There is a callback called Completed, and I am subscribing with a lambda expression... I tried with the ref keyword, but obviously the compiler is yelling, that she doesn't want to pass my ref, out whatever parameters to local functions... ( I tried it out with no local functions, and it did not work without the ref keywork, but it did with it! You get the idea! Please see my code below! This is the one that I can't get to work... Trying to set the generic variable data from the Addressable assetref public static void TryLoadData lt T gt (this AssetReference assetref, T data) var handle assetref.LoadAssetAsync lt T gt () handle.Completed loadedresult gt T result loadedresult.Result if (result null) return data result This one does, but only with ref... Setting the generic data parameter to the parameter g. public static void SwapTest lt T gt (this T g,ref T data) where T class gt data g I am not sure if there is a workaround, I thought of pointers, or global variables, but not sure which one is the right way to go. Thanks


How to make UI image bounce back and forth inside another UI image? I've been trying to create a battle system for my game, and I've been trying to get a UI image to bounce back and forth inside another image, but for some reason, the UI image goes out of the other UI and bounces back, like so Here's the script I add to the moving arrow image, in order to make it bounce using System.Collections using System.Collections.Generic using UnityEngine public class JumpSystem MonoBehaviour private Vector2 startPosition public int speed Start is called before the first frame update void Start() startPosition transform.position Update is called once per frame void Update() transform.position new Vector2(startPosition.x Mathf.Sin(Time.time speed), transform.position.y) Is there any way I can prevent this incident from occurring? Please help me understand this and thank you in advance.


Can I use trilinear filtering for my sprites, but keep their outlines unfiltered? Suppose that I have two images of equal size. They both contain a square https i.stack.imgur.com BI62X.png https i.stack.imgur.com Nev5Z.png When overlapped, both squares will appear next to each other. If both images use Point (no filter), they will contact without issues regardless of the amount of zoom or scale If you use either Bilinear or Trilinear, there will be an artifact visible in certain zoom scale levels Of course, that is to be expected from the very nature of the filters. As much as I would like to just leave it at Point (no filter), my game looks far better using Trilinear instead except of course, for the "borders" or points of contact. The ideal scenario for me as bizarre as it may sound, is to be able to use Trilinear filtering generally, but force the "outlines" of my sprites to stay as if they were Point (no filter). This way, my game looks painterly when zoomed in out (the game isn't pixel art), and I also avoid the "glitch" in specific contacts. Yes, the glitch is only noticeable if you use a scale zoom that is higher than 100 . Unfortunately, due to the nature of the game, the player should be able to zoom in out if they desire, so I can't just pick "the" ideal camera size or sprite scale because it can't be constant. I've tried using Canvas and its Pixel Perfect checkbox to no avail. I didn't really expect that to work though. What can I do to achieve the desired effect, then?


LineRenderer sorting order lines always in front of everything I have 3 cameras and 3 canvases. Back Camera depth 5, Back Canvas Sorting layer BackLayer, Camera depth 0, Middle Canvas Sorting layer MiddleLayer, Camera depth 10, Front Canvas Sorting layer FrontLayer, Orders in canvases are also set (for SpriteRenderers, images, ui etc.) Back is for a background image and stars, middle for mountains and front for the UI. Everything is working perfectly with one exception No matter where I draw lines with a LineRenderer they're always at the front of everything (each canvas). The one situation where the line moves deeper is when I set it's points Z to some huge values like 30000 and then they're just behind everything. My goal is to place these lines along with the background image and stars on the BackLayer or BackCanvas. What I've already tried Setting LineRenderer sorting layer and it's order from the code. I read somewhere on Unity forums that lineRenderer has to have a special material for this to work but I tried most of them not working. I also tried setting their positions manually, from the inspector, from the code, incrementally in the Update() method they're always in front or complately hidden (with huge numbers mentioned above). I tried assigning them to different canvases (back, middle, front) as children didn't work too. On Unity forums I also read a post which says that we shouldn't use sorting layers with linerenderer and use only Z positions. If someone has any experience with this, I would be grateful. I really have no idea if I'm doing something wrong or what.


How do I blink a sprite a few times before it disappears? I need the 3d poop emoji model in the chest on the right to blink, visible invisible visible, several times This is a 3d gameObject oriented to face the camera, shaded with an unlit material. I need the object to "blink flash" to indicate that the item has been obtained. The object needs to be generated the moment the lid opens (done), stay unchanged until the lid pops all the way up (0.2 seconds), and flash 3 times during the 0.6 seconds the lid is up. The object is destroyed the moment the lid starts to come down again. My code (blinking flashing is not working) using System.Collections using System.Collections.Generic using UnityEngine public class ItemBox MonoBehaviour bool disabled false private Animator anim public GameObject item null void Start() anim GetComponent lt Animator gt () if (!disabled) anim.Play("ItemBoxIdleState") Update is called once per frame void Update() void OnTriggerEnter (Collider other) if (!disabled amp amp other.gameObject.tag "Player") anim.Play("ItemBoxGetItemState") GameObject itemClone Instantiate(item, transform.position new Vector3(0, 0.5f, 0), Camera.main.transform.rotation Quaternion.Euler(0,180,0)) Blink(itemClone) Destroy(itemClone) disabled true IEnumerator Blink(GameObject obj) Renderer objRenderer obj.GetComponent lt Renderer gt () objRenderer.enabled true yield return new WaitForSeconds(0.2f) for (int i 0 i lt 3 i ) objRenderer.enabled false yield return new WaitForSeconds(0.1f) objRenderer.enabled true yield return new WaitForSeconds(0.1f) Instead of blinking flashing, the object is just there, doing nothing.


Is database necessary? Hi I have studied c for good few months and I'm at intermediate level at the moment. And few days ago I decided to make simple 2D Games like "Mr Jump" after studying Unity. So my question is as follow 1)Should I study database to make simple mobile games? and if so what would be good language to study? 2)And if you have played "Mr.Jump", can you tell me if that game required complicated database coding and a lot of knowledge? 3)Also when we play the game, our best score and new characters get saved in our phone. Is that something to do with database? 4)Could tell me examples of database in games? 5)Should I study database as much as c ?


How to check if gun may shoot again (because animation has stopped playing)? When the user presses the fire button, I set a trigger animator.SetTrigger( quot HG Shoot quot ) This trigger causes a quot pistol shoot quot animation to be played. The gun should only be able to shoot again as soon as the shoot animation has finished. I could check at each Update() if that certain animation is still being played like this bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName) if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName) amp amp anim.GetCurrentAnimatorStateInfo(animLayer).normalizedTime lt 1.0f) return true else return false But I don't like the frequent checks. I would rather like to have a variable to would be set by the animator. Or I would set it at the beginning of the shoot animation. Because there are other animations that I have to check that would disallow shooting of the gun, too, like reloading the gun. This would make everything even more complicated. How can I solve this problem?


prefab editor not working for NGUI in unity2018 i just updated my project from unity5 to unity 2018. my project uses ngui as UI solution. eveything works fine in updated version but when i want to edit prefabs in prefab mode i get this message is there any idea about cause of this problem and how to solve it? i looked for updating ngui for unity 2018 but because of many changes ngui has, it causes lots of problem in project that takes lots of time to solve the mall


How would I find the SDK folder for Android Studio so I can build my Unity project? So I've been trying to build my unity project for android, but my problem is that I don't know how to find the Android SDK. I have the old developer bundle installed, when it was still the one with eclipse, but this version is not supported by Unity. So, I installed the latest version of Android Studio, the new official Android IDE, but the SDK folder is not in the same place as the rest of the program. How would I find the SDK folder for Android Studio so I can build my Unity project?


Specify the size of the points when building a mesh based on a point cloud I create a mesh in Unity3D based on a point cloud in this way The standard sequence for creating a mesh Mesh mesh new Mesh() Vector3 points new Vector3 numPoints int indecies new int numPoints Color colors new Color numPoints Fill in points, indecies, colors mesh.vertices points mesh.colors colors mesh.SetIndices(indecies, MeshTopology.Points, 0) I learned that it is possible to set the size of points in PSIZE through Vertex Shader. Applied such a Shader, but without result. Shader "VertexColor" Properties PointSize("Point size", Float) 5.0 SubShader Pass LOD 200 CGPROGRAM pragma vertex vert pragma fragment frag uniform float PointSize struct VertexInput float4 vertex POSITION float4 color COLOR struct VertexOutput float4 pos SV POSITION float4 col COLOR float size PSIZE VertexOutput vert(VertexInput v) VertexOutput o o.pos UnityObjectToClipPos(v.vertex) o.col v.color o.size PointSize return o float4 frag(VertexOutput o) COLOR return o.col ENDCG Tell me, please, how to set the size of points correctly?


I need to keep music playing but still be able to mute it between games, how? I have a game built in Unity. The game plays music continuously, which can be muted on button press on the scene. This works fine using the below code MuteButton.cs using UnityEngine using System.Collections using UnityEngine.UI public class MuteButton MonoBehaviour public GameObject audioObject private AudioSource audioSource void Start() Button b gameObject.GetComponent lt Button gt () b.onClick.AddListener(Pause) void Pause() Debug.Log("mute toggle") audioSource audioObject.GetComponent lt AudioSource gt () if(!audioSource.isPlaying) audioSource.Play() else audioSource.Pause() However, when the player loses the game restarts by reloading the scene, using this code public void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex) In order to keep the music running I have attached the following script to my music game object using UnityEngine using System.Collections public class Music MonoBehaviour static Music instance void Start() if(instance null) instance this DontDestroyOnLoad(gameObject) else if (instance ! this) Destroy(gameObject) All working fine up until now. Once the scene is reloaded when the user tries to mute the music I get the following MissingReferenceException The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. I understand that the error is that I'm trying to mute a now non existent game object, but how can I pause the music if this is the case?


How do i move a 2D object with angle and speed variables in unity? I want to move an object with a certain angle and speed, is there a was to set this as an initial velocity so that it is still possible for the object to collide and bounce of other objects using its rigid body?


Creating outline from a collection of points following the concavity I am trying to create an outline from a collection of points. I found this solution for Convex Hull. I specifically picked this implementation https en.wikibooks.org wiki Algorithm Implementation Geometry Convex hull Monotone chain Edit I can't find an algorithm that will find the concavity of the region specified in green. The yellow line is the Hull from the algorithm amove I have the point is defined as Serializable public struct Point IComparable lt Point gt , IEquatable lt Point gt public int X public int Y public static int Cross(Point o, Point a, Point b) return (a.X o.X) (b.Y o.Y) (a.Y o.Y) (b.X o.X) Here is the implementation of the algorithm public static List lt Point gt ConvexHull(List lt Point gt points) if (points null points.Count lt 3) return points var size points.Count var k 0 var hull new Point 2 size points.Sort() build lower hull for (int i 0 i lt size i) while (k gt 2 amp amp Point.Cross(hull k 2 , hull k 1 , points i ) lt 0) k hull k points i build upper hull for (int i size 1, t k 1 i gt 0 i) while (k gt t amp amp Point.Cross(hull k 2 , hull k 1 , points i 1 ) lt 0) k hull k points i 1 var result new List lt Point gt (hull) if (k gt 1) result.Resize(k 1) remove non hull vertices after k remove k 1 which is a duplicate return result


Unity Ambient Occlusion artefacts When I create two cubes from Unity Component menu. And turn on AO the bottom cube is not shaded properly. I mean the upper cube is alright but the bottom cube does not have any shadow present. What am I doing wrong ? Lighting setup Result


How can I add array of components to a new gameobject? I use Getcomponents to get all components from existing gameobject Component components go.GetComponents(typeof(MonoBehaviour)) And I want to add them now to another gameobject for (int i 0 i lt components.Length i ) var comp components i newObject.AddComponent lt comp gt () components is type Component But when I try to type components inside the AddComponent lt the variable components not exist. Tried then to make the comp variable but can't type it inside the lt either.


Animation imported from Blender into Unity via FBX doesn't play? I started building this model in Blender and gave it a simple animation that rotates the board about the axel. ...I exported it as FBX and imported it into Unity. I can see the animation is stored in the file when I import, but I can't find an animation file after I drop it in the scene, and there is no controller for the Animator controller it generated, either. I can watch the animation play in the FBX preview thumbnail but nowhere else. How can I get my animation working?


Quaternion.slerps resets camera rotation to (0,0,0) when i go to play mode help! i am building a camera rotation script like in fps. Everything is setup and working except that camera rotation resets to zero at the start of game which i dont want. This is the camera rotation i have set This is rotation of character my script is attached to And after hitting play it resets camera rotation to (0,0,0). i want it to remain how i have set it in inspector. i am using quaternion.slerp to rotate camera around to rotations on the basis of touch inputs. After reset to (0,0,0) everything works fine.please help, i have always had a hard time understanding quaternions. this is the script public class ScreenCharacterController MonoBehaviour private Camera mainCamera private CharacterController character private int leftFingerID 1 private int rightFingerID 1 private Vector2 leftFingerInput private Vector2 rightFingerInput private float xAxisRotation private float yAxisRotation SerializeField private float minXRotation SerializeField private float maxXRotation SerializeField private float minYRotation 25f SerializeField private float maxYRotation 25f SerializeField private float cameraRotationSpeed 20f void Start() mainCamera Camera.main void Update() for touch TouchInput() for calculating rotation vaues CalculateAndClampRotation() RotateCamera() void TouchInput() foreach (Touch touch in Input.touches) if (touch.phase TouchPhase.Began) Left Touch if (touch.position.x lt Screen.width 2) leftFingerID touch.fingerId Right touch else rightFingerID touch.fingerId else if (touch.phase TouchPhase.Moved) Left Touch if (touch.position.x lt Screen.width 2) if (leftFingerID touch.fingerId) Right touch else if (rightFingerID touch.fingerId) rightFingerInput touch.deltaPosition Time.smoothDeltaTime else if (touch.phase TouchPhase.Ended touch.phase TouchPhase.Canceled) if (touch.fingerId leftFingerID) leftFingerID 1 else if (touch.fingerId rightFingerID) rightFingerID 1 rightFingerInput new Vector2(0, 0) void RotateCamera() Quaternion currentRotation mainCamera.transform.localRotation Quaternion targetRotation Quaternion.identity targetRotation Quaternion.Euler((mainCamera.transform.localRotation.x yAxisRotation), (mainCamera.transform.localRotation.y xAxisRotation), 0f) mainCamera.transform.localRotation Quaternion.Slerp(currentRotation, targetRotation, 0.5f) void CalculateAndClampRotation() xAxisRotation rightFingerInput.x cameraRotationSpeed yAxisRotation rightFingerInput.y cameraRotationSpeed xAxisRotation Mathf.Clamp(xAxisRotation, minXRotation, maxXRotation) yAxisRotation Mathf.Clamp(yAxisRotation, minYRotation, maxYRotation)


Unity editor, horizontal line in inspector How to draw a horizontal line in the inspector like on the reference image? Kind of separation line.


Unity Ragdoll Colliders don't collide I have a humanoid character with Ragdoll setup in Unity. However the box capsule colliders on the various parts of the body don't collide with other static geometry. They do collide with the ground but not with any other static meshes. Is it possible to use them as colliders towards static meshes and what do I need to do for it to work?


Is it legal to sell or monetize games created with the Unity 3D free edition? Is it okay to use Unity 3D programming and gaming software to create mobile game apps for Android and iOS? I am using a free version of Unity 3D and planning it to sell my current game app I've created by publishing it to Google Play. I also use this method for earning money by setting as a free app with ads on it. I saw some developers relied on using free version of Unity 3D to create games and published it via App Store or Google Play. If it does, should I have to pay or share contribution to the Unity development team for earnings since I use the free version in order to rely for producing several game apps for business?


Unity3D terrain object's textures flickering on long distances I'm making RTS project on Unity3D. I created terrain with Unity's standard Terrain tool, and added textures of grass, mood etc. on it. Then, for creating "man made" objects of terrain (roads, sidewalks, road curbs etc) I'm created this objects in separate assets, and placed on terrain. And I have one issue with this solution. On moving camera away from the terrain, terrain's texture(e.g. mood) are flickering under roads, sidewalks and other objects. AFAIK, this bug caused by insuficcient accuracy of floating point coordinates in Unity3D engine (?). Now, as I concerned, my approach to creating terrain objects is not correct. I must create one mesh with terrain, and all manmade objects in 3D modeling software, and then create UV map for texturing all of it. Is this approach correct? If "yes", is any special approach for modelling and texturing so large and complex object as terrain?


How to put virtual hands in front of player? I want to have the VR hands always in front of the player. This works while walking forwards backwards, once I rotate the camera they stay in the same place. I know that I need to take the camera facing into account, but I am missing the math here. Here is the code for hand translation rotation void Update() if (UnityEngine.XR.XRDevice.isPresent) GameObject player GameObject.Find("PlayerGameObject") if (hand WebVRControllerHand.LEFT) transform.position UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.LeftHand) player.transform.position transform.rotation UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.LeftHand) if (hand WebVRControllerHand.RIGHT) transform.position UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.RightHand) player.transform.position transform.rotation UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.RightHand) Update Having no movement implemented, looking around will make the hands always appear in front of the camera. If I add this code to the camera object, it will break so the hands never leave their original space(they still move when I rotate the controller but they stay in the same place) Script is attached to the parent of the hands public class SimpleMovement MonoBehaviour void Update() var x Input.GetAxis("Horizontal") Time.deltaTime 150.0f var z Input.GetAxis("Vertical") Time.deltaTime 3.0f transform.Rotate(0, x, 0) transform.Translate(0, 0, z) Update 2 It seems like I got it partially working. At least for translation movement. I set the position only according to what comes out of the XR framework, now I add the player's position on top(previously I did this at the wrong spot). What is missing now is rotating the camera with the sticks seemns different than rotating the camera with the headset. So the hands still do not respond to rotation movement of the sticks.


How can I get Unity to do letterbox pillarbox to maintain aspect ratio? I'd like my game to have the same aspect ratio at all cost, including keeping all UI elements fixed in the same place. I'm totally ok with losing screen space in the interest of fixing the aspect ratio.


How to set up the camera for a PS Vita game? I am starting my first project for Unity and I want to start a new game for PS Vita. This console has a resolution of 960x544 pixels. How do I have to set up my camera so that it adapts to this aspect ratio?


Unity2D Floor tiles moved or missing I'm following the 2D Roguelike tutorial, which can be seen here. I don't want to get fancy, just follow the existing steps. I've reached the part where all it's supposed to do is draw the playfield. But it looks like this and I don't know why. Some of the floor tiles are appearing beyod the outer wall, and others are missing (or maybe they're stacked on top of other tiles). (EDIT I discovered that the "missing" tiles are because I had the sprites in the wrong layer, and fixed them. I still have several appearing to the left of the outer wall, though.) I tried to debug it in Visual Studio. The plan was to step through it line by line to see how the tiles are put down, but the debugger doesn't show the playfield until the whole thing is complete.


Mip Maps on 2D Sprite causing black line above. Why is this? I am new to Unity. I'm trying it out and using Futile for a code first approach, but still importing textures using the Unity system. The problem I'm having is that when I use mip maps to scale large sprites down to smaller sizes without jagged edges, I'm getting a black line artefact above said sprites. A little hard to see, but they're there. If I turn down the resolution, you can clearly see them These are my texture settings My question is, why are these black lines here? Is it a mistake I've made? Is it just a common side effect? How can I reduce these? Also, if this is the wrong approach, how can I use smooth sprites in a game with the ability for them to scale up smoothly? Thanks!


How can I my homing missile avoid walls (2D)? Okay, I have the homing missile implemented. It will follow the player, but I want it to avoid the walls. I tried out A but I want to make my own. I need some help plzz.


Quat.AngleAxis broken on one axis I have a scene in my game where you create your own designs by placing static meshes and manipulating their scales, positions, and rotations. For the rotations I'm using Quaterion.AngleAxis as so if (toolMode PositioningTool.Rotate) switch (grabbedCollider.transform.name) case "X" focus.localRotation Quaternion.AngleAxis(delta.x 90 Time.deltaTime, transform.right) break case "Y" focus.localRotation Quaternion.AngleAxis(delta.x 90 Time.deltaTime, transform.up) break case "Z" focus.localRotation Quaternion.AngleAxis(delta.x 90 Time.deltaTime, transform.forward) break where delta is the mouse movement for that frame, focus is the object I am manipulating, and transform is the transform component of the ToolArm that the player interacts with. toolarm.position is set to focus.position every frame my problem arises when I try to do a rotation on my x axis. my other axis will spin 360 and beyond, spinning in circles endlessly. when x axis is used, it only rotates from 90 to 90 (as seen in the unity editor). What am I doing wrong?


Setting up a shader for RTS construction grid visibility (around cursor) I've set up a shader, thanks to the good help of DMGregory over at Draw animating grid with terrain deformation and variable colors here's what I got so far here's what it's supposed to look like here's what my shader code looks like as it stands forgive my non 2K screen it's only a 1080p but this is the full shader. here's each bit in isolation here's the main options for the node If I set surface to transparent... I get a much better result yet still not what I want because the grid area fades out immediately instead of staying at the center of the cube also the corner clearly has a green and red line overlap when line should only ever be red or green. this is the mock file that I'm currently using for buildable and non buildable area it's 256x256 (the size of my map) for now because I want to start small (where 1px maps to one unity square on the terrain of 1 unit) before I move on to the real deal which should be a 3584x3584 Texture 2D (where 1px corresponds to 1 14th of a unity unit). I want my grid to be 1 14th of an digit. eg cell one is (in diagonal) from (0.0f, 0.0f) to (0.14f, 0.14f). I've got preliminary code which will serve to generate this texture 2D programmatically editable2DconstructibleMap new Texture2D(256, 256, TextureFormat.RGBA32, false) constructionGrid GameObject.FindGameObjectWithTag( quot GridViewer quot ).GetComponent lt MeshRenderer gt () fill texture color corresponding to navMesh for (int x 0 x lt editable2DconstructibleMap.width x ) for (int y 0 y lt editable2DconstructibleMap.height y ) NavMeshHit hit if (NavMesh.SamplePosition(new Vector3(x 1.0f, 0f,y 1.0f), out hit, 1.0f, NavMesh.AllAreas)) editable2DconstructibleMap.SetPixel(x, y, Color.white) else editable2DconstructibleMap.SetPixel(x, y, Color.black) constructionGrid.sharedMaterial.SetTexture( quot BuildableMask quot , editable2DconstructibleMap) Here I'm using the navMesh which itself is automatically generated based on terrain slope. I target each point of the map and see if it falls in or out of the navmesh. Instead of redrawing this texture 2D when a building is placed and placement becomes impossible. I think I'll simply programmatically edit the 2D texture to add the new black pixels whilst the navmesh will be updated independently. Anyways, I guess the green red overlap issue comes from my texture2D being currently too small, but if I don't know yet what one pixel corresponds to, I'll have trouble getting this right. Update so changing the texture to one of 3584x3584 did not help. I still have the exact same behavior. So basically what did I get wrong in following the instructions from the other answer?


Is it possible in Unity to Flip a 2D Sprite Without Flipping the Object it is Assigned to? I 'built' (followed a tutorial) on a collision detection system, and when I flip the object to go left and right the collision messes up. So I have three options find a way to modify the collision detection, have sprites for all animations for left and right or to flip the sprite but no the object. if anyone has used RaycastHit2D, and has figured out a way to do it correctly, that would also be great.


How can I make several 2D objects move in complex pre defined patterns? I will be making my mobile 2D game in Unity and the objects in the game will have complicated movement. For example, there will be lots of squares (around 10 15 tiny squares) in the middle of the screen which will move in pre defined patterns like in the shape of an X or an M or O. The tiny squares forming the pattern M will be constantly moving within that X symbol and will be constantly instantiated at one end and destroyed at the other to achieve the effect (or just allowed to move within a pattern if the patterns shape permits). Unity tutorials explain the basics on how to work with the transform component, etc but I have been looking for a resource that tells you how to achieve the above. How can I implement it?


Build Unity3D project from source without Unity Editor I am trying to create an installer which will download the source of the latest release of a Unity project from a repository hosted on Github and then build it into an executable file. I have tried looking online for a solution, but, they all require the Unity Editor to be installed. Is it possible to build a Unity project from the source code into a .exe file or a .dmg file without the Unity Editor? EDIT From DMGregory's answer, it seems that using an external tool to build Unity Projects will violate Unity's Terms of Service. Therefore, I am updating the question. Does Unity provide a lightweight (installer) tool that can allow clients to build and install Unity projects from source rather than requiring the client to install the entire Unity Editor?


Set Parent to Instantiated Objects in Unity i am having problem in attaching parent to the instantiated objects. I have attached the code below. please tell me where i am doing wrong. Thank you. public GameObject brick public Transform BrickHolder public GameObject Bricks void Start() for (float y 2.16f y lt 4.88f y 0.34f) for (float x 2.125f x lt 2.125f x 0.85f) GameObject Bricks Instantiate(brick, new Vector3(x, y, 0), Quaternion.identity) as GameObject if (Bricks ! null) Debug.Log("Hello") Bricks.transform.SetParent(BrickHolder)


Making a new instantiated prefab as a child for existing GameObject I've been searched about how to make these fruit to move as the basket movement if it collided with it, and I've been found that if I want to perform this I've to let these fruit to be a child to the basket game object .. for example banana.transform.parent basket.transform banana and basket each of them of type "GameObject" ... BUT unfortunately this way didn't work !! and I don't know why ?? So now I need to know if it is possible to destroy the banana if a collision with the basket happened and instantiate a new banana in the basket as a child at run time ?!! I need to try this stupid way because I've tried all the other ways and nothing worked (


Shooting at mouse in unity I'm using unity and trying to get my bullet to shoot at a target. I am clicking the mouse and I'm wanting to fire my bullet in that direction. I have gotten the coordinates of the mouse click and tried to compute the vector. Then I've tried instantiate the bullet prefab (which has rigidbody component and is in front of the scene) at my position and then fire it in the direction of the mouse. I can see that my objects being instantiated in my Hierarchy Pane but can't see anything on the screen! Not sure if I'm doing the vector thing right (newb here), but if I click on Yoshi's head, I'm getting ( 2.0, 0.4). Does this sound right? Code void fireBullet(float mousePositionX, float mousePositionY) Vector2 position new Vector2(mousePositionX, mousePositionY) position Camera.main.ScreenToWorldPoint(position) GameObject bullet Instantiate(bulletPrefab, transform.position, Quaternion.identity) as GameObject bullet.transform.LookAt(position) Debug.Log(position) bullet.rigidbody2D.AddForce(bullet.transform.forward 1000)


Should a beta version of an engine be used to start a new project? Is it advisable to use a beta version of unity(2019.3b) to make an actual complete project? What are the disadvantages?


Building meshes conforming to terrain deformation I have an uneven terrain on which the player is supposed to build buildings. For most structures I can just fudge the foundations, have them extend through the terrain. For roads, pipes, tracks and such I do have however the problem how to make them line up. What techniques can I best use to make the meshes of adjacent pieces line up, making it conform to the terrain?


Unity finding force vector to separate colliders in OnTriggerStay events In Unity, I have Trigger Colliders, and catch the OnTriggerStay(Collider other) events. Once two Colliders are touching, how do I get the Force vector to make them want to separate again? In the example below, I have a Sphere and a Box Collider touching. The OnTriggerStay is being called for the Sphere. I cannot use the center positions of the transforms to get a direction, as that would not give me a very good force vector And I do not think I can use the Collider.ClosestPointOnBounds to figure out the Box touch position, because the point I look from (center of Sphere), could be inside the Box Collider itself, which I understand will just return me back the center of the Sphere again. I would not be able to resolve any force vector from that.


Unity Raycast not detecting layers I am having problems with layers detection using raycasts. Context I created a grid to use in a pathfinding algorithm on a 2D plane. I want to implement now different weights according to the layer each node of the grid is in e.g. a node in a normal terrain will have a "terrainPenalty" of 1 and more difficult terrains 2 or more. In order to detect the terrain type on the 2D plane, I am shooting a raycast on the node position for each node previously considered "walkable". The problem comes up now, because I observed that the paths created are neglecting such values, this is the slice of code which is giving me problems if (walkable) Ray ray new Ray(worldPoint Vector3.back 10, Vector3.forward) PROBLEM HERE (NOT DETECTING PENALTIES) RaycastHit hit walkableMask walkableMask if (Physics.Raycast(ray, out hit, 100, walkableMask)) walkableRegionsDictionary.TryGetValue(hit.collider.gameObject.layer, out terrainPenalty ) At first I thought that the problem was how the layers were called, because I created a LayerMask combining 2 layers using the bitwise OR operator, but then I tried to play around with all the layers (hence why there is walkableMask walkableMask now). The result was always a false output for Physics.Raycast(ray, out hit, 100, walkableMask). I thought that maybe I was getting the wrong coordinates for the ray, but I created some gizmos to actually check that the ray was piercing perpendicularly my plane and it did, as well as trying to change layers to see if anything worked, but the output is always false. What am I getting wrong? Here is the rest of the function, if needed I can upload the whole script as well void CreateGrid() grid new Node1 gridSizeX, gridSizeY Vector3 worldBottomLeft transform.position Vector3.right gridWorldSize.x 2 Vector3.up gridWorldSize.y 2 for (int x 0 x lt gridSizeX x ) for (int y 0 y lt gridSizeY y ) Vector3 worldPoint worldBottomLeft Vector3.right (x nodeDiameter nodeRadius) Vector3.up (y nodeDiameter nodeRadius) bool walkable !(Physics2D.OverlapCircle(new Vector2(worldPoint.x, worldPoint.y), nodeRadius, unwalkableMask)) bool walkable !(Physics.CheckSphere(worldPoint, nodeRadius)) int terrainPenalty 0 if (walkable) Ray ray new Ray(worldPoint Vector3.back 10, Vector3.forward) PROBLEM HERE (NOT DETECTING PENALTIES) RaycastHit hit walkableMask walkableMask if (Physics.Raycast(ray, out hit, 100, walkableMask)) walkableRegionsDictionary.TryGetValue(hit.collider.gameObject.layer, out terrainPenalty ) grid x, y new Node1(walkable, worldPoint, x, y, terrainPenalty) EDIT Here is how I create the layerMask foreach (TerrainType region in walkableRegions) walkableMask.value region.terrainMask.value is the bitwise OR operation, I could have simplified by writing " " walkableRegionsDictionary.Add((int)Mathf.Log(region.terrainMask.value, 2), region.terrainPenalty) Where TerrainType is the following class System.Serializable public class TerrainType public LayerMask terrainMask public int terrainPenalty I basically create an array of TerrainType objects that will store their layerMask and penalty and then upon positive output from the raycast I access the dictionary to retrieve the terrain penalty. For the terrain and obstacles I am using a 2D BoxCollider and 2D PolygonCollider respectively, they do not interact with any other layer. Thanks for any possible hints, I don't know what else to try .


Issues using NetworkServer.Spawn with Unity and Mirror Networking I am using Mirror to handle the networking aspect When I spawn an object on the network, I Instantiate it on the server and then use NetworkServer.Spawn to notify all clients to spawn the object. However, when this object is eventually spawned on the client side, it seems to be spawned at the wrong position for a few seconds and then corrected itself and move to the correct position as is reflected by the server. Is there something I am not doing? Is this normal? Also I noticed if I changed the Network Sync Mode to 0, then it will only spawn in the wrong spot for a split second. using System.Collections using System.Collections.Generic using UnityEngine using Mirror public class EnemySpawner NetworkBehaviour public uint theId public int maxNumEnemies public int spawnDelay public GameObject enemyToSpawn float curSpawnTime BoxCollider2D boxColl Start is called before the first frame update public override void OnStartServer() curSpawnTime spawnDelay boxColl GetComponent lt BoxCollider2D gt () void Start() if (!isServer) return theId netId Update is called once per frame void Update() if (!isServer) return if (transform.childCount lt maxNumEnemies amp amp curSpawnTime lt 0.0f) Vector2 spawnPoint new Vector2(Random.Range(boxColl.bounds.min.x, boxColl.bounds.max.x),Random.Range(boxColl.bounds.min.y, boxColl.bounds.max.y)) curSpawnTime spawnDelay SpawnEnemies(spawnPoint,netId) else curSpawnTime Time.deltaTime Server void SpawnEnemies(Vector2 spawnPoint, uint theId) GameObject gobj Instantiate(enemyToSpawn, new Vector2(60.7f,1.3f), Quaternion.identity) gobj.GetComponent lt EnemyController gt ().parentNetId netId NetworkServer.Spawn(gobj) The way I've organized things, in the hierarchy I have Enemies Area1 Spider(Clone) Spider(Clone) Area1 has the EnemySpawner script. The spider is registered a spawnable prefab. Both Area1 and the Spider have a NetworkIdentity with no boxes checked. Additionally, the Spider has a NetworkTransform and NetworkAnimator.


Hide "No custom tool available" window I have this annoying window in the bottom right of the scene view. From the manual, it seems like I opened it by clicking on the wrench amp scribe button next to the movement buttons. How do I make it do away now? Restarting doesn't make a difference, neither does creating a brand new project. The documentation say this appears it I've clicked on the tools icon and there aren't any custom tools (which I'm sure I have done). Surely is should vanish after a while though.


Unity3d or WebGL Where should I go? I am interested in making a simple 3D game this summer, and I'd prefer if it were playable in a browser. My choices I am considering are Unity and WebGL. Currently I have no experience in either. But I have taken an introduction course to OpenGL. As well I will later be taking a course that will use Unity. I have some C experience, but no web background. The factors I'm considering are ease to learn and the penetration each has. I know Unity games can be uploaded to Kongregate, which seems like a pretty big deal if I made a game that would be somewhat successful. But of course that may not be the case at all. Which way should I lean? Personally I think learning WebGL would be the easiest transition, but I am not sure


How to make the character move along the axis using touch? I have the following code it works, but I don't know how it works. This is the code I found void Update() if UNITY ANDROID if(Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Moved ) Vector2 touchDeltaPosition Input.GetTouch(0).deltaPosition float offset touchDeltaPosition.x 40f 18 Mathf.Deg2Rad transform.position new Vector3(0f, 0f, offset) transform.position new Vector3(0f, 0f, Mathf.Clamp(transform.position.z, 7.1f, 7.1f)) endif I need to move the player along the axis by touch, for example, like in the game Cube Surfer! What I want to get (I used android emulator) The code I wrote works well at 720x1280, but if you set the resolution to 1440x2960, the controls become too sharp. I know why this is happening because touch.delta is getting too big. My code if (Input.touchCount gt 0) var t Input.GetTouch(0) var delta t.deltaPosition if (delta ! Vector2.zero) var offset transform.position offset.x delta.x Sensitivity Time.deltaTime offset.x Mathf.Clamp(offset.x, 4f, 4f) transform.position offset How to fix it? ScreenToWorldPoint this does not fit because the player moves along a spline. Thank for help


Subsurface Scattering Transmittance I have a question related to SSS and especially transmittance. I've looked at several papers about that topic, most of them from Jorge Jimenez, which are very interesting and, I admit, a bit hard for me. Here is one of the papers http www.iryoku.com translucency I have some difficulties to understand the way it works and the way it calculates the distance the light traveled through the object. I think that I understand the very big lines but I am also a bit confused as I am trying to integrate this into the Unity engine and I have some difficulties to match Unity engine available values such as the shadows maps, the shadows coords, etc... to make them fit the way they are used in the paper. So here it is, I am a bit lost in the "in between" and I hope that somebody might be able to help me. Thanks a lot. EDIT added the shader code from referenced paper float distance(float3 posW, float3 normalW, int i) Shrink the position to avoid artifacts on the silhouette posW posW 0.005 normalW Transform to light space float4 posL mul(float4(posW, 1.0), lights i .viewproj) Fetch depth from the shadow map (Depth from shadow maps is expected to be linear) float d1 shwmaps i .Sample(sampler, posL.xy posL.w) float d2 posL.z Calculate the difference return abs(d1 d2) This function can be precomputed for efficiency float3 T(float s) return float3(0.233, 0.455, 0.649) exp( s s 0.0064) float3(0.1, 0.336, 0.344) exp( s s 0.0484) float3(0.118, 0.198, 0.0) exp( s s 0.187) float3(0.113, 0.007, 0.007) exp( s s 0.567) float3(0.358, 0.004, 0.0) exp( s s 1.99) float3(0.078, 0.0, 0.0) exp( s s 7.41) The following is done for each light 'i'. Calculate the distance traveled by the light inside of the object ('strength' modulates the strength of the effect 'normalW' is the vertex normal) float s distance(posW, normalW, i) strength Estimate the irradiance on the back ('lightW' is the regular light vector) float irradiance max(0.3 dot( normalW, lightW), 0.0) Calculate transmitted light ('attenuation' and 'spot' are the usual spot light factors, as in regular reflected light) float3 transmittance T(s) lights i .color attenuation spot albedo.rgb irradiance Add the contribution of this light color transmittance reflectance


How to get light level (brightness) of a particular location? I'm making a 2D top down survival game similar to Rimworld, I'm trying to emulate a day night system. Many features depend on whether any tile is light (or dark) enough, based on time of day or other light sources such as torches, so I'm wondering if there's an easy way to detect how much light there is on a certain tile without making a whole system that tracks light on a per tile level (or maybe the latter option is better)? I am using Unity 2020.3.6f1 and the URP, which means I'm going to be using the 'new' 2D lights. EXAMPLE When it's nighttime, I'm going to disable the global light (sun) so those tiles will be pitch black. When it's daytime, the global light will have an intensity of 1 so that tile will have 100 brightness (look normal). When it's nighttime, but there's a torch, the tile where the torch is sitting on will have 100 brightness, and that will slowly fade to 0 over a span of 5 tiles. Making a system that updates every single tile in the game with information about the light level seems pretty expensive. Is there a way we can observe a block quot graphically quot , or in other words, literally look at the pixel on the screen, and determine it's alpha value to check for light level? Any suggestion is super welcome. EDIT Every tile does not need to know its brightness every frame, but they do need to know it less often. Some examples are A plant checking every couple of frames to see if it can grow A character checking every couple of frames to see if he's in the dark (and if he is, he needs to start panicking) More importantly, I need my characters to make decisions based on light amount. For an example, if there is a job that needs to be done at a certain location, a character should first check the light level of that location before going to do it.


Using coroutines and texture array for talking animation? I was thinking of having random textures from a texture array being chosen every 0.5 seconds through a coroutine to imitate talking if something like talking true. Not sure how I could set this up and such so I appreciate any help!


Change Camera Contrast in VR Game Hello there Firends , I'm developing a Virtual Reality game in Unity. As in every VR game , i have 2 cameras for stereo rendering. I want to show the same object in each camera having different color contrast ratio gt The effect is similar to the one shown in this image the grid in the center here is the same in each side but each camera is seeing it differently.i.e. its grey in the left and black in right (you will notice the black grid if you look closely) here is another example (source wired.co.uk) How do i get this effect ? Any suggestions ?


Adding more effects to a Unity3d mixer I recently started exploring the wonderfull world of audio in unity. I noticed that you can add a bunch of effect modules to a mixer. Now I'm wondering if you can add your own custom effects( for example export a plugin from a audio program or something) and add them to the list. I cant seem to find anything related to the question.


Restrict the rotation of the camera using button I've been trying to limit the Y axis of the camera rotation but I'm out of depth until now. I'd looked up many tutorials and I found the clamping method, but I seem can't get it to work on my code, and all the tutorials I found is using them in Update(), while I'm using a button to rotate the camera. Here's the code public void RotateLeft() cameraY Mathf.Clamp(cameraY, minAngle, maxAngle) if(cameraY gt minAngle) Camera.main.transform.Rotate(0, cameraY,0) public void RotateRight() cameraY Mathf.Clamp(cameraY, minAngle, maxAngle) if(cameraY lt maxAngle) Camera.main.transform.Rotate(0,cameraY,0) Does clamping works outside an Update()? What am I missing? Thank you in advance.


How can I get the borderSize s of a plane? public Texture2D gridImage public GameObject floor private int borderSize private void Start() GenerateGrid() void GenerateGrid() Color gridColor Color.cyan Color borderColor Color.black Collider floorCollider floor.GetComponent lt Collider gt () MeshRenderer floorRenderer floor.GetComponent lt MeshRenderer gt () floorRenderer.material.mainTexture gridImage floorRenderer.material.mainTextureScale new Vector2(floorCollider.bounds.size.x, floorCollider.bounds.size.z) floorRenderer.material.mainTextureOffset new Vector2(.5f, .5f) Vector3 foorSize new Vector3(floorCollider.bounds.size.x, floorCollider.bounds.size.z) for (int x 0 x lt gridImage.width x ) for (int y 0 y lt gridImage.height y ) if (x lt borderSize x gt gridImage.width borderSize y lt borderSize y gt gridImage.height borderSize) gridImage.SetPixel(x, y, new Color(borderColor.r, borderColor.g, borderColor.b, 50)) else gridImage.SetPixel(x, y, new Color(gridColor.r, gridColor.g, gridColor.b, 50)) gridImage.Apply() In the end I want to create something like this on a 3D Plane UI


What happens to deleted or added assets in your app when updating to a new version in the Google Play Store and iOS App Store? So let's say I used Unity and built an app and uploaded it to the android and iOS app store, it is 100 MB and lots of people downloaded it. So now I want to update it to the newer version, however along the way I decided a lot of features were unnecessary so I remove about 50 MB worth of assets and the new build is 50 MB so I uploaded it to the respective app stores. Will the people who already had my 100 MB app and now update to the new 50 MB version continue to have 100 MB of storage space taken up, even though the new one is half the size or will their app size be reduced to 5 MB according to the new build? Essentially, how does app store updating work? Is the whole old app deleted and new one downloaded? Are matching files and assets retained and only differences in files and assets deleted or updated? Or are new assets and files just piled on top? Additionally, for larger games, where the whole game is too big to be allowed on the app store, and where the player has to download more stuff once they have downloaded the game, how does it work? Is the additional, no longer needed content left on user's device kept there? Is it automatically removed?


GPU (render time) increase if screen size increase i create a simple 2d scene in unity 2017.3.1f1 I changed the size (height and width) in the Game View and proflie to see how it affects the rendering.. (below photo) I saw that the rendering time increases by increasing size, and now if this happens when playing the game on a different resolution android phone, each The higher the resolution of the phone, the more likely it is to get gpu bound !??? And i do not understand Cpu graph in the two situations in above photo(lower GPU gt higher CPU !!!) I tested my game on the quot huawei mate 10 lite quot (android device) with a resolution of 1080 x 2160 and it looks like there is a lot of rendering time.(a simple scene with only 5 sprite renderer) (unity dosen't show GPU profiling when game run on android device and we can't check these...) I did all the optimizations I heard, like DynamicBatching, Sprite Atlas , Quality Setting , sprite Texture Comprestion Override for Android.. What can be done to ensure that rendering time does not exceed a specified limit on different phones ??


Unity Sprite disappears completely when just a part of it is outside the camera's FOV I'm making a game in Unity, and when the player walks past a sprite, the sprite disappears, and when the player walks back toward it, it reappears. You can see a video of the problem here https www.youtube.com watch?v jgLN3m94tBo I've also included my camera script below if anyone wants to check that out. Any help on this matter would be more than appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class Camera MonoBehaviour private Transform target private float minX 7.99f private float minY 19.09f public float maxX, maxY void Start() target GameObject.Find("Player").transform void LateUpdate() transform.position new Vector3(Mathf.Clamp(target.position.x, minX, maxX), Mathf.Clamp(target.position.y, minY, maxY), transform.position.z) Here's a screenshot of my camera's settings


Unity gameobject design approach for item drops In a game like Minecraft, the player could have any of several hundred types of items in their inventory. Players can drop those items into the world, but obviously how they're rendered in the world differs from how they're rendered in the inventory. I'm trying to understand how to design for this scenario using Unity's GameObject concept. Individually, it seems like the expectation is that I would have one GameObject (with at least a SpriteRenderer) for every unique item that can appear in world. I would have one GameObject (with at least an Image component) for every unique item that can appear in inventories. With so many, I also need to come up with some sort of directory so that I can associate bulk prefab objects for use in game. Is this accurate? I feel like that's a lot of overhead. Would I be able to create one GameObject with both a SpriteRenderer and an Image and maybe toggle between then based on whether its in world or an inventory? I had also considered using one generic GameObject and replacing the sprite image based on the item needed, but that feels like it's misusing what GameObjects are meant for. It also likely subverts the benefit of pooling them, etc. Is there another approach I'm missing?


Unity Is type casting every frame too expensive? I have a state machine that controls my enemy AI. Each AI has a target which may be a Player, an obstacle, a shell, or even a Vector2 position. I'm trying to abstract my "target" member, and my first thought was to use GameObject, then downcast to whichever type I need for different enemies. Examples below class StateController MonoBehavior GameObject target FireAction action Update() action.Fire(this) class FireAction ScriptableObject public abstract void Fire(StateController c) Examples of different fire scripts class FireAtPlayer FireAction public override void Fire(StateController c) Player p c.target as Player use properties of Player object class FireAtPoint FireAction public override void Fire(StateController c) GameObject t c.target as Player use properties of GameObject object As you can see, my Fire methods would cast the target object at every call to Update. Will this negatively affect my game's performance? Note that I know for a fact what type of object the target is, so I'm not guessing when I'm casting. Thank you in advance of your help!


Is it possible to load asset bundle dependencies manually in Unity 5.0? Is it possible to tell Unity to not load asset bundle dependencies automatically so they can be loaded manually. If so, how can this be done?


Unity3d Position a gameobject such that its forms a right angled triangle with other two gameobjects How do I position C gameObject such that it forms a right angled triangle with A and B. I tried to use (B.transform.position.x,A.transform.position.z) but it still gives me something which is close to A (it takes it globally). I want the C to be along the local red axis of A and local green axis of B as seen in the picture. What do I do?


Day and Night mode according to user's real local time How do I make it so the texture of my plane is a black sky when it's night according to player's local time (say from 10 PM to 5 AM it's going to be black, and from 6 AM to 9 AM it's going to be a blue sky)? Blue sky texture name is "bluesky" Black sky texture name is "blacksky" Thanks.


When the motion button is pressed, the shape of the character changes and always goes to the left direction good day. When the motion button is pressed, the shape of the character changes and always goes to the left direction. Why is this happening and what is the solution? Pressing two buttons moves to the left and the shape changes. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerKontrol MonoBehaviour public float karakterHizi 8f, maxSurat 4f private Rigidbody2D myRigidbody private Animator myAnimator private bool solaGit, sagaGit void Awake () myRigidbody GetComponent lt Rigidbody2D gt () myAnimator GetComponent lt Animator gt () void FixedUpdate () if (solaGit) SolaGit () if (sagaGit) SagaGit () public void AyarlaSolaGit (bool solaGit) this.solaGit solaGit this.sagaGit !solaGit public void HareketiDurdur () solaGit sagaGit false myAnimator.SetBool ("run", false) void SolaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0)) void SagaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0))


Handmade Terrain vs. Terrain Engine in Unity? I'm planning a game right now, to be made in Unity, and I'm trying to decide how I'll approach the basic level construction. Essentially, my game takes place on an island in an infinite ocean, very similar to Wuhu Island My question concerns all the stuff heightmaps can't handle. To use Wuhu Island as an example, note the lighthouse cliff, and the nearby similarly jutting out cliff. The volcano itself is also empty, and there are some tunnels through it on the other side. I was thinking I would just model the entire island myself in Cinema 4D, but as I read more about the terrain system, it seems Unity has special optimized rendering systems in place for terrain objects. Would I be shooting myself in the foot performance wise if I just built my island entirely by hand? This will be for mobile, so the little stuff might well count. Am I even approaching this question correctly if not, how would you best go about creating (something very close to) Wuhu Island as a level in Unity? Is there any reason for me to not do it as one mesh? I have effectively zero experience with 3D game dev only rendered 3D video stills for other applications, so this is a learning process.


How can I use different fonts for different objects in Unity? In Unity 3.5, I have a font that is strangely linked to four game objects. I want to put separate fonts on each object. In the Inspector, when I click on the circle icon next to the "Text" attribute, I can select a font. But, then it changes the font on the other three objects as well. I was hoping Unity would have something like a material ID from 3DS Max. If I could put a new material ID on the other objects, hopefully I could assign a new font to the text mesh. Regardless, is there a way to assign a different font to each of my objects?


Is it possible to import UV maps in Unity3D without manually importing the associated texture? When i import an object from Maya with a defined UV map i have to manually import the texture (image) and assign it to the material. Is there a way to keep the materials texture reference from Maya when importing into Unity?


Tile Palette problem in Unity I am working on isometric tilemap in Unity 2019.4.8f1. In the Tile Palette panel, the selection is always 1 block away. Please see this screenshot In the screenshot, apparently I selected an empty tile, but in fact I am select the green tile with flowers. How come? Every selection is one tile away. The same issue happens in the Tilemap selection mode too. I have to select the adjacent tile in order to select the tile I want. How do I fix it? It's quite annoying. UPDATE I have added the settings of Grid, Tilemap as well as the import settings of the tile sprite sheet below. UPDATE 2 Changed the Pivot in Sprite Editor to Bottom Center Recreated the Tile Palette, and it looks like hovering 0.5 unit up.


How can I find an animation's final compression size in Unity? I've been looking at animation compression, and the only way I can seem to find it's final size is to create a Build and check it in the Profiler. There must be an easier way?


Cannot overlay text? I'm trying to make text have a fixed position in world space and be overlayed in screen space at the same time. I have text in canvas with "Screen Space Overlay" which covers my text located in canvas (world space). What should I do? Is this a dead end? Please comment if you didn't understand (I know it's hard to get)


OnTriggerExit2D called multiple times when two triggers touch I have two GameObjects tagged "Point", each with a Collider 2D set to Is Trigger. I have another GameObject, "pencil", which also has a Collider2D set to Is Trigger I want to move the pencil the first point to the start drawing a line, and then stop drawing when it hits the second point. My problem is that when the pencil hits a point, it calls OnTriggerExit2D multiple times. How can I only detect first contact with the point? Pencil script private void OnTriggerExit2D(Collider2D collision) if (!collision.isTrigger) if (collision.gameObject.tag "Point") writing !writing


Getting user id from one scene then to the next scene I'm new to multiplayer and photon so pardon me if this question is somewhat frequent. I have successfully set up my project to start from a main menu waiting room actual gameplay scene. However I couldn't search my way through getting a sort of user id from waiting room(ie order of user joined to waiting room) then use it in the gameplay scene to manipulate sort by score by hp etc. Perhaps I got the while concept of having to identify unique players via such variable? I'm not quite sure. I just got my foot in the multiplayer development realm, so please go easy on me. Edit Sorry for my initial question being quite vague. Basically, I'm trying to replicate this with Photon. I've got various things set up but was stuck at where designating individual players to individual player info panels as if captured(Get WHAT to connect to those UI elements I've got set up). It'd be simple enough even for me if this was a singleplayer, but since it's not I'm also refactoring a lot on the way as well. Thanks to both of the answers given so far I'm looking into Photon UtilityScripts(To a novice to anything simply directing where to look helps a ton, so thanks again), but since I'm not quite there yet I'll update my progress.


Export "Lite" and "Full" versions with different package names for Google Play Console On the Google Play Console, you can't have two games with the same package name. Is there a way to have two of the same game with different package names, exported from the same Unity project? For example, a quot lite version quot with ads and a quot full version quot without ads.


Unity Animation Controller and walking diagonally keeps switching between the two diagonals? Using Unity 2019.4.1f1 Personal. I have the above Animation Controller. When only walking in one direction at a time and when you stop you stay facing that direction, this works as planned. All of the transitions do not have an exit time and have a fixed duration of 0. I don't know what info to give as this is the first time I've used animation. Let me know and I'll add relevant details. Here's my update function that updates the variables in the animator void Update() float h Input.GetAxisRaw( quot Horizontal quot ) float v Input.GetAxisRaw( quot Vertical quot ) animator.SetFloat( quot Horizontal quot , h) animator.SetFloat( quot Vertical quot , v) if (Mathf.Abs(v) lt Mathf.Abs(h)) flips the renderer to reuse other handed image spriteRenderer.flipX h gt 0 no actual movement until I figure this out What I'm experiencing that I want to fix is when running diagonally It seems that when walking diagonally then the animator variables for Horizontal and Vertical are both either 1 or 1 and this causes the alternating of the sprites. What I'd like to happen is that the state machine would deterministically pick either N S sprites or E W sprites when moving diagonally. Turning on quot Can Transition To Self quot seems to properly pick a direction and stick to it but it fails to animate when only moving in a single direction. It looks like it's constantly transitioning to itself which starts over the cycle so I've left that unchecked on all transitions. I'm not sure what the best way to fix this is. Most attempts I've tried so far complicate the state machine to the point it's unmaintainable. I also couldn't find anything about introducing priorities in a way that fixed the jitter. What's the idiomatic Unity way to achieve clean diagonal movement in 2D?


How do i draw a ray in unity So i am trying to scrap together something for vr in which the locomotion is about the player holding the direction where he wants to go to(basically planning what he is going to do)while holding down the button a ray is beeing drawn and when the player lets go the character moves until he reaches the end of the ray i tried looking up something but couldnt find anything regarding something like this


How to calculate a movement Vector3 to kill unnecessary momentum and start moving in the right direction? Imagine a rocket is accelerating in a straight line toward PointA, picking up momentum every frame, then suddenly decides it wants to go toward PointB instead. It can't just turn straight toward PointB and start accelerating, because the new acceleration plus the pre existing momentum will carry it wildly off course, and not straight toward PointB. It could turn exactly 180 around to aim directly away from PointA and thrust until it comes to a stop, then turn toward PointB and start accelerating from scratch. But that's very inefficient, especially if the two points are in generally similar directions. It would be more efficient to turn and start accelerating in some specific direction that will bleed off the unnecessary momentum but keep any useful momentum, course correcting so that it is now moving toward PointB. I'm trying to figure out how to calculate that quot specific direction quot that the rocket needs to start accelerating toward, in order to efficiently reach PointB. I have the rocket's position, the Vector3 of its inertia, and the Vector3 locations of PointA and PointB, but I'm not experienced enough in Vector Math to totally understand what's needed. Especially since we're talking about acceleration (not just speed), so the angle will no doubt need to be recalculated each frame as the changing momentum leads to a changing angle toward PointB, etc. Can anyone help me out?


How to use Facebook Web Hosting for my Unity Game for both WebGL and GameRoom As can be seen from the Facebook's official Docs It says that To have both a Gameroom and a Facebook Web Game, you should leave your Facebook Web Games URL (https) unchanged. For example, https friendsmashsample.herokuapp.com and also Otherwise, if you only have a Gameroom title, you should enter https localhost as shown here I wanted to know if there is a way to get both of them working instead of hosting WebGL game on my server and putting it's URL? I have even tried to enable the Simple Web Hosting but the toggle just reverts Back to off upon saving.


Is it possible to apply a texture to a 2D sprite in unity 2 d? I want to take an (animated) 2 d sprite and apply a texture to it. Basically, I want every non transparent pixel to be covered by the texture (color is disregarded). I understand I can probably accomplish this using masks but I am worried that may not be the most performant solution. I know you can put textures onto 3 d models, so I was wondering if there was a similar process for 2d sprites. Below I have a graphic demonstrating what I want. What I have tried so far I see there is an option to add a material to a sprite, so I tried creating various materials. 1. Default material When I tried applying this material to my sprite, the sprite disappeared entirely. I suspect because this default material type only works on 3D objects 2. Sprite Material I figured sprites probably expect sprite materials, so I tried creating one. However, there does not appear to be anywhere to upload an image to use as a texture. This appears to only be useful for adding tints to sprites.


When is the CheckResources() function called? This question is asked in the context of image effect shader implementations in Unity. Looking through the scripts for image effects in the standard assets package, I notice that initialization is generally done in the CheckResource() function. The following is a snippet of code from the BloomAndFlares image effect. public override bool CheckResources() CheckSupport(false) screenBlend CheckShaderAndCreateMaterial(screenBlendShader, screenBlend) lensFlareMaterial CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial) vignetteMaterial CheckShaderAndCreateMaterial(vignetteShader, vignetteMaterial) separableBlurMaterial CheckShaderAndCreateMaterial(separableBlurShader, separableBlurMaterial) addBrightStuffBlendOneOneMaterial CheckShaderAndCreateMaterial(addBrightStuffOneOneShader, addBrightStuffBlendOneOneMaterial) hollywoodFlaresMaterial CheckShaderAndCreateMaterial(hollywoodFlaresShader, hollywoodFlaresMaterial) brightPassFilterMaterial CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial) if (!isSupported) ReportAutoDisable() return isSupported I am probably wrong in assuming that this is essentially the Start() or Awake() functions for PoseEffectsBase, but I decided to try implementing something simillar. public override bool CheckResources() saturationPassMat CheckShaderAndCreateMaterial(saturationPassFilter, saturationPassMat) if (!isSupported) ReportAutoDisable() return isSupported Unlike the standard asset scripts, CheckResources() does not seem to be called consistently for me. Unity console throws UnassignedReferenceExceptions every frame, for the object saturationPassMat. When is the CheckResources() function called? Should it be used for initialization just like Start()?


How to change Texture2D type to Sprite during runtime (Unity) How can we convert the Texture2D type to "Sprite" using the script (not in Editor)? It seems that the Texture2D retrieved from file is by default Normal Map. I need to convert the TextureType to "Sprite". Texture2D texture LoadPNG("D download.jpg") testPlaneRenderer.material.SetTexture(" source",texture) LoadPNG method code public static Texture2D LoadPNG(string filePath) Texture2D tex null byte fileData if (File.Exists(filePath)) fileData File.ReadAllBytes(filePath) tex new Texture2D(2, 2) tex.LoadImage(fileData) ..this will auto resize the texture dimensions. Debug.Log("File Exists!") else Debug.LogError("File not exists!") return tex It seems that this texture is set as "Default" or "Normal" Type when imported from file and then assigned to Material dynamically. As the particular shader I'm using, works best if the Texture Type is set to Sprite (I tested it by manually placing the texture file in Project and then assigning the texture to Material). I need to change Type of Texture to Sprite before assigning it to the material. I've seen options like "AssetImporter" but it only works in Editor. The effect of the shader (which takes two texture types a) Inverted amp Blurred Texture b) GrayScale Texture And then returns a Sketch Effect to the object. I convert the original image to inverted amp blurred, grayscale texture using some image processing code (C , Unity working around with GetPixels and SetPixels)... Output with Defualt Texture Type Output with Sprite Texture Type


Unity ScriptableObject Conversation Dialogue and Reading I'm unsure as to how I would reference a scriptable object's variables within a struct from another class. I know I'd have to make a public Conversation, but I'm stuck understanding how I could access it's struct, and how I could access individual variables such as the Position, or line string array. Is this method even viable or should I look at creating a different way of accomplishing a dialogue conversation scriptable object? Thanks for any insights and help My current code System.Serializable CreateAssetMenu(fileName quot New Conversation quot , menuName quot Create Conversation quot , order 1) public class Conversation ScriptableObject System.Serializable public struct LineData public string line public string option public enum Position BottomLeft, BottomCentre, BottomRight, MiddleLeft, MiddleCentre, MiddleRight, TopLeft, TopCentre, TopRight public Position position public enum TextSpeed Normal, Slow, Fast, UltraFast public TextSpeed textSpeed public LineData Line


In Unity3D, try to load a png into a Texture2D in an Editor script and then run PackTextures, but they need Readable flag to be set I am trying to automatically create a texture atlas from a set of generated png files in an Editor script. The problem is that I can't seem to be able to load a png into a Texture3D without it being inaccessible by the PackTextures method. I have tried a few different ways to load the PNGs, such as Resources.LoadAssetAtPath(...), AssetDatabase.LoadAssetAtPath(...) and a few more. Since all of this is done in OnPostprocessAllAssets, I don't want to have to do any manual editing of the textures. I just want to be able to drop a PNG into a certain folder and get an updated atlas. Answers such as this seem to suggest manual editing. The actual error message is "Texture atlas needs textures to have Readable flag set!". So the question is, is it possible to do this kind of post processing in Unity3D? Is there any way to import a PNG into a Texture2D with the Readable flag set, without having to manually change it?


How should I handle animation state systems in derived classes? I'm trying to get some kind of state system for my game objects. I have a base Actor class that is derived by classes like Policeman, Informant or Brawler. Each of those classes describes different functionality, but I want as much of the functionality to be shared. On of those is animation system. Each class has their own states (for example Policeman has Walking, Shouting and Shooting, while Informant has Idle and Whispering). What is the best way of handling such states? Do I have the Actor class have something like enum ActorState state1, state2, state3, ... And just map each behaviour of appropriate actor (Policeman, Informant, etc) to ActorState, so that the rendering system of ActorState can take over? Or maybe is there some better solution that people use. Game is 2D, sprite based, and I'm using Unity3D system, with Actor being a component to GameObjects.


Unity LWRP Projection Shader I recently added the Lightweight Render Pipeline to my project as I'd like to start experimenting with Shadergraph to see if I can get a better basic understanding of shaders. Everything has gone pretty smoothly except the Shader used by my Projectors, the Projection Shader Standard asset no longer works (does not project the texture) and I have very little experience with Shaders. The main concern for me is that I cannot find anyone else who seems to be having this problem. I have tried reading through the older shader and recreating it in ShaderGraph but I'm out of my depth. So could anyone provide me with a simple projection shader or materials on where I could learn to write one, or just learn more about them projection specifically. thanks edit To clarify I was using the Projectors to project a simple square texture on to each tile that I could tint, to show selectable current target tiles. Old shader that no longer works under Lightweight Render Pipeline From DevGuy Unity Forums Upgrade NOTE replaced ' Projector' with 'unity Projector' Upgrade NOTE replaced ' ProjectorClip' with 'unity ProjectorClip' Upgrade NOTE replaced 'mul(UNITY MATRIX MVP, )' with 'UnityObjectToClipPos( )' Shader "Projector AdditiveTint" Properties Color ("Tint Color", Color) (1,1,1,1) Attenuation ("Falloff", Range(0.0, 1.0)) 1.0 ShadowTex ("Cookie", 2D) "gray" Subshader Tags "Queue" "Transparent" Pass ZWrite Off ColorMask RGB Blend SrcAlpha One Additive blending Offset 1, 1 CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct v2f float4 uvShadow TEXCOORD0 float4 pos SV POSITION float4x4 unity Projector float4x4 unity ProjectorClip v2f vert (float4 vertex POSITION) v2f o o.pos UnityObjectToClipPos (vertex) o.uvShadow mul (unity Projector, vertex) return o sampler2D ShadowTex fixed4 Color float Attenuation fixed4 frag (v2f i) SV Target Apply alpha mask fixed4 texCookie tex2Dproj ( ShadowTex, UNITY PROJ COORD(i.uvShadow)) fixed4 outColor Color texCookie.a Attenuation float depth i.uvShadow.z 1 (near), 1 (far) return outColor clamp(1.0 abs(depth) Attenuation, 0.0, 1.0) ENDCG


Touch to continue (coroutine) in unity When the object gets destroyed in my game, I want a touch to continue function after a delay. This is what I tried. this is the SceneManager class which is attached to the Main Camera public bool ttc public void NextLevel() StartCoroutine(Delay()) IEnumerator Delay() yield return new WaitForSeconds(2) print("touch to continue") ttc true My Object class void OnDestroy() Camera.main.GetComponent lt SceneManager gt ().NextLevel() if (Camera.main.GetComponent lt SceneManager gt ().ttc true) if (Input.GetKeyDown(KeyCode.V)) Application.LoadLevel("TheGame2") I also tried this IEnumerator Delay() yield return new WaitForSeconds(2) print("touch to continue") if (Input.GetKeyDown(KeyCode.V)) Application.LoadLevel("TheGame2") side note I will change the 'KeyCode.V' to a mouse button later


How I randomise a list of audio clips in Unity and remove it from the list once the clip is finished? I have 4 audio clips. When I play a press a certain button in Unity, the data is sent to MAX MSP and the audio is played. I created a list a signals (As shown below in the code). What I want is that, the signal list is randomised. The user presses a button to listen to the audio (which works fine). Once the clip is finished the user presses Next Trial button. Once the Next Trial is pressed. The previous clip is removed from the list. Once all the clips are finished. A message is displayed in the Debug.Log( quot All trials finished quot ). I have the following problems One of the audio clips is repeated again. It appears that the audio clips are not removed from the list. How do I write the audioclip index to a csv file? Code public class SignalToMax MonoBehaviour private static int localPort private string IP define in init public int port 8050 define in init quot connection quot things IPEndPoint remoteEndPoint UdpClient client experiment case public string experimentCase quot A quot string strMessage quot quot public List lt int gt signals public static int stimIndex void Start() NextTrial GameObject.FindGameObjectWithTag( quot NextTrial quot ).GetComponent() signals new List lt int gt 1, 2, 3, 4 define IP quot 127.0.0.1 quot port 8050 Senden remoteEndPoint new IPEndPoint(IPAddress.Parse(IP), port) client new UdpClient() NextTrial.onClick.AddListener(Advance Trial) void Advance Trial() int signalIndex Random.Range(0, signals.Count) int currentSignal signals signalIndex stimIndex currentSignal signals.RemoveAt(signalIndex) string text signalIndex.ToString() byte data5 Encoding.ASCII.GetBytes(text) client.Send(data5, data5.Length, remoteEndPoint) Debug.Log( quot lt color magenta gt Current source signal is lt color gt quot currentSignal) if (signals.Count gt 0) Debug.Log( quot lt color blue gt Signal count before removal was lt color gt quot signals.Count) Debug.Log( quot lt color yellow gt Source signal removed lt color gt quot ) else Debug.Log( quot lt color green gt All Trials finished lt color gt quot )


ScreenToWorldPoint and ViewportToWorldPoint I'm currently following tutorials on Youtube to learn howto use Unity. My code runs perfectly as per the tutorial, but i just have some questions regarding the code, with regards to screenToWorldPoint amp viewportToWorldPoint. The purpose of the code is for a 2D platformer, where the character's arms will rotate and face where the mouse cursor is. Code using System.Collections using System.Collections.Generic using UnityEngine public class ArmRotation MonoBehaviour public int rotationOffset 0 Update is called once per frame void Update () Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position Gets the difference between difference.Normalize() Normalizing the vector float rotateZ Mathf.Atan2(difference.y, difference.x) Mathf.Rad2Deg transform.rotation Quaternion.Euler(0f, 0f, rotateZ rotationOffset) I've done some googling and am aware of the difference between screenToWorldPoint and viewportToWorldPoint as per the answer here https answers.unity.com questions 168156 screen vs viewport what is the difference.html Where Screen from 0,0 to Screen.width, Screen.height Viewport from 0,0 to 1,1 Questions Why do we have to calculate the difference between the position of the mouse cursor and the position of the character's arm instead of just setting the following . Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) I've tried setting it to the position of the mouse cursor instead of using the difference between the arm amp the cursor and while the code still works and the arm is still able to rotate, it is a little "off" from the direction of the cursor. E.g A little higher than where the cursor is. Why does using the difference solve this issue? Why do we call difference.Normalize() ? To my understanding, Normalize returns a vector between 0 amp 1.However, Mathf.Atan2 returns the angle in radians whose Tan is calculated by y x. As such, calling Normalize and returning a vector to a value between 0 amp 1 makes no difference because the value calculated will be the same between a un normalised and normalised vector since the proportions are the same? When i use ViewportToWorldPoint instead of ScreenToWorldPoint, i do not use Normalize because to my understanding, the Vector returned by ViewportToWorldPoint should already be within 0 amp 1, hance we do not have to normalise it. However, when i test the code out in play mode,the arm barely rotates. Why is this so? I would appreciate any help or pointers in the right directions. Thanks! EDIT I had a look at the manual and realise that Normalize() returns a vector with the same direction, but magnitude 1, but i'm still just as confused


AndroidManifest file was deleted by accident I deleted the AndroidManifest file of my project which was located in Assets Plugins Android , so I tried creating new project and copying the Assets and everything but it seems that something is missing ,it's perfectly working in the editor , but as apk there are few things aren't working, I can't figure out why, and there isn't even a Plugins folder in my new project !


How to remove a component of an object in a script? I want to remove a Sphere Mesh Renderer component from a certain gameobject. I want to do this in a script. How do I do it? I do not want to destroy the sphere itself, just the component


On button click wait I have a button I got from google material design asset pack which has a ripple animation when pressed. I'm using the button's click option in the inspector that calls a method that switches scenes. But when I tap the button it switches the scene immediately and feels unnatural since the animation hasn't finished the button ripples animation. I tried using co routines. Made the button call a method in which I call a IEnumerator method (since the button can't directly call a co routine) and then switch the scene. But that doesn't work since it starts the co routine and switches the scene, the co routine never pauses the code and never finishes (probably because I loaded a new scene and the object that carries the script isn't transferred). Code example The method that gets called when I tap a button public void OnButtonTap() StartCoroutine(Wait(0.2f)) SceneManager.LoadScene("OnePlayerGameIntro") The wait coroutine public IEnumerator Wait(float seconds) yield return new WaitForSeconds(seconds)