_id
int64
0
49
text
stringlengths
71
4.19k
0
How to make a text box where text "types" smoothly I want to create a textbox that behaves like most textboxes seen in other games where the text appears gradually. So far this has been my attempt at it but unfortunately, the text appears very unevenly and slow even when changing the letter pause to an insanely low amount. public float letterPause 0.1f IEnumerator TypeText() number of char typed per loop int len 3 for (int i 0 i lt text.Length i len) if (i len gt text.Length) ibubbletext.text text.Substring(i, text.Length i) else ibubbletext.text text.Substring(i, len) yield return new WaitForSeconds(letterPause)
0
Unity Set rotation of object using angle between two points? I have a LineRenderer that draws a line between two points, Vector3 startPos and Vector3 endPos. How can I get the angle between these points, and apply it to an objects transform rotation, so that it points in that direction? Here is my code that draws a line between 2 points by dragging your mouse, if you want to test just Replace the Interact methods with Input.MouseButtonDown(1), hold and up. Vector3 startPos Vector3 endPos float angle LineRenderer lr private void Awake() lr GetComponent lt LineRenderer gt () lr.useWorldSpace true public override void InteractOnDown() base.InteractOnDown() lr.enabled true lr.positionCount 2 startPos PointerHandler.RaycastScreenPoint(Input.mousePosition, UnitManager.instance.movementMask, GameManager.instance.cam).point lr.SetPosition(0, startPos) public override void InteractOnHold() base.InteractOnHold() endPos PointerHandler.RaycastScreenPoint(Input.mousePosition, UnitManager.instance.movementMask, GameManager.instance.cam).point lr.SetPosition(1, endPos) public override void InteractOnUp() base.InteractOnUp() lr.positionCount 0 lr.enabled false
0
Unity How to make an array of video clips and play them? I have 26 video files which I have to put in an array and play for different objects. So far I have written this from what I know using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Video public class videomanager MonoBehaviour public VideoClip vids private VideoPlayer vp Use this for initialization void Start () vids new VideoClip 25 vp gameObject.GetComponent lt VideoPlayer gt () Update is called once per frame void Update () I have attached this script on a plane on which I am playing the video. Before that, I had 26 different planes, one for each different video, but I think it would be better if I could play them on a single plane and change the video according to logic. I am not sure how I should load them into my player and play them.
0
2D Camera Movement Temporal Reprojection Having an Orthographic Camera with its View Projection Matrix given from the current and last frame, how to reproject the previous frame to the new one?
0
In Unity, Change which mouse button is used to scroll in ScrollRect I've created a new ScrollView in Unity. How do I change which mouse button is used to scroll in ScrollRect (through script or in the editor). By default it's the left mouse button. I'd like to be able to change this to another mouse button. I'd also like to be able to use a keyboard key and disable it altogether (via script without also disabling the scrollbars), but mainly I at least want to change it from the left mouse button.
0
How can I make billiard without using Rigidbody? Unity's physics engine isn't deterministic (ie. the results aren't always the same on all computers) so I haven't Idea that how billiard games Implemented.Is there a way to Implementing fake and deterministic physic in unity? I mean I want to make billiard without using Rigidbody http www.bezzmedia.com swfspot tutorials flash8 8 Ball Pool I found this open source project that didn't use physic! this is what I need but unfortunately it's full c and I haven't enough time to convert it to c http downloads.sourceforge.net foobillard foobillard 3.0 win32 2 bin.zip
0
Unity 2D Sprite Bending between Hinge Joints I've created a tentacle that consists of multiple game objects, each attached to eachother using HingeJoint2D's. Gameplay wise this multiple segmented approach is great because I can use Unity's built in physics, but it doesn't look very good art wise. Is it possible to 'bend' 2D sprites, so the tentacle segments look like they're attached to eachother? Or perhaps take a single image and bend it using splines of some sort? I would prefer to keep using multiple game objects to represent the tentacle.
0
Unity Ads showing test ads I am implementing Unity Ads in my game and for some reason I have the test ads showing up in my production version of my app. I have the advertisements initialized with test ads turned off and I have even gone into my settings on the Unity Ads admin and set it to force test ads to be off. I'm not sure what else to do here. Here is how I am initializing Advertisement.Initialize("myID", false)
0
Unity sizeDelta of an Image update opposite to what it should I have an IEnumerator coroutine in which I call the UIManager script to update the Image size to fit the text size but it doesn't happen. when I use yield return new WaitForEndOfFrame() it sometimes solve the problem. but I don't want to use it. edit I tested the code like I was suggested in an empty unity project and it still happens, the width should change according to the text size but it happens opposite (when the text is small the width of the image is large and when the text is large the width of the image is small) (it only happens correctly at the first time the width of the image fits the text width) public class Example MonoBehaviour public Image image public Text text private int k 0 public void ButtonClick() text.text (k 2 0) ? "10" "10 10" image.rectTransform.sizeDelta new Vector2(text.rectTransform.rect.width, 30) k edit Solved! thanks for the help, Canvas.ForceUpdateCanvases() did the trick
0
Filling Closed Shapes Game Engine Unity 5.1 Developing on Windows 7 Hello, I am using Vectrosity to draw some some shapes on screen run time. I also need to fill these shapes and none of them are really trivial shapes. So after doing some research I figured the best way would be to do it by creating a run time mesh. Now this almost works for me but has a big issue. This is my process. 1) I have defined my complex shapes as a set of 2D vertices that I extracted from Illustrator. These vertices I feed to the Vectrosity's Catmul spline function to create my shapes. 2) I then project these vertices in the real space using ScreenToWorldPoint to get 3D vertices. 3) I then pass these vertices to a program that Triangulates these points to a mesh (I use the classic Triangulate script on wiki) 4) I then clean up a little and align Now all this works well if the camera is not rotated and the forward vector of the camera is orthogonal to the XY plane. The moment I rotate the camera the alignment of the mesh and the vector lines is completely gone. Here is the image of the vectorline and mesh when the camera is not rotated And here is the image when the camera is rotated Here is the function that projects the point into 3D space void DrawPolygon () Vector2 tempVerts new Vector2 allLinePoints.Count for(int i 0 i lt allLinePoints.Count i ) Vector3 projectedPoint Camera.main.ScreenToWorldPoint(new Vector3(allLinePoints i .x, allLinePoints i .y, 10.0f)) tempVerts i new Vector2(projectedPoint.x, projectedPoint.y) polyTarget.SendMessage("Create", tempVerts) This message is sent to a generic Triangulation script. Here it is using UnityEngine using System.Collections using System.Linq public class CreatePolygon MonoBehaviour public Material meshMaterial public void Create (Vector2 verts) Triangulator tr new Triangulator (verts) int indices tr.Triangulate () Create the Vector3 vertices Vector3 vertices new Vector3 verts.Length for (int i 0 i lt vertices.Length i ) vertices i new Vector3(verts i .x, verts i .y, 0) Create the mesh Mesh msh new Mesh() msh.vertices vertices msh.triangles indices msh.RecalculateNormals() msh.RecalculateBounds() Set up game object with mesh gameObject.AddComponent(typeof(MeshRenderer)) MeshFilter filter gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter filter.mesh msh GetComponent lt Renderer gt ().material meshMaterial StartCoroutine (FlipNormal ()) public void ResetMesh (Vector2 verts) Triangulator tr new Triangulator (verts) int indices tr.Triangulate () Create the Vector3 vertices Vector3 vertices new Vector3 verts.Length for (int i 0 i lt vertices.Length i ) vertices i new Vector3(verts i .x, verts i .y, 0) Create the mesh Mesh msh new Mesh() msh.vertices vertices msh.triangles indices msh.RecalculateNormals() msh.RecalculateBounds() Set up game object with mesh MeshFilter filter GetComponent lt MeshFilter gt () filter.mesh msh GetComponent lt Renderer gt ().material meshMaterial StartCoroutine (FlipNormal ()) IEnumerator FlipNormal() yield return new WaitForSeconds (0.1f) Mesh mesh (GetComponent lt MeshFilter gt () as MeshFilter).mesh mesh.uv mesh.uv.Select(o gt new Vector2(1 o.x, o.y)).ToArray() mesh.triangles mesh.triangles.Reverse().ToArray() Now this seems to be an obvious problem to have but I am just not being able to crack it. I have a feeling the solution is some mathematics that is completely escaping me right now. Can someone please help and point me to the right direction. I need to be able to align the mesh to the outline even when the camera is rotated.
0
Unity2D Child class inheriting onCollisionEnter() methods I may be an idiot for asking this but I can't seem to solve it myself, I have a GenericWeapon class which has a onCollisionEnter() method which I want applying to all child classes which inherit from it, here is the code public void onCollisionEnter(Collider target) Debug.Log("Collided with player!") if(target.GetComponent lt Player gt ()) bc2d.enabled false rb2d.Sleep() equip(target.GetComponent lt Player gt ()) My child class is the following using System.Collections using System.Collections.Generic using UnityEngine public class RangedWeapon GenericWeapon Start is called before the first frame update void Start() Update is called once per frame void Update() public void attack() and my in GameObject has the RangedWeapon class as a component however the GameObject does not seem to be picking up any collisions with the player. Could someone point out where I'm going wrong with this?
0
Is it necessary to know some programming language before learning to use Unity I had learnt a bit of Java programming in school...is there any other programming language that I should learn to be able to work using Unity?
0
Transform check should return null, but returns as initialized instead In my Player script, I initialize my FirePoint transform using GameObject.Find in the Awake function. In the editor, I purposely misspelled the name of FirePoint to test if the null check inside of my Fire function will print an error to the console. The only error that shows up is from the Awake function giving a NullReferenceException, but why don't I see my Debug.LogError? Instead, the else statement prints that the FirePoint is not null. public class Player MonoBehaviour HideInInspector public Transform FirePoint private void Awake() FirePoint GameObject.Find("FirePoint").transform private void Fire() if (FirePoint null) Debug.LogError("FirePoint is null.") else print("FirePoint is NOT null.")
0
How to create pixel perfect noise shader? I would like to know how they created the pixel perfect noise shader in monument valley 2 in that b w level (example picture). I think it starts with a billboard shader, but I have no clue how to scale the texture to it's native size. I'm using ShaderLab (unity, mobile platforms)
0
Tire mesh rotates faster than wheelcollider in Unity I have a car in Unity. Scripts are C . I have noticed that my tire meshes' rotation is faster than whellcollider rotation. I am using this code for wheel rotation flWheel.localEulerAngles new Vector3(flWheel.localEulerAngles.x, flWheelCollider.steerAngle flWheel.localEulerAngles.z, flWheel.localEulerAngles.z) frWheel.localEulerAngles new Vector3(frWheel.localEulerAngles.x, frWheelCollider.steerAngle frWheel.localEulerAngles.z, frWheel.localEulerAngles.z) flWheel.Rotate(flWheelCollider.rpm 60 360 Time.deltaTime, 0, 0) frWheel.Rotate(frWheelCollider.rpm 60 360 Time.deltaTime, 0, 0) rlWheel.Rotate(rlWheelCollider.rpm 60 360 Time.deltaTime, 0, 0) rrWheel.Rotate(rrWheelCollider.rpm 60 360 Time.deltaTime, 0, 0) I found this from here Does anyone know how to fix this? Edit Using AquaGeneral's answer I could able to solve rotation problem. But now front right tire position changed to rear left tire position and rear right tire rotated 180 on Y axis. need help
0
In Unity3D, what is the relation between inertiaTensor and inertiaTensorRotation? In unity3d there are two properties on rigidbody that correspond to the moment of inertia tensor. One of them is rigidbody.inertiaTensor, which I know is the diagonal of the inertia tensor, The other is rigidody.inertiaTensorRotation, which I don't quite understand. I have, though, created a rigidbody in such a way that I get it to be other number than Quatenion.identity, but I still don't see the connection. Can I describe the products of inertia tensor with the rotation or ... what is the relation between them and where would I require them?
0
How to have a point light with no falloff in Unity 3D? Does anyone know of a good strategy to make point lights with no falloff, eg. anything in the radius of the light will be 100 illumination while anything outside the radius will be 0 illumination. I want to use this as a sort of 3D line of sight drawing. The line of sight is a big sphere originating from the character's head that I thought would be a clever idea to have that represented as a point light, however with the falloff it doesn't correctly show where the edge of the line of site is. I've tried a few solutions, such as a custom falloff package (doesn't seem to have the options I want) and a few shaders, but I am terrible at shaders so it's difficult for me to debug. I'll post the shader here in case somebody can tell me if I'm being dumb, otherwise if someone can point me to a different solution that would be great. Thanks! Here's a shader I tried, but it just turns everything invisible and it's not immediately obvious to me why Shader "Custom No Falloff v2" Properties Color("Color", Color) (1,1,1,1) MainTex("Texture", 2D) "white" SubShader Tags "Queue" "Transparent" Pass Blend SrcAlpha OneMinusSrcAlpha Tags "LightMode" "ForwardAdd" CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" include "Lighting.cginc" compile shader into multiple variants, with and without shadows pragma multi compile fwdadd fullshadows shadow helper functions and macros include "AutoLight.cginc" sampler2D MainTex float4 MainTex ST fixed4 Color struct v2f float2 uv TEXCOORD0 SHADOW COORDS(1) put shadows data into TEXCOORD1 float4 pos SV POSITION v2f vert(appdata base v) v2f o o.pos UnityObjectToClipPos(v.vertex) o.uv TRANSFORM TEX(v.texcoord, MainTex) TRANSFER SHADOW(o) return o fixed4 frag(v2f i) SV Target fixed4 col tex2D( MainTex, i.uv) Color compute shadow attenuation (1.0 fully lit, 0.0 fully shadowed) fixed shadow SHADOW ATTENUATION(i) if (shadow lt 0.5) return fixed4(0.0156862745, 0, 0.23529411764,1.0) or any other color for shadow return col ENDCG shadow casting support UsePass "Legacy Shaders VertexLit SHADOWCASTER"
0
Unity3D (5.1) NavMesh Agent Error This is my first post in GameDev StackExchange, so please excuse me if I make any mistakes on best practices here (if I do, please refer me so I can learn). I'm making a prototype where I have 2 types of enemy units Uninfected and Infected. The Uninfected are to seek out Infected via AI pathfinding. However, I came across an issue when implementing the NavMesh in the scene. If the Player collides with an Uninfected, they go flying backwards. If they hit the walls, the walls collectively get hit. Here's some screenshots. Example 1 http s7.photobucket.com user Korudo media GameDev RoboInfect 20Scene 20 20WallWeirdness1 zpsg0k2wbyk.png.html Example 2 http s7.photobucket.com user Korudo media GameDev RoboInfect 20Scene 20 20WallWeirdness1 zpsg0k2wbyk.png.html Thanks in advance.
0
Understanding Screen Position Node in Unity Shader Graph I'm struggling to understand what exactly the Screen Position node outputs in Unity's Shader Graph. I'm using the screen position with scene depth to calculate the distance between two objects. Every tutorial I saw (like Brackey's forcefield one) is using the alpha channel of the Screen Position output I read that the Screen Position node outputs the mesh vertex screen positions. Does it means the 2D position on the screen projection? Or the vertex 3D position from the eye space? And more importantly, what is exactly the apha channel of this output? (I have the feeling this is related to the quot clip space W component quot in the documentation)
0
Unity Interrupting Animations When I interrupt an Animator Controller during an Animation and reopen it the Armature gets stuck (more or less) at the point where the previous Animation was interrupted. How can I safely and instantly quit an animation without destroying it? Please watch the Video to fully comprehend the problem https youtu.be O9X5SBATHRw Screenshot of Problem Screenshot of Animator Controller Part of the Weapon Switch Script disableWeaponModel(weaponNameList activeWeapon ) Disable active Weapon Model if (holsteredWeapon 1) If player carries only 1 weapon holsteredWeapon activeWeapon Active Weapon is holstered else Player already carries 2 weapons actionDropGun() Active Weapon is thrown (New LOD generated) activeWeapon getWeaponIDfromLOD(targetName) Active Weapon is set to Target LOD setWeaponVars(activeWeapon) Set all variables to the active Weapon setWeaponModel(weaponNameList activeWeapon ) Set Weapon Model to the active Weapon setAnimator(weaponNameList activeWeapon ) Set Animations to the active Weapon setAnimator(string name) Function from above (last code line) void setAnimator(string name) Add new guns here if (name "MP5A3") currentWeaponAnimation MP5A3 Animation else if (name "Rpk 74") currentWeaponAnimation Rpk74 Animation else if (name "Skorpion") currentWeaponAnimation Skorpion Animation Variables from setAnimator(string name)
0
How to scale an object in one direction without moving the opposite edge? I am using Unity. In my game, I have an SpriteRenderer and I'd like it to increase its size I'd like it to lengthen to the right, without moving the left edge. I tried changing its scale to something bigger than its original scale and it changes into something like this, growing to both the left and the right I also tried to increase its position together with its scale but then it didn't work. Editor's note this is where you tell us how it "didn't work". What exactly did you try, what results did you get, and how did those results differ from what you wanted? My Object is configured like this in UnityEngine
0
Adding components to a GameObject referenced within code So in my project, I have a class called ComponentRegistry. The idea of this class is to store a dictionary of components and their names. For example public Dictionary lt string, MonoBehaviour gt registry public MonoBehaviour testComponent void Start() registry new Dictionary lt string, MonoBehaviour gt () registry.Add ("TestComponent", testComponent) public MonoBehaviour GetScript(string name) return registry name Then in a separate class, I will access this dictionary using a string in order to retrieve the associated component, subsequently adding the associated component to the gameObject. foreach (string comp in blockInfo.components) For each of the components that need to be added gameObject.AddComponent(ScriptMaster.compReg.GetScript(comp)) I know this is incorrect, but the idea is there Just for understanding, compReg is an instance of the ComponentRegister class stored as a static variable within my ScriptMaster class. But no matter what I try, I have not been able to get this to work. I have switched endlessly between different formatting of adding components to gameObjects, alternating between using Components and MonoBehaviours, adding by type. Thank you for any insight.
0
Unity LoadLevelAdditive and baked light scene settings I am a programmer for a small game. For our levels, I separated the UI from the level data, so one scene is a scene which contains only the UI, the other scene has all the gameobjects and models and ... the light. So when loading a level, I first load the UI scene (LoadLevel), then the actual play scene (LoadLevelAdditive). Now that our graphics guy wants to bake some lights, he is telling me it doesn't work, because whatever his settings in the play scene, Unity ignores them and uses the settings of the UI scene. He also tells me we cannot just ignore the light settings of the UI scene ... So my question is, how do I make Unity ignore the light settings of a certain scene (UI scene in my case) or how can I enable a settings override? Thanks.
0
Delay Pause game while displaying countdown 3,2,1 go I have already a running script of countdown and it works fine , the problem is that I want to pause or delay the game while the countdown is displaying, the moment countdown finished the player is already dead. Here is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class jb MonoBehaviour private string countdown "" private bool showCountdown false public AudioSource noise1 public AudioSource noise2 public Sprite sprite2 public Vector2 jump new Vector2 (0,300) private SpriteRenderer spriteRenderer void Start () GetComponent lt Rigidbody2D gt ().velocity Vector2.right speed StartCoroutine(getReady()) spriteRenderer GetComponent lt SpriteRenderer gt () noise1.GetComponent lt AudioSource gt ().Play() Update is called once per frame void Update () if(Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Began) Vector2 touchPosition Input.GetTouch(0).position GetComponent lt Rigidbody2D gt ().AddForce(jump) noise1.GetComponent lt AudioSource gt ().Play() Vector2 screen position Camera.main.WorldToScreenPoint (transform.position) if(screen position.y gt Screen.height screen position.y lt 0) noise1.GetComponent lt AudioSource gt ().Stop() noise2.GetComponent lt AudioSource gt ().Play() StartCoroutine(Die()) void OnCollisionEnter2D(Collision2D det) noise1.GetComponent lt AudioSource gt ().Stop() noise2.GetComponent lt AudioSource gt ().Play() StartCoroutine(Die()) IEnumerator Die() PlayerPrefs.SetString( "previousLevel", SceneManager.GetActiveScene().name ) spriteRenderer.sprite sprite2 yield return new WaitForSeconds (2) SceneManager.LoadScene("score") IEnumerator getReady() showCountdown true countdown "3" yield return new WaitForSeconds (1) countdown "2" yield return new WaitForSeconds (1) countdown "1" yield return new WaitForSeconds (1) countdown "GO" yield return new WaitForSeconds (1) showCountdown true countdown "" void OnGUI () if (showCountdown) GUI.color Color.red GUI.Box ( new Rect (Screen.width 2 100, 50, 200, 175), "GET READY") display countdown GUI.color Color.white GUI.Box (new Rect (Screen.width 2 90, 75, 180, 140), countdown) what can I do to pause the game? I tried invoke (by creating another function and copying everything over there) in update call but it didn't work.
0
How do I size my map in blender so it will be the right size in unity? I am working on a fps game but I cant get the size right of my map in blender, every time I export it to a .fbx file (unity won't work if it is a .blend file) it is a super small plane floor in unity the player controller is 10 as big as the map. I don't know what to do.
0
Enum or Inheritance for event based interaction? I am currently considering two possibilities to a centralised interaction system within my game. Consider that you want to produce different results for different types of objects within the game world you interact with a signpost and dialogue appears, or interact with an item on the ground and it gets added to your inventory with a notification. Essentially, I cannot decide whether it would be more efficient to implement such functionality all within one centralised place or to spread each function out over separate events. Option 1 Centralised This is what I have started coding. One Interact class which contains several "Types" of possible events in my game. When the player "interacts" with an object implementing this script, it will implement the functionality that it is set to in the Editor. This means I drag and drop this Event Script onto a prefab and can automatically tweak its functionality within a couple of seconds and have it ready to go in the game world. I have simplified the general consensus of my code into this block for readability public string eventName public enum EventType Movement 0, Dialogue 1, NPC 2, ItemCollect 3, Teleport 4, Cutscene 5, Switch 6, Custom 7 public EventType eventType INITIALIZATION private void Awake() SetupEvent(eventType) public void Activate(bool calledFromTrigger false) if (autoTrigger amp amp !calledFromTrigger) return Debug.Log("Activated " name "!") StartEvent(eventType) private void StartEvent(EventType type) switch (type) case EventType.Movement MovePlatform() break case EventType.Dialogue break case EventType.NPC break case EventType.ItemCollect break case EventType.Cutscene break case EventType.Switch break case EventType.Custom break Resulting in Option 2 Inheritance It is as if I have a little devil and angel on my shoulder, one tugging me towards the easy and half finished code of the former example, and another urging me to redesign what I am doing into a much cleaner and abstracted approach. In the previous example, all "event types" (Movement, Dialogue, Item Collection etc.) were handled by enums that were passed through a Switch statement to check which method should be executed based on the parameters inputted into the Unity Editor for that specific Game Object. In this system, there would be a base "Interactible" class, which various classes would inherit from to implement functionality. The Activate() method would be overridden in the children for each specific class. public class NPC Interactible public override void Activate() NPC Code... The unfortunate downside to this is that I can't just use one prefab for all my events and change them based on the custom editor that I define. I would have to create a custom editor for each possible child of the Interactible class, and instead of selecting which type of event I want it to be from a simple drop down, I will have to swap out different scripts for different functionality.
0
How to move player on unity3D? I checked the input settings. I added a speed value. I also added Time.deltaTime, but the body is not moving. using UnityEngine using System.Collections public class PlayerController MonoBehaviour public float speed private Rigidbody rb void Start () rb GetComponent lt Rigidbody gt () void FixedUpdate () float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) rb.AddForce(movement speed)
0
Selecting Dictionary item based on custom classes instead of keys I am attempting to write my own path finding code for a game I'm working on that will implement a form of the A algorithm. I store my nodes of the path finding system as a class called nodes and add these to a dictionary with their position in world space as the key for the dictionary. Here's the problem. At one point I need to test the dictionary and return from it the node with the lowest "f" value. I came across the morelinq MinBy function with seemed promising, but so far have not had any luck getting it to work. Here is a stripped down version of the code using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using MoreLinq public class GMove MonoBehaviour public Dictionary lt Vector3, Node gt vectorNodesOpen new Dictionary lt Vector3,Node gt () public Dictionary lt Vector3, Node gt vectorNodesClosed new Dictionary lt Vector3,Node gt () private KeyValuePair lt Vector3, Node gt currentNode new KeyValuePair lt Vector3,Node gt () private bool goal private bool findingPath void Start() goal false findingPath false public void addNodes() several nodes get added to the dictionary based on the A algorithm ending way point and beginning waypoint are stored as Vector3 public class Node public int h get set public int g get set public int f get set public Vector3 pos get set public Vector3 parentNodeVector get set void Update() if(findingPath) while (!goal) currentNode new KeyValuePair lt Vector3, Node gt (vectorNodesOpen.MinBy(x gt x.Value.f).Key, vectorNodesOpen vectorNodesOpen.MinBy(x gt x.Value.f).Key ) This is the line in which I'm attempting to get the node in the open list with the smallest f value. vectorNodesClosed.Add(vectorNodesOpen.MinBy(x gt x.Value.f).Key, vectorNodesOpen vectorNodesOpen.MinBy(x gt x.Value.f).Key ) vectorNodesOpen.Remove(vectorNodesOpen.MinBy(x gt x.Value.f).Key) remove current from open. if (currentNode.Value.pos waypointEnd) if current node end position we are done. goal true addNodes(currentNode.Value.pos, waypointEnd) Add and update nodes The line that is giving me trouble is the first line inside the while loop. I need a way to return the Dictionary item with the smallest "F" value, this would be pretty easy if it were an integer but the F value resides in the Node class. I don't have to use MoreLinq, I would be happy to do it any other way that someone can come up with. Cheers! One more note the code above is incomplete in an effort to minimize it down to only what is necessary to understand the problem more complete code can be provided if necessary.
0
How can I draw lines in editor between waypoints when creating the waypoints? public List lt Vector3 gt destinations new List lt Vector3 gt () public int numberOfDestionations public float moveSpeed 5f public bool loop false public bool moveBack false public Text textCounter private Coroutine movementCoroutine private bool pause false private bool coroutineRunning false private Vector3 startPosition private int countDestionations private void Start() for (int i 0 i lt numberOfDestionations i ) destinations.Add(new Vector3(UnityEngine.Random.Range( 300, 25), 1f, 0)) 25, 1f, 0) if(i gt 0) Gizmos.DrawLine(destinations i , destinations i 1 ) I'm trying to use gizmos but getting exception ArgumentOutOfRangeException Index was out of range. Must be non negative and less than the size of the collection. Parameter name index On line 33 Gizmos.DrawLine(destinations i , destinations i 1 ) I want that while it's creating the vectors draw lines from the current created vector destination and the next one. A line from index 0 to index 1 to index 2 and so on. So when running the game I will see a net of all the lines connected between the vectors destinations.
0
How to offset a 2D GameObject by a pixel amount? I'm extremely new to game creation. I'm playing around with creating a 2D Unity game. The scene is setup from the default Unity 5 2D template. Following a tutorial, I've created a TerrainManager GameObject and Script. The script instantiates tiles and sets their position using a standard double loop. I've found a 2D isometric tile set. Each tile is visually rendered as rotated around the vertical axis by 45 degrees, creating more of a diamond shape rather than a square. This requires that every second tile be offset by half the tile width on the x axis, and half the tile height on the y axis. As each tile is of a different height, one can not simply offset the tile on the Y axis by half its height. Each terrain "layer" is 16px tall in the PNG. Some PNGs have a single "layer", some have multiple "layers". (For instance, a single layer water tile is 83px in height, while a dual layer "grass on top of dirt" layer is 99px in height. As the game object expects the transform.position as a Vector3 in (I assume) game units, I do not know how to compose this using pixel values. So the question I have is, how do I achieve the 16px y axis offset of the game object? I'm more than happy to provide additional details if needed.
0
Unity2D force of an impact I don't know how to name what I am searching for... Force, Impact? It's easier to explain with an image for me. We have two GameObjects with colliders, A and B. They can move in any direction (top down game with 360 movement possibilities). First case (left) A go to the right at a speed of 2, B to the left at a speed of 1 and they collide. How to calculate that A take 1 damage (from the speed of B in its direction) and B take 2. Second case A go to the right at speed of 2 and B to the right at speed of 1. A take 0 damage and B take 1. I am using Collision2D which doesn't have "impulse" property. I have no idea how to calculate thing like this manually.
0
Adding a delay into the middle of a function in Unity In the spot wait 1.5 seconds what would I say to make it wait 1.5 seconds then complete the code after? Here is the code using System.Collections using System.Collections.Generic using UnityEngine public class OnclickHeal MonoBehaviour public PlayerHealth playerHealth public PlayerMovement playerMovement public Inventory Inventory public Button healButton void Start() Button btn healButton.GetComponent lt Button gt () btn.onClick.AddListener(TaskOnClick) void TaskOnClick() playerMovement.moveSpeed 3 wait 1.5 seconds playerMovement.moveSpeed 4 playerHealth.currentHealth 100 Also, the line public Button healButton throws an error error CS0246 The type or namespace name 'Button' could not be found (are you missing a using directive or an assembly reference?)
0
How to avoid material copying error message in Edit mode? I created a component called "AphaGroup" (an analog of the existing CanvasGroup for UI) which should be able to change alpha of the whole game object tree. My component finds all the MeshRenderer components, takes their material.color and changes its alpha. It should work both in play amp edit modes. When it's run in edit mode there is an error in the console when the material is copied for the first time Instantiating material due to calling renderer.material during edit mode. This will leak materials into the scene. You most likely want to use renderer.sharedMaterial instead. I've read most of the similar questions on the Internet but still haven't found the answer on how to manage this situation properly. How to avoid both this error message and memory leaks? I tried Renderer.material, Renderer.materials and Renderer.GetMaterials, but all they cause the same error.
0
Rotate the player in a certain way that makes it look like he is sliding I'm trying to make my first game in Unity a 3d platformer inspired by the classic Crash Bandicoot games. I've managed to make most of the movement with the character control script below. However, I don't know how I can do a slide crouch. What I want to do is to rotate and move the player down closer to the ground and give him some more speed that decreases over time until he reaches a normal waking state. I thought about making the player rotate on a specific axis but when he turns the axis doesn't change so now I'm kind of lost in what to do. using UnityEngine public class PlayerMovement MonoBehaviour public CharacterController controller public float speed 10f turnning smoothness public float turnSmoothTime 0.1f float turnSmoothVelocity jump controls public float jumpHeight 3f public float gravity 29.43f Vector3 velocity bool isGrounded gravity check public Transform groundCheck public float groundDistance 0.4f public LayerMask groundMask Update is called once per frame void Update() isGrounded Physics.CheckSphere(groundCheck.position, groundDistance, groundMask) if(isGrounded amp amp velocity.y lt 0) velocity.y 1f player movement on both axis float horizontal Input.GetAxisRaw( quot Horizontal quot ) float vertical Input.GetAxisRaw( quot Vertical quot ) Vector3 direction new Vector3(horizontal, 0f, vertical).normalized velocity.y gravity Time.deltaTime controller.Move(velocity Time.deltaTime) if (Input.GetKeyDown( quot space quot ) amp amp isGrounded) velocity.y Mathf.Sqrt(jumpHeight 2f gravity) if (direction.magnitude gt 0.1f) player turning depending on where moving float targetAngle Mathf.Atan2(direction.x, direction.z) Mathf.Rad2Deg float angle Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime) transform.rotation Quaternion.Euler(0f, angle, 0f) controller.Move(direction speed Time.deltaTime)
0
How could I get composite rigid body into unity I am developing a game, in unity, that has accurate destruction physics and from my understanding unity uses plain old rigid body physics. I was wondering if there was a way to bring composite rigid body physics into unity through a plug in or library or some other way? Thanks, nova edit So composite rigid body physics is almost exact like normal rigid body physics. But the main difference is that in composite rigid body physics all of the assets will not be considered physics based objects until an outside force hits them. For example a building and all of that parts it is made out of will not be processed as physics based objects until say a rocket hits it. This method of composite rigid body physics uses much less memory because it is only processing what is being affect and not everything else.
0
How to set the z axis bound of the collider of child of an instantiated object to zero I have attached a script to an empty GameObject to instantiate a prefab and the script is using System.Collections using System.Collections.Generic using System.Collections.Specialized using UnityEngine public class Circles MonoBehaviour SerializeField float Xmax SerializeField float Xmin SerializeField float Ymax SerializeField float Ymin SerializeField float outsideMaxsize SerializeField float outsideMinsize float insideMaxsize float insideMinsize public GameObject enemy GameObject enemyObject int enemyNo float Xpos float Ypos float outsideSize float insideSize Start is called before the first frame update void Start() enemyNo Random.Range(0, 4) instantiator() Update is called once per frame void Update() public void instantiator() Xpos Random.Range(Xmin, Xmax) Ypos Random.Range(Ymin, Ymax) outsideSize Random.Range(outsideMinsize, outsideMaxsize) Vector2 circlePos new Vector2(Xpos, Ypos) transform.position circlePos enemyObject GameObject.Instantiate(enemy enemyNo , transform.position, transform.rotation,transform.parent) as GameObject var enemies enemyObject.transform var outsideComponent enemies.GetChild(0) var insideComponent enemies.GetChild(1) outsideComponent.transform.localScale new Vector2(outsideSize, outsideSize) insideMaxsize outsideSize 0.5f insideMinsize 0.15f insideSize Random.Range(insideMinsize, insideMaxsize) insideComponent.transform.localScale new Vector2(insideSize, insideSize) enemyNo Random.Range(0, 4) And I have attached a script to the prefab which is being instantiated and that script is using System using System.Collections using System.Collections.Generic using UnityEngine public class destroyer MonoBehaviour Circles circles CircleCollider2D collider1 Collider2D collider2 private void Start() circles FindObjectOfType lt Circles gt () print( quot 1 max quot collider1.bounds.max) print( quot 1 min quot collider1.bounds.min) print( quot 2 max quot collider2.bounds.max) print( quot 2 min quot collider2.bounds.min) private void OnEnable() collider1 gameObject.transform.GetChild(0).GetComponent lt CircleCollider2D gt () collider2 gameObject.transform.GetChild(1).GetComponent lt Collider2D gt () void OnTriggerStay2D(Collider2D other) print( quot star max quot other.bounds.max) print( quot star min quot other.bounds.min) if (collider1.bounds.Contains(other.bounds.max) amp amp collider1.bounds.Contains(other.bounds.min)) if (other.bounds.Contains(collider2.bounds.max) amp amp other.bounds.Contains(collider2.bounds.min)) Destroy(other.gameObject) Destroy(gameObject) circles.instantiator() the problem is that the z axis bounds of the colliders are coming out to be 15.8 when the prefab is instantiated and when I drag the prefab to scene then the z axis bounds of the collider is 0. I want the z axis bounds of the colliders to be 0 when the prefab is instantiated
0
How can I check if a point(Vector3) is in Matrix4x4 I'm placing random objects in an imaginary cube in front of my target. I am using following code to do this var center Vector3.zero center.z (m size.z 2) m offset.z center.x m offset.x center.y m offset.y var mat Matrix4x4.TRS(m target.position, m target.rotation, m target.lossyScale) Vector3 pos center new Vector3(Random.Range( m size.x 2, m size.x 2), Random.Range( m size.y 2, m size.y 2), Random.Range( m size.z 2, m size.z 2)) pos mat.MultiplyPoint(pos) m instantiatedObject.Add(Instantiate(m object, pos, Quaternion.identity)) And it's working as expected. but now my problem is as my target moves, the previously placed objects may not be in this imaginary cube anymore. how can I check if my placed objects are in this imaginary cube and if they are not I can remove them?
0
Calculate position on Isometric grid I created the following tile grid in unity3d The blue dot is the absolute center point (0,0) of both scene space and tile map. Now I am trying to calculate the X Y position of points on the tile map ( the black coordinates). The red coordinates are positions in the scene space. Every calculation I make just gives me a wrong result. Is the tile map roatated the wrong way? Any help really apreciated!
0
How can I scroll animate up lines reading from a string to ui text? This is the reading lines code if (primaryTarget ! null) var lines primaryTarget.description.Split(' n') text.text quot Item found quot primaryTarget.description else text.text quot quot And this is the script of the description The script is attached to each interactable target(item) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class InteractableItem MonoBehaviour public enum InteractableMode your custom enumeration Description, Action public InteractableMode interactableMode InteractableMode.Description public float distance private bool action true TextArea(1, 10) public string description quot quot public void ActionOnItem() if(interactableMode InteractableMode.Action amp amp distance lt 5f amp amp action true) action false Depending on the amount of text in the string I want to show it in the ui Text. If there is one line then just show the text or even if there are two lines. but if there is a lot of text then split the lines and scroll the lines smooth up so the first line will be disappear or pushed up and bottom lines will come up. In the screenshot you can see on the left the text that show in the ui text on the right the text of the description. The ui text can't show all the text and I don't want the text to overlap other ui's or objects so the idea is to make the text slowly smooth scrolling up.
0
Rotating a gameobject in the Inspector doesn't change direction When I add a Cube to a scene, the blue axis ( forward) of the cube points into a certain direction. When I now change the Y rotation of the cube to 90 in the inspector, the blue arrow doesn't rotate. I would have expected it to rotate with the rotation that I have defined for the cube. What is happening here? To explain more in detail why this is bothering confusing me I want to rebuild the RE4 inventory (which is actual 3D). The items in this inventory can be moved within the "grid" To do that I have created a suitcase and then I added a gun to it As one can see, I have assigned the facing direction properly The blue axis ( forward) points into the direction of the gun. Now I wanted to rotate the gun in such a way that it is shown like in the original RE4 inventory. To do that, I apply a rotation of Y 90. The gun looks correctly now However, the blue axis now faces the wrong direction in my opinion. Why does it not rotate along with the rotation of the gameobject? This really confuses me because now when I want to move the gun left or right, I have to change its X position value instead of changing the Z position value. This just seems wrong to me. Can somebody tell me what I'm missing here? Thank you.
0
Want some limits in Bullet firing and its stop when i press the shoot button I want some limits or range when my player fire the bullets and when i press the shoot button my fire as been stopped. I use the GetButtonDown from this its fire continuously but its not stopped. and if i use Input.GetButton than its hold the button and fire continuously but in fire there is no gap. So, my problem is that how i stop the bullet fire when i press the shoot button and if choose this (INPUT.GETBUTTON) and its hold the shoot button and its fire continuously than i want some gap on that fire and some limits or range of fire. void Update() if(Input.GetButtonDown("Fire1")) shootRoutine StartCoroutine(PlayerShoot()) else if(Input.GetButtonUp("JumpButton")) StopCoroutine(shootRoutine) shootRoutine null void JumpButton() if(!transform.GetChild(0).gameObject.GetComponent lt PlayerHealth gt ().hasDied) if (grounded) grounded false myRigidBody.AddForce (new Vector2 (0, jumpPower), ForceMode2D.Impulse) if(myRigidBody.velocity.y gt jumpPower) myRigidBody.velocity new Vector2 (0, jumpPower) animator.SetBool ("isGrounded", grounded) PlayerShoot method IEnumerator PlayerShoot() while(true) if (!transform.GetChild (0).gameObject.GetComponent lt PlayerHealth gt ().hasDied) if (energy gt 5f) energy 5f energyLevel.value (int) energy energyText.text (int)energy " " GameObject newProjectile Instantiate(projectile, new Vector3(transform.position.x 1.5f, transform.position.y 0.02f, transform.position.z), Quaternion.identity) as GameObject if (GameController.instance.isMusicOn) AudioSource.PlayClipAtPoint(MusicController.instance.audioClips 2 , newProjectile.transform.position) yield return new WaitForSeconds(shootDelay) Wait for 'shootDelay' seconds before starting over again.
0
Should LOD models be used in mobile games? LOD models are widely used in PC and console games, to optimize performance by reducing the vertex count and texture size for distant objects. However, I'm having a harder time finding out if they are typically used to increase performance in mobile games. I've seen a few people in forums suggest that the CPU overhead for LOD models might actually outweigh the GPU gains on mobile devices. Another consideration is the more limited storage space on mobile, and LOD models textures necessarily increase the total size of a game. Other than that, I can't find much information on the subject. The Unity documentation on LOD models doesn't mention mobile, and the Unity documentation on optimizing for mobile doesn't mention LOD models. I know the first answer to any performance question is usually "profile it and find out for yourself" however, in this case, I am helping to optimize a game that doesn't currently have LOD models, so profiling it would first require commissioning the artists to create enough LOD models that we can realistically profile the performance change. Does the usage of LOD models typically provide noteworthy performance gains in 3D mobile games, or does the overhead for LOD cancel out any gains? The specific title in question is a racing game.
0
Given a 3d goal point and a turn rate in radius, find max speed to reach goal I'm working on a 3d space sim with AI agents flying ships through space. I am trying to get them to follow a waypoint path nicely, which involves figuring out how fast they can be travelling and still manage to pass through the waypoint. Given a point in 3d space and an an agent that only travels forwards and has a given turning rate in radians second and an acceleration rate, how can I find the maximum speed the ai can travel and still manage to face the point before overshooting it? Can any math wizards lend a hand? public class AIPilot relevant fields from my class float turnRate radians float acceleration Transform transform public float FindMaxSpeedToFace(Vector3 goal) trying to fill the body of this method
0
Unity game in edit the scene mode all of a sudden became incredibly slow "laggy" So I recently have been working on a game. So far I have very few assets in the game, which are a point light, a piece of terrain (which is textured), a player controller and a tree. Everything was going well until I put the tree in the scene. I made tree and started to add some branches I got to about 8 branches, and then I added 35 leafs. Then the edit scene started to become laggy. When I played the game it was running perfectly. But as soon as I changed the scene back to edit mode it became laggy again. I then deleted the tree to see if that would solve the problem but it seems to have done nothing at all. I would really appreciate if someone could explain why the edit scene is becoming laggy even though there are only a few assets within the game. Thanks, Nova
0
MeshMemory causing constant spikes I have a ready to launch application, cleaning everything right now. I have these strange spikes on Mesh Memory. The best part of it is that this view below is from a static menu screen, where there are no meshes. I don't even interact with it. Can this be caused by meshes import options or something like that?
0
Smooth rotation for a bone? I'm trying to make my character bone "chest" rotate smoothly when face enemy and get back to his stand. Can anyone help me with this ? public Transform Target public Vector3 Offset Animator anim Transform chest public float rotation speed public bool aim at traget false void Start() anim GetComponent lt Animator gt () chest anim.GetBoneTransform(HumanBodyBones.Chest) void LateUpdate() if (aim at traget true) smooth rotation to face target chest.LookAt(Target.transform.position) chest.rotation chest.rotation Quaternion.Euler(Offset) else get back to you stand smoothly
0
Offsetting ground texture doesn't work in WebGL so I've created a 2D sidescroller game, the technique I used is to keep the player on the same place, and move the obstacles towards him. I also offset the ground and backdrop constantly to create the illusion of player moving. The ground texture is on a quad, and the texture wrap mode is set to repeat. In the editor everything is running fine as I wanted, however when I build it (WebGL), in the browser the ground doesn't seem as if it is set to Repeat but rather Clamp. Here's how it looks You can see from the left part of the image the ground doesn't repeat, the strange thing is that, after the game runs for a few more seconds it fixes, and then in a few seconds becomes like that again. heres the code attached to the ground to keep it offsetting constantly using System.Collections using System.Collections.Generic using UnityEngine public class Offset MonoBehaviour public float scrollSpeed public Material mat private float offset Use this for initialization void Start () mat GetComponent lt Renderer gt ().material Update is called once per frame void Update () offset Mathf.Repeat(Time.time scrollSpeed, 1) mat.mainTextureOffset new Vector2(offset, mat.mainTextureOffset.y) What may I be doing wrong, and how can I fix it? Thanks in advance!
0
How to create a two way teleport system? I'm trying to create a two way teleport system in which players can move into a teleport gameobject, and is then teleported to another linked teleport gameobject. How I was planning to have it work was very simple. On the teleport gameobject's script, it would have a public property to the other teleport's transform in which to teleport the player to. In OnTriggerEnter, I simply set the entering's collider position to that of the linked teleport. void OnTriggerEnter(Collider other) other.transform.position DestinationPoint.position However, when the player's position is changed, it triggers the OnTriggerEnter of the destination teleport, and thus the player gets stuck bouncing back and forth between the two points. What's a good way to prevent this? Some less than ideal solutions I came up with is to offset the position that player teleports too slightly so that he doesn't cause OnTriggerEnter to be called at the destination portal, but I'd like to avoid that.
0
How to get neigbor pixel coordinates in Unity HLSL shader I am writing Mandelbrot set shader for Unity. I wrote an Image Effect shader and it works. Unfortunately, each point quot shimmers quot on translate scale. This is because, for each shader call I compute value for only one mathematical point, which is infinitesimal. On even small translation, the value can change drastically. So, I would like to compute math value not for one point, but for several. But for this I need to know, which aother points belong to my pixel, and for this I need to know the distance to neighbor pixel. Unfortunately, my incoming values are float and I don't know, how to step to next pixel. How to accomplish?
0
Changing the RotateAround center point dynamically Black circles are static Red player Blue line path I'm trying to achieve a constant movement of the red dot like on the image below. For now, I have something like void Update() target firstCircle here I need to perform some calculations this.transform.RotateAround(target.transform.position, Vector3.forward, speed Time.deltaTime) As you can see in the code, it rotates around the upper circle now. I need to switch the target variable to the secondCircle when the player comes back to it's initial position (or is near it). I came up with something like if(Mathf.Abs(Mathf.DeltaAngle(360f,this.transform.rotation.eulerAngles.z)) lt 5f) change target and it works but has two issues. First the epsilon value. If I set it to 5f the above if is true like 7 times (depending on the player's speed). Of course I could make a lock to run it only once per cycle, but there's a second problem. If the object is moving too fast, the if will be false each time, cause the speed step is always higher than the epsilon. How is this done in 'gravity' games like AngryBirds when the bullet changes it's attraction point?
0
How to instantiate a sprite from a sprite sheet using script in unity? We are creating a 2D top down rpg, and we have multiple textures, and we need to be able to change which sprite sheet its reading from in order to change the look of the walls and floor in each room. It has the same basic tiles just they need to look different. Like the corner of a cabin, to the corner of an office building. At the moment we are taking the sprite sheet, splitting it up, and making prefabs out of it for placement by script in the game. Is there a way to do this automatically because we have a lot of textures, and its too many to make into prefabs.
0
Can I use a SkinnedMeshRenderer animation in a Canvas? I just downloaded an asset from the store https www.assetstore.unity3d.com en ! content 67122 They're just animated characters. If you drag amp drop the prefabs on the scene, it works fine. The thing is, I work exclusively with Unity's new 2D Canvas Image Button etc. These prefabs instead use a SkinnedMeshRenderer so it's not like you can put them inside your Canvas. I want to have the prefabs work in my Canvas. For all intents and purposes I want those animations to act like a Image inside the Canvas. This is what one of those prefabs looks like I want to take advantage of the Unity's canvas because it makes a lot of things easier like scaling for all devices, scroll views, easy masks, etc.
0
How would I edit .anim files in Blender? I absolutely cannot stand animating in Unity. I am making an FPS game with many weapons, and each weapon has four animations running, jumping, aiming, and shooting. I would like to create a .anim file in Unity with the keyframes of the character and the weapon, and then edit that .anim file in Blender. How would I edit .anim files in Blender?
0
Using Unity built in sprites programatically I'm trying to figure out how to use the "Panel" built in resource in a game I'm making. I've been able to figure out some potential solutions, but I can't quite figure out how to put all of the pieces together. panelImage.sprite UnityEditor.AssetDatabase.GetBuiltinExtraResource lt Sprite gt ("UI Skin InputFieldBackground.psd") panelImage.sprite Resources.GetBuiltinResource(typeof(Sprite), "Resources unity builtin extra Background.psd") as Sprite The first produces the button sprite, which is almost what I want, but not quite. The second doesn't work at all. I'm missing some small piece of what it takes to make this work, but I can't quite figure it out. How can I use the panel background programmatically?
0
Why does AudioSource not initializes itself? Why does AudioSource not initializes itself? Here is my code using System using System.Collections using System.Collections.Generic using UnityEngine public class CameraConfig MonoBehaviour public GameObject objToFollow public bool followRabbit Use this for initialization void Start() followRabbit true LevelController.current.cameraWhichLooksForRabbit this setMusicSource() setSoundSources() public AudioClip music, rabbitWalksSound, rabbitDiesSound, rabbitFallsSound, enemyAttacksSound private AudioSource musicSrc, rabbitWalksSrc, rabbitDiesSrc, rabbitFallsSrc, enemyAttacksSrc private void setMusicSource() setClipForSrc(musicSrc, music, true) private void setSoundSources() setClipForSrc(rabbitWalksSrc, rabbitWalksSound, false) setClipForSrc(rabbitDiesSrc, rabbitDiesSound, false) setClipForSrc(rabbitFallsSrc, rabbitFallsSound, false) setClipForSrc(enemyAttacksSrc, enemyAttacksSound, false) private void setClipForSrc(AudioSource src, AudioClip clip, bool loop) src gameObject.AddComponent lt AudioSource gt () src.clip clip src.loop loop void Update() checkMusicAndStopOrStartIfNecessary() if (!followRabbit) return Transform rabit transform objToFollow.transform Transform camera transform this.transform Vector3 rabit position rabit transform.position Vector3 camera position camera transform.position camera position.x rabit position.x camera position.y rabit position.y camera transform.position camera position public void playSoundRabbitWalks() if (!rabbitWalksSrc.isPlaying) rabbitWalksSrc.Play() public void playSoundRabbitDies() rabbitDiesSrc.Play() public void playSoundRabbitFalls() rabbitFallsSrc.Play() public void playSoundEnemyAttacks() enemyAttacksSrc.Play() public void stopSoundRabbitWalks() if (rabbitWalksSrc.isPlaying) rabbitWalksSrc.Stop() public void stopSoundRabbitDies() rabbitDiesSrc.Stop() public void stopSoundRabbitFalls() rabbitFallsSrc.Stop() public void stopSoundEnemyAttacks() enemyAttacksSrc.Stop() private void checkMusicAndStopOrStartIfNecessary() if (SoundManager.Instance.isMusicOn() amp amp !musicSrc.isPlaying) musicSrc.Play() else if(!SoundManager.Instance.isMusicOn() amp amp musicSrc.isPlaying) musicSrc.Stop() Here are screenshot of the exceptions in console and inspector view
0
Screenshot preview freezes a game for a few seconds I have a screenshot preview at the end of the level, but when I show it my game freezes for a bit(low fps for a few seconds). This is code I use to load screenshot and crop it(for a little preview sample). Please, help me to solve this lag issue private IEnumerator ShowScreeshotPreview() yield return 0 screenshotTexture new Texture2D(2, 2) byte fileData File.ReadAllBytes(destination) yield return 0 screenshotTexture.LoadImage(fileData) yield return 0 Rect croppedSpriteRect new Rect() croppedSpriteRect.height screenshotTexture.height croppedSpriteRect.width screenshotTexture.height croppedSpriteRect.y 0 croppedSpriteRect.x 0 croppedTexture new Texture2D((int)croppedSpriteRect.width, (int)croppedSpriteRect.height) yield return 0 croppedTexture.SetPixels(screenshotTexture.GetPixels((int)croppedSpriteRect.x, (int)croppedSpriteRect.y, (int)croppedSpriteRect.width, (int)croppedSpriteRect.height)) yield return 0 croppedTexture.Apply() Memory leak occurs here yield return 0 screenshotPrview.mainTexture croppedTexture yield return 0 ScreenshotPreviewAnimator.SetBool("visible", true) screenshotLoaded true
0
Variable value in inspector is not updating automatically? Something weird is happening when I change a variable value in script and hit play the var value doesn't update I have to reset the script in inspector. Is this normal? Aren't the values suppose to update when we hit play? The Simple Code I used to test this var a int 0 function Start () print(a)
0
Why isn't occlusion culling working correctly? Occlusion culling doesn't seem to be behaving the way I was expecting. I've set the yellow wall as static and have baked an occlusion map using the occlusion window in unity. However when visualising the occlusion the red cylinder behind the wall is still visible despite not being seen in the camera preview. Any clue what I'm doing wrong?
0
How to detect whether a transform has rotated left or right I have a game object in my scene, and I want to know how can I calculate whether this game object rotating to the right or to the left. For example if(check whether the transform rotated to the right) print("rotate to right") else if(check whether the transform rotated to the left) print("rotate to left") else print("no rotation")
0
Why the break point is not working with the unity3d editor? The visual studio version is 16.8.3 Visual studio community 2019 The editor version is 2019.4.15f1 personal On other project I have opened it's working fine. It also worked fine on this project but then something went wrong now not sure why the break point s are not working with this project ! In the editor I did double click on a script attached to gameobject and it opened the visual studio then I clicked on the left side to add a break point and did Attach to Unity but the break point on the left is broken with yellow warning. I tried to close and re open both visual studio and the editor. In the editor I did Edit gt Preferences gt External Tools and this is the settings I also clicked on the Regenerate project files. But nothing worked so far.
0
Why won't Unity drop objects to the origin position? It seems that my objects drop to the middle of the scene, not a global position of (0, 0, 0). Why is Unity behaving like this?
0
Problem when trying to use rb.MoveRotation in Unity OK so I learned that rb.MoveRotation is different from rb.transform.Rotate(). But I am having trouble using it and hoping you can help me. I usually use transform.translate(Vector3.forward) (after using transform.Rotate(x,y,z)) , so that I know that will always make object move in the direction its facing. But this isnt working when I use rb.MovePosition. The object rotates when i remove the MovePosition line, but then for some reason doesn't when its there. I've tried multiple things as you'll see in the code. I cant understand also why, if I use the bottom commented attempt in my code, and then press D in game, it will go in the direction its facing and then get stuck. I've commented in my code to try to explain whats happening. What is the correct way to move the position of the player now I am using MoveRotation? I want to base my movement of the direction that the object is facing and not in world coordinates. Thanks void HandleKeys() if (Input.GetKey(KeyCode.A)) if (!facingLeft) rb.MoveRotation(Quaternion.Euler(0, 90,0)) facingLeft true rb.transform.Translate(Vector3.forward speed Time.deltaTime) if I remove this line, the character does turn and face left . But when its in he doesn't and both keys make him move right (and face right) also tried rb.MovePosition(transform.position Vector3.forward speed Time.deltaTime) this results in it going Vector3.forward in world coords rb.MovePosition(transform.position rb.transform.forward speed Time.deltaTime) this makes him go RIGHT gt ?? and the objects facing RIGHT why???? if (Input.GetKey(KeyCode.D)) if (facingLeft) rb.MoveRotation(Quaternion.Euler(0f, 90f, 0f)) facingLeft false rb.transform.Translate(Vector3.forward speed Time.deltaTime) if i leave this in, and the one marked above, then it works but only once, so if I press A then, D he heads right but wont turn round, if I press D first he just goes right if (Input.GetKeyDown(KeyCode.Space) amp amp IsGrounded()) rb.AddForce(Vector3.up jumpForce, ForceMode.Impulse)
0
Can we create same name class for different objects in unity? I have four similar objects in my game. As they are all similar therefore I have created a single script that defines mash for all of them. The script that defines mash for these objects uses a variable called radius which I have imported from other file (by classname.radius). The radius updates on every frame and it is the only property that is different for all objects. To allow different radius for different objects, What I thought would work was, making four different classes of same name classname. Creating variable radius in all of them and giving them different values. Dragging first file to the first object, second file to second object and so on.. When executed, every time the script that generated mash considers classname.radius from the file which is dragged to that object. But that isn't working. What is wrong and how can I implement it? Seems I'm messing with OOPS concepts!
0
(Unity) Shortest way to instantiate an object and obtain it script Normally I use ScriptName script ((GameObject)Instantiate( Resources.Load("Prefab"), new Vector3(x, y, z), Quaternion.identity )).GetComponent lt ScriptName gt () It is a little too long and too much of brackets, so I wondering if there is any other way to get instantiated object's script without break it in two statements.
0
How to find the participation id corresponding to a sender id I am creating a real time multiplayer game in unity 3d using Google Play Game Services. In my function where I deal with the positioning of players based on information that is sent from other players, I get a sender id. The sender id is a long string of characters that does not match any participation ids. My participation ids are just strings such as "Player 1234." I keep the participation ids in an array so I can reference them and compare them to the sender of the information that I am receiving so I know which player it is from. If the sender id and participation id are two different things, how do I make the connection between the two? Here is a link to the tutorial I have been following for Google play services in unity https www.raywenderlich.com 87042 creating cross platform multi player game unity part 2
0
Question about references I have an enemy game object and an item game object. Enemies have an ItemDrops script attached. Items have a DisplayItemLabel script attached. Attached to each enemy public class ItemDrops MonoBehaviour public Transform itemPrefab private EnemyHealth enemyHealth private float originToGroundDistance private Vector3 offset private bool itemDropped private bool numberGenerated private float randomNumber private ItemData itemData public string nameOfDroppedItem void Start() enemyHealth GetComponent lt EnemyHealth gt () itemData GameObject.Find("Item Manager").GetComponent lt ItemData gt () void Update() Initialized in Update instead of Start because enemy floats to 1.083333 on the Y axis after some time after Start originToGroundDistance transform.position.y 0.25f offset new Vector3(0f, originToGroundDistance, 0f) if (enemyHealth.isDead amp amp !itemDropped) if (!numberGenerated) RandomNumberGenerator() Debug.Log(randomNumber) if (randomNumber lt 1) SpawnItem(itemData.coin) private void RandomNumberGenerator() numberGenerated true randomNumber Random.value private void SpawnItem(Item item) itemDropped true nameOfDroppedItem item.itemName Instantiate(itemPrefab, transform.position offset, Quaternion.identity) Attached to each item public class DisplayItemLabel MonoBehaviour private GameObject itemLabel private Text itemNameText void Start() itemLabel transform.Find("Canvas Item Label").gameObject itemNameText itemLabel.GetComponentInChildren lt Text gt () itemNameText.text "Item Name" itemLabel.SetActive(false) void Update() ClampLabelToItem() private void ClampLabelToItem() Vector3 offset new Vector3(0f, 16f, 0f) Vector3 desiredPosition Camera.main.WorldToScreenPoint(transform.position) offset itemLabel.transform.position desiredPosition itemLabel.SetActive(true) Item is not a child of enemy for multiple reasons I can think of. One is that enemies are destroyed when they are killed. With that said, how do I get the item to know who dropped it or get the enemy to know which item it dropped? MY GOAL is to get itemNameText.text "Item Name" to say something like itemNameText.text itemDrops.NameOfDroppedItem but I can't use GameObject.FindGameObjectWithTag("Enemy").GetComponent lt ItemDrops gt () because it won't always grab the correct enemy and thus the correct ItemDrops script. I also can't set DisplayItemLabel.itemNameText.text nameOfDroppedItem in the SpawnItem function because it wouldn't know which item's DisplayItemLabel script to get. So clearly, I'm having issues with references. What should I do?
0
Unity2D Rendering multiple sprites as a single one I'm creating NPCs in Unity 2D using C , and I have 16x16 sprites for body, helmet, clothes and weapon. All these have a tile set which has been split in unity. I'd like to be able to render one of each part together, so I can drag the sprite to the field, and then it will be rendered on the NPC. IE, I drag a helmet sprite into the helmet field and that is the rendered helmet. I intend on having multiple NPCs, so I'd prefer to minimise the child objects. Multiple sprites will need rendering, however there's only one sprite renderer. Is it possible for me to combine the sprites (in code), and then render the final sprite? Or is there perhaps a better way? Thanks in advance!
0
How can I find and get all enabled cameras and switch between them? I have 5 cameras in the scene. In the Inspector I added to the cameras array 3 cameras. In the script I store this cameras using storedCameras array. In cameras array there are 5 cameras. I added a flag allCameras to change between the stored cameras mode and all cameras mode. And I'm using the G key to switch between the cameras either the stored or the all cameras. But when I press on G I see in the Inspector that each press on G remove one camera from the array cameras in the end I left with one camera. And the idea is to press G and switch between the cameras either if it's on stored cameras mode or all cameras mode depending on the flag. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class SwitchCameras MonoBehaviour Header("Cameras Init") public Camera cameras public Vector3 originalPosition HideInInspector public Vector3 currentCameraOriginalPosition, currentCameraPosition public bool allCameras false private Camera storedCameras Space(5) Header("Cameras Switch") public string currentCameraName public Vector3 lastCameraPosition private int currentCamera 0 void Start() storedCameras cameras if (allCameras true) cameras new Camera Camera.allCameras.Length cameras Camera.allCameras lastCameraPosition new Vector3 cameras.Length if (cameras.Length gt 1) originalPosition new Vector3 cameras.Length for (int i 0 i lt cameras.Length i ) originalPosition i cameras i .transform.position if (cameras.Length 1) Debug.LogError("Need more then 1 camera for switching..") else Debug.Log("Found " cameras.Length " cameras") for (int i 0 i lt cameras.Length i ) cameras i .enabled false cameras 0 .enabled true currentCameraName cameras 0 .name currentCameraOriginalPosition originalPosition 0 void LateUpdate() if (allCameras true) cameras new Camera Camera.allCameras.Length cameras Camera.allCameras else cameras new Camera storedCameras.Length cameras storedCameras if (Input.GetKeyDown(KeyCode.G)) cameras currentCamera .enabled false if ( currentCamera cameras.Length) currentCamera 0 cameras currentCamera .enabled true currentCameraName cameras currentCamera .name currentCameraOriginalPosition originalPosition currentCamera lastCameraPosition currentCamera cameras currentCamera .transform.position currentCameraPosition lastCameraPosition currentCamera
0
The jumping height changes randomly, and it is not due to the fact that I press the space bar longer. It is just random Sometimes, the jump height will be so high, and sometimes it jumps normally. How do I solve this? Code using UnityEngine public class PlayerController MonoBehaviour SerializeField private LayerMask platformsLayerMask public Rigidbody2D rb public float MovementSpeed 100f public float JumpingHeight 100f public BoxCollider2D bc public float fallMultiplier 2.5f public float lowJumpMultiplier 2f public Animator anim void Awake() rb transform.GetComponent lt Rigidbody2D gt () bc transform.GetComponent lt BoxCollider2D gt () void Update() if (IsGrounded() amp amp Input.GetKeyDown(KeyCode.Space)) rb.velocity new Vector2(rb.velocity.x, JumpingHeight Time.deltaTime) Debug.Log("Jumping") HandleMovement() private bool IsGrounded() RaycastHit2D raycastHit2d Physics2D.BoxCast(bc.bounds.center, bc.bounds.size, 0f, Vector2.down, 1f, platformsLayerMask) Debug.Log(raycastHit2d.collider) return raycastHit2d.collider ! null void HandleMovement() if (Input.GetKey(KeyCode.A)) rb.velocity new Vector2( MovementSpeed Time.deltaTime, rb.velocity.y) Debug.Log("Going Left") transform.localScale new Vector2( 1, 1) else if (Input.GetKey(KeyCode.D)) rb.velocity new Vector2( MovementSpeed Time.deltaTime, rb.velocity.y) Debug.Log("Going Right") transform.localScale new Vector2(1, 1) else no keys pressed rb.velocity new Vector2(0, rb.velocity.y) Debug.Log("No key pressed") if (rb.velocity.y lt 0) reponsive jumping and falling rb.velocity Vector2.up Physics2D.gravity.y (fallMultiplier 1) Time.deltaTime else if (rb.velocity.y gt 0 amp amp Input.GetKeyDown(KeyCode.Space)) rb.velocity Vector2.up Physics2D.gravity.y (lowJumpMultiplier 1) Time.deltaTime
0
Why does physics not behave consistently in Unity? I'm making a game in which AI players throw a ball. In the screenshot, you can see the arena which is separated by a net in the middle. Each side of the arena has 6 players belonging to one of 2 teams. Right now, one of the players on the right side has the ball (the top right player). He is going to throw the ball to the left side. According to my code, the ball should always land on the same place, because the player always applies the same force to the ball. However, I have noticed that the ball doesn't always land in the same place. I have marked where I've seen the ball land with several red circles. Interestingly, on my main PC, the ball almost always lands on the right most circle. It rarely lands on the other circles, although that does happen. On 3 other PCs I've tested this game on, however, the ball most often lands on the legs of the top left player, sometimes on his head or behind him, but never on the right most circle (in front of him). My game relies heavily on physics. The AI is supposed to calculate how to throw the ball to get it to land on a very specific location, as well as guess where it'll land depending on the ball's position and movements. If the physics don't behave consistently on all machines all the time, how is the AI supposed to calculate all of this accurately? Here is the code in charge of throwing private IEnumerator Serve() var ball GameObject.Find("Ball").GetComponent lt BallController gt () if (ball.ServingPlayer ! this) yield break yield return new WaitForSeconds(3) Vector3 shootDirection transform.forward.normalized var q Quaternion.AngleAxis( 45, transform.right) ball.RigidBody.AddForce(q shootDirection 20f, ForceMode.VelocityChange) As you can see, the ball is always thrown "forward" (facing the net) at a 45 upward angle, using a normalized vector and a constant speed (20f). Before each throw, the position of the players is reset to the exact same location (and rotation) they are seen on the screenshot. player.transform.localEulerAngles new Vector3(0, playerRotation, 0) player.transform.position startingposition posOffset In this case, playerRotation is either 90f or 90f depending on which side the player is on, startingposition is their "horizontal" position (relative to the net), and posOffset is their "vertical" position. The ball has its velocity and angular velocity reset, but not its rotation (since it's a sphere, its rotation shouldn't influence anything). Its position is also set to a fixed location relative to whichever player has to serve the ball. rb.velocity Vector3.zero rb.angularVelocity Vector3.zero transform.position ServingPlayer.ServingPosition Here, rb is the ball's RigidBody. Finally, I am not influencing the ball's movement in any way. I simply apply a force to it when serving, which happens only once. 3 seconds after the ball lands, the match is reset and everything repeats. The flow is basically like this (pseudocode) Start() ResetCourt() StartCoroutine(Players 0 .Serve()) event BallLanded() wait for 3 seconds repeat starting with ResetCourt() I really need the ball's trajectory to be reproducible every single time on every possible machine. Obviously I'm doing something wrong here, but what?
0
How can I loop over waypoints to move all the objects between them? using System.Collections using System.Collections.Generic using UnityEngine public class Waypoints MonoBehaviour public enum RotationMode Normal, Curved public GameObject objectToDuplicate public Transform waypoints public float movingSpeed public bool randomSpeed false private GameObject prefabsToMove private void Start() prefabsToMove GameObject.FindGameObjectsWithTag("FrameLine") DuplicatePrefabEffects(prefabsToMove.Length) private void DuplicatePrefabEffects(int duplicationNumber) for (int i 0 i lt duplicationNumber i ) var go Instantiate(objectToDuplicate) go.tag "Duplicated Prefab" go.name "Duplicated Prefab" private void WaypointsAI() for (int i 0 i lt waypoints.Length i ) if (randomSpeed) movingSpeed Random.Range(1, 20) prefabsToMove i .transform.position Vector3.MoveTowards( prefabsToMove i .transform.position, waypoints i .position, movingSpeed Time.deltaTime ) void Update() WaypointsAI() The problem is inside the loop there might be less or more prefabsToMove then waypoints so it will throw exception. Then doing prefabsToMove i is wrong.
0
Why doesn't this movement script work, while the other one does? Im trying to get a rigidbody2D to move around and got it working with this script public class RubyController MonoBehaviour public Rigidbody2D rigidbody2d public float speed 5.0f Vector2 movement void Start() rigidbody2d GetComponent lt Rigidbody2D gt () void Update() movement.x Input.GetAxis( quot Horizontal quot ) movement.y Input.GetAxis( quot Vertical quot ) private void FixedUpdate() rigidbody2d.MovePosition(rigidbody2d.position movement speed Time.deltaTime) but not with this, and I can't understand why public class RubyController MonoBehaviour public Rigidbody2D rb2d float horizontal float vertical public float speed 5f private void Start() rb2d GetComponent lt Rigidbody2D gt () private void Update() horizontal Input.GetAxis( quot Horizontal quot ) vertical Input.GetAxis( quot Vertical quot ) private void FixedUpdate() Vector2 position this.rb2d.position position.x position.x speed horizontal Time.deltaTime position.y position.y speed vertical Time.deltaTime rb2d.MovePosition(position)
0
How do I run a headless Unity server in a Windows Docker (without GPU)? I am trying to run a headless Unity server on a Windows Docker. On Linux, there is Xvfb, but I don't know how I could get similar results on Windows. How would I do that?
0
Rotating UI element using touch for mobile Unity 2D I want to create the above object that will rotate on z axis following the direction of a finger. Like a dial. I have written the following code and attached it to that element private float rotationRate 3.0f void Update() get the user touch input foreach (Touch touch in Input.touches) Debug.Log("Touching at " touch.position) if (touch.phase TouchPhase.Began) Debug.Log("Touch phase began at " touch.position) else if (touch.phase TouchPhase.Moved) Debug.Log("Touch phase Moved") transform.Rotate(touch.deltaPosition.y rotationRate, touch.deltaPosition.x rotationRate, 0, Space.World) else if (touch.phase TouchPhase.Ended) Debug.Log("Touch phase Ended") But the element does not move at all. Any ideas? EDIT Here is a gif for better understanding
0
How do you make small icons look good? I am running into an issue with my UI. Basically I need to have a lot of small icons, similar to many other games, here is an example With Mip maps As you can see, these look awful. This is simply a UI Image with size 15x15, it seems when they get too small it simply does not look good. It has nothing to do with import options or anti aliasing, I have tried everything there. I submitted it as a bug but according to Unity it simply will not look good when images are scaled down too much.I have tried both PNG with large resolutions and small, I have exported the .SVG vector image and tried using that, all look bad when scaled down. So what are my options then when I need small icons? How do other games do it? Here is a link to the actual .png file https ibb.co nDG0hmD For reference, here are the same icons zoomed in, as you can see, they look fine Im developing for PC.
0
My mesh has holes in it. How do I make those invisible faces show? I have a mesh. A perfectly normal mesh, without any artefacts at all. However, when I import it into Unity, there are holes in it. After going through my UV mapping and normals, they are all mapped, have no faces with the normals going the wrong way (facing inwards) and have non transparent textures over each mapped UV face. Oddly enough, this mesh hasn't been split, despite its poly count and is one whole object, but yet It has missing polygons. Is there any way to get Unity to recognise these faces? Also, it is worth noting that these holes happen to be all the tris faces on this model, and are all (mostly) along the UV seames. Question How do I make the invisible faces show? What's going on?
0
Unity3D Touch and Objects have different coordinate systems I would like to associate the same script to different empty objects I just use as placeholders in the game. The aim is to exploit their positions so that when the user touch a point in the screen, close to one of these objects, a dedicate GUI appears. The problem is that though the two objects are different their scripts seem to influence each other so that when the game is running and I touch one of these two objects both the gui appears. What am I doing wrong? Some hours later... This happens because the object and the touch are in two different coordinate systems. For instance though I touch the object I get ( 0.77, 0.46) for the object and (12.1,95.2) for the touch which, I guess, is measured in pixel. How to transform one into the other? .... private var check boolean var topCamera Camera var customSkin GUISkin function Update () if (Input.GetMouseButtonDown(0)) if(Input.mousePosition.x gt this.transform.position.x Screen.width 0.20 amp amp Input.mousePosition.x lt this.transform.position.x Screen.width 20) if(Input.mousePosition.y gt this.transform.position.y Screen.height 0.2 amp amp Input.mousePosition.y lt this.transform.position.y Screen.height 0.2) check true if(check) the camera zooms forward else the camera zooms backward function OnGUI () if (this.check) var w Screen.width var h Screen.height var bw 0.083 var bws 0.001 w GUI.skin customSkin GUI.Box(new Rect(w 0.6,h 0.3,w 0.38,h 0.45), "Stuff") customSkin.box.fontSize 0.04 h customSkin.textField.fontSize 0.08 h customSkin.button.fontSize 0.04 h textFieldString GUI.TextField (Rect (w 0.62, h 0.39, w 0.34, h 0.1), textFieldString) if (GUI.Button (Rect (w 0.62,h 0.50, w bw, h 0.1), " ")) if (this.check) this.check false else this.check true ... ...
0
Audio slider doesn't change value For some reason, my slider and audio resets back to 0 when I stop and play the game after I changed the value. Here is the code, I can't spot anything wrong with it using UnityEngine using System.Collections using UnityEngine.UI public class MainAudio MonoBehaviour public Slider slider void Awake() PlayerPrefs.Save () GetComponent lt AudioSource gt ().volume PlayerPrefs.GetFloat ("CurVol") if (slider) slider.value GetComponent lt AudioSource gt ().volume public void VolumeControl(float volumeControl) GetComponent lt AudioSource gt ().volume volumeControl PlayerPrefs.SetFloat ("CurVol", GetComponent lt AudioSource gt ().volume) PlayerPrefs.Save ()
0
Unity "Text Mesh Pro UGUI" component rewrites my text! Make it stop? I'm having this terribly annoying problem where my text is being overwritten by Unity. This Happens regardless of whether I am using tags or not. Here is what I want to appear (more or less, I don't think this example is using the tag) And here is what happens when I try to include a monospace tag Since you might not see it here, the text I inputed is lt mspace 64px gt A lt mspace gt This works FINE for regular TMP objects, which the other 3 are (and are using). I am trying to implement dropdown (and left, and up, and right) menus. You can see that Unity overwrites it as "Option A", like it has a clue what I'm doing. What can I do?
0
Multiplayer VR art gallery using different headsets I'm creating a VR art gallery using Unity3D (like a VR Museum Views with more freedom) and would like to have an environment where 1 or more users can gather together, communicate and move around (similar concept to SecondLife except in this case would be first person view (by default) with only one room location and users would be in VR). From a user perspctive, the initial screen would be a door and the user would have a mini map and a menu, turned to him herself, with specific actions. Once inside of the gallery, the users would be able to see others, "walk" or "teleport" to different locations and see the canvas The overall environment is rather simple so I've decided to get feedback from potencial users. Turns out the majority doesn't want to be alone in such environment. So, I've considered adding multiplayer (one of the users could even be guiding the others, which is interesting). Now, multiplayer makes more sense when we can more inclusive. That's where the problem starts. In this specific case, inclusive is being defined as the possibility of users to be able to be present in the environment using at least one of the following devices Android Phone (Cardboard) Oculus GO Samsung Gear VR Google Daydream Oculus Rift HTC Vive I've done some research and couldn't find someone doing it or a way to do it (considering all of the requirements). If that's possible to do, how can i do it? One thing I found was that if I didn't want the users to move around and just be watching the gallery like watching a webinar presentation in different devices, I could use VR Sync (they basically synchronize video playback on multiple VR devices). So, at the moment I can either have the environment with just one user at a time and develop the environment for all the different headsets or use VR Sync.
0
Unity Profiler How do I correct Audio (WASAPI) Feeder issues? I've got the following data after running the Unity Profiler If I'm reading this correctly, the thing that's driving me down to 1 FPS is the CPU Audio. I can't understand what's going on here, though, because there isn't any audio in my game right now.
0
How to move objects across a canvas with consistent speed on different screen resolutions? I am making a rhythm game in Unity. I have been using Transform.Translate for moving images on a canvas as the music notes. However, I cannot consistently use this method on different screen widths. The notes move the same amount each frame. I want to use interpolation for my music notes. I want to have the notes reach the center of the canvas at the same time despite the width of the screen. How can I write such a script?
0
Bullet is not instantiating properly in Unity So I'm trying to make a simple weapon where I just instantiate a bullet at the Shoot Point's gameobject position. For some reason when I press down on my mouse the bullet just flies up. Any ideas on why this could happen? Vector3 velocity bullet.transform.forward 1000 GameObject bulletGameObject Instantiate(bullet, shootPoint.transform.position, Quaternion.identity) Rigidbody bulletBody bullet.GetComponent lt Rigidbody gt () bulletBody.velocity velocity Destroy(bulletGameObject, 4f)
0
What are the correct steps to add Admob to Unity? The official documentation leaves out really important steps. Adding 'cocaopods' and 'Google Play Services' They are just listed as prerequisites without even any links. Another confusing thing is that, elsewhere I have seen that apparently I don't also need the Unity Google Play Games Services SDK for Admob to work. But in that case then why is 'Google Play Services' listed as a prerequisite on the official docs?
0
How to fade in and out a game object with two child game objects I have been fading game objects in and out using the following code. Now I want to fade out a game object with two child game objects. How can I do this? IEnumerator FadeToForGO(Material material, float targetOpacity, float duration, GameObject gameObj, bool isEnabled) Cache the current color of the material, and its initiql opacity. Color color material.color float startOpacity color.a Track how many seconds we've been fading. float t 0 if (isEnabled) gameObj.GetComponent lt BoxCollider2D gt ().enabled isEnabled while(t lt duration) Step the fade forward one frame. t Time.deltaTime Turn the time into an interpolation factor between 0 and 1. float blend Mathf.Clamp01(t duration) Blend to the corresponding opacity between start amp target. color.a Mathf.Lerp(startOpacity, targetOpacity, blend) Apply the resulting color to the material. material.color color Wait one frame, and repeat. yield return null if (!isEnabled) gameObj.GetComponent lt BoxCollider2D gt ().enabled isEnabled
0
Physics Determine how much thrust to apply at each thruster for linear angular acceleration I have a question somewhat similar to this one 2D Spaceship Thruster Movement Turning. I have a ship with thrusters placed randomly on it (not necessarily symmetrically), and I need to know which thrusters and how much to fire them to have a perfectly linear acceleration, as well as how much they contribute to the angular acceleration of the ship to know which ones to fire when you want to turn the ship. What I know the position and orientation of the thrusters, the center of mass of the ship. Basically I just need a way to make the ship obey the commands as best as physically possible, the commands being 'move' (apply acceleration on thrusters so if results in a linear acceleration), and 'rotate' (apply differential acceleration to maximize angular and minimize linear acceleration). The game is 2D. Thank you very much in advance.
0
UnityEditor.SyncVS.SyncSolution putting wrong language version in generated files I'm working on getting our Unity projects building in bamboo for our build server. We have a cli step that runs through the Unity commands for creating a build. It works fine on several projects, but for some reason this particular project I'm working on I'm getting an error that states I need to use c version 7.2 or newer. If I log in to the build server and open the .csproj files in notepad and check the language version, it's setting them to 7.0. However, if I deactivate the cli step so that the build job only clones the project, then manually log in and open unity and go through the process so it generates the .csproj files, then check them, the language version is set to 8.0. The project works fine locally on my own pc. And it works when setup manually on the build server pc, but when ran through the cli step, it generates them at an earlier c version. This leads me to believe there is a problem with the UnityEditor.SyncVS.SyncSolution step in my commands. I'm just not sure what it could be, or why it's behaving differently for this project as opposed to other projects that are using the same code base (where the problem is said to occur), same Unity version, same build server, etc. Anyone else experience this issue or have any thoughts on a solution?
0
Unity Instantiate 2 copies at same time?? (Asteroids clone) C I haven't been at my computer learning code or game dev in a few months and am just starting again. I am trying to make a game very similar to Asteroids. In 3d but fixed camera from above so basically disregarding the Y Axis at the moment. I have everything working fine so far such as the rocket stays in middle and can rotate, and fire weapon. The Asteroids for now all come from the top side of the screen, and have some code to randomise the X location and speeds. When the laser hits the Asteroid I want it to destroy that Asteroid and create two more that are half the size and with a Rotation added of 45 45 degrees. I have the code that I thought would work but it is only creating one more and not two. (note as you'll see I have tried making tempAsteroid2 and even asteroidPrefab2, before this I just had the one which I tried to instantiate twice). What am I missing? why does this code not make two more appear upon laser collision?? Any help massively appreciated as always. Many thanks public class Asteroid MonoBehaviour float speed public GameObject asteroidPrefab, asteroidPrefab2 public int sizeKey 2 Use this for initialization void Start () if (sizeKey lt 1) Destroy(this.gameObject) transform.position.Set(transform.position.x, 0f, transform.position.y) speed Random.Range(0.5f, 2f) Update is called once per frame void Update () GetComponent lt Rigidbody gt ().transform.Translate(Vector3.forward speed Time.deltaTime) private void OnTriggerEnter(Collider other) if (other.tag "Laser") BreakAsteroidInHalf() Destroy(other.gameObject) void BreakAsteroidInHalf() GameObject tempAsteroid asteroidPrefab tempAsteroid.transform.position transform.position tempAsteroid.transform.Rotate(0, 45, 0) tempAsteroid.transform.localScale 0.5f tempAsteroid.GetComponent lt Asteroid gt ().sizeKey 1 Instantiate(tempAsteroid) GameObject tempAsteroid2 asteroidPrefab2 tempAsteroid2.transform.position transform.position tempAsteroid2.transform.Rotate(0, 45, 0) tempAsteroid2.transform.localScale 0.5f tempAsteroid2.GetComponent lt Asteroid gt ().sizeKey 1 Instantiate(tempAsteroid2) Destroy(this.gameObject) Debug.Log("Asteroid destroyed and replaced by 2 more")
0
Emit particles from only some parts of a mesh I have a 3D mesh with 3 sub meshes in it, for 3 different materials. I would like particles to spawn from the mesh, but only from location where one of the material is assigned. How can I make this happen?
0
How can I copy an asset folder programatically depending upon a constant? I have a Unity project in which I have 200 games and some 350 scenes. Now I want to make separate builds for each game. All my assets are present in Assets IgnoredAssets ABC folder. To include these assets in my current build the assets of the current game (say ABC) needs to be in Assets Resources ABC. I want Unity to take these Assets IgnoredAssets ABC files and copy them to Assets Resources before making build depending upon a constant defined in some file. I want a kind of automation so that when I mention in my constant file string gameName "ABC" it automatically picks its assets, paste them in Resources and builds for me. How can I do this?
0
Double jump, without allowing two jumps after falling down a cliff I created a script that allows the player to double jump, which works like a charm. The problem is if the player walks off a cliff, they will still be able to jump twice. But that isn't how double jump works, right? Can someone tell me how to make it so that if the player falls down a cliff, they will be able to jump only once? using System.Collections using System.Collections.Generic using UnityEngine public class PlayerController MonoBehaviour private Rigidbody2D rb private Animator anim private float movementInputDirection public float movementSpeed 10f public float jumpForce 16f public int amountOfJumps 1 private int amountOfJumpsLeft private bool isFacingRight true private bool isWalking private bool isGrounded private bool canJump public float groundCheckRadius public LayerMask whatIsGround public Transform groundCheck void Awake() rb GetComponent lt Rigidbody2D gt () anim GetComponent lt Animator gt () void Start() amountOfJumpsLeft amountOfJumps void Update() CheckInput() CheckMovementDirection() UpdateAnimations() CheckIfCanJump() private void FixedUpdate() ApplyMovement() CheckSurroundings() private void CheckMovementDirection() flips sprite if (isFacingRight amp amp movementInputDirection lt 0) Flip() else if (!isFacingRight amp amp movementInputDirection gt 0) Flip() if(rb.velocity.x ! 0) isWalking true else isWalking false private void UpdateAnimations() anim.SetBool("IsWalking", isWalking) private void CheckInput() movementInputDirection Input.GetAxisRaw("Horizontal") if (Input.GetButtonDown("Jump")) Jump() private void ApplyMovement() player movement rb.velocity new Vector2(movementSpeed movementInputDirection, rb.velocity.y) private void Flip() isFacingRight !isFacingRight transform.Rotate(0f, 180f, 0f) private void Jump() if (canJump) rb.velocity new Vector2(rb.velocity.x, jumpForce) amountOfJumpsLeft private void CheckSurroundings() isGrounded Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround) private void CheckIfCanJump() if (isGrounded amp amp rb.velocity.y lt 0.01) amountOfJumpsLeft amountOfJumps if (amountOfJumpsLeft lt 0) canJump false else canJump true private void OnDrawGizmos() Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius)
0
In Unity, can I load a local ( Resources folder) website to safari on an ipad In Unity, can I load a local ( Resources folder) website to safari on an ipad? This works fine on a Mac, opening up a wepage from my Resources folder. string path "file " (Application.dataPath) " Resources testsite.html" void OnGUI() if(GUI.Button(new Rect(20, 20, 100, 100), "site")) Application.OpenURL(path) but when I try to load this on an iPhone or iPad, it doesn't seem to work. Am I accessing the address incorrectly for iOS using "file "? If this is not possible, is there an alternative way I can load a locally stored website on an iOS device?
0
GameObject walk onto platform Unity2D I currently am working on a 2D game designed for android and iOS. I have a repeatedly spawning enemy game object which comes in from the left. I want the enemy game object to walk onto a slope which leads to a platform. I've tried adding physics rendering but it doesn't seem to work. I tried adding colliders to both and still nothing. The enemy object just goes straight through the slope and doesn't actually climb it.
0
Vibration duration for mobile devices in Unity I'm used the Handheld.Vibrate() method. I know that if you call it several times, you can increase the vibration time, but when it is called once, the vibration lasts about 1 second. But I would like to make an imitation of clicking on the android keyboard. (Vibration 0.2s) How to set the duration of the vibration?
0
Foreach list loop problem I am having a problem with a foreach loop. When my AOE ability hits an enemy it creates a CircleCollider2D and puts all the enemies on a list, which then the loop goes through and adds damage to their scripts. private void OnTriggerEnter2D(Collider2D other) if(other.tag "Enemy") targets.Add(other) foreach (Collider2D enemy in targets) EnemyHealth hp enemy.GetComponentInChildren lt EnemyHealth gt () hp.TakeDamage(abilityConfig.baseDamage) print(enemy.name " takes " abilityConfig.baseDamage "damage!") But as you can see from the picture below the loop goes 3 times over one enemy, 2 times over the second one and once over the third. As these enemies are the same type they all have the same EnemyHealth script. If anyone would point me in the right direction I would greatly appreciate it.
0
GraphicRaycaster on the child object containing buttons blocks Raycast from the parent object containing GraphicRaycaster. How to solve it? What I'm trying to achieve is to detect clicks on buttons in UI. Here is the tree I have a parent object SlotMachineScreen containing GraphicRaycaster with a script detecting clicks attached to it if (Input.anyKeyDown) Set up the new Pointer Event m PointerEventData new PointerEventData(null) Set the Pointer Event Position to that of the mouse position m PointerEventData.position Input.mousePosition Create a list of Raycast Results List lt RaycastResult gt results new List lt RaycastResult gt () Raycast using the Graphics Raycaster and mouse click position m Raycaster.Raycast(m PointerEventData, results) foreach (RaycastResult result in results) Debug.LogWarning( quot Hit quot result.gameObject.name) And there are a bunch of child objects with a GraphicRaycaster (red ones) with buttons in it, that I want to detect a click on. But there is no response from my sprit at all when I click on them. I found one solution so far, but its not what I need the solution is to move all buttons from child containers to SlotMachineScreen. Are there any different ways to solve this problem?
0
Implementing Galaga Style Enemy Behavior in Unity I've been trying to work on a space shooter with the idea of having enemies behaving like it is shown in this video https www.youtube.com watch?v 3p7u8uCR6yw In the video above, enemies fly from different portions outside the view area of the screen doing elaborate movement before finding a spot to form an organized formation. I've been thinking of ways how this could all be done. One way is by having either the enemies and or a manager use a Finite State Machine that will control when there is a "performing" state and when there is a "FindingSpot" state. but at as far as implementing the complex patterns, I'm at a loss. Is there some sort of Math formulation that's used to generate those movement patterns?
0
Selecting Dictionary item based on custom classes instead of keys I am attempting to write my own path finding code for a game I'm working on that will implement a form of the A algorithm. I store my nodes of the path finding system as a class called nodes and add these to a dictionary with their position in world space as the key for the dictionary. Here's the problem. At one point I need to test the dictionary and return from it the node with the lowest "f" value. I came across the morelinq MinBy function with seemed promising, but so far have not had any luck getting it to work. Here is a stripped down version of the code using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using MoreLinq public class GMove MonoBehaviour public Dictionary lt Vector3, Node gt vectorNodesOpen new Dictionary lt Vector3,Node gt () public Dictionary lt Vector3, Node gt vectorNodesClosed new Dictionary lt Vector3,Node gt () private KeyValuePair lt Vector3, Node gt currentNode new KeyValuePair lt Vector3,Node gt () private bool goal private bool findingPath void Start() goal false findingPath false public void addNodes() several nodes get added to the dictionary based on the A algorithm ending way point and beginning waypoint are stored as Vector3 public class Node public int h get set public int g get set public int f get set public Vector3 pos get set public Vector3 parentNodeVector get set void Update() if(findingPath) while (!goal) currentNode new KeyValuePair lt Vector3, Node gt (vectorNodesOpen.MinBy(x gt x.Value.f).Key, vectorNodesOpen vectorNodesOpen.MinBy(x gt x.Value.f).Key ) This is the line in which I'm attempting to get the node in the open list with the smallest f value. vectorNodesClosed.Add(vectorNodesOpen.MinBy(x gt x.Value.f).Key, vectorNodesOpen vectorNodesOpen.MinBy(x gt x.Value.f).Key ) vectorNodesOpen.Remove(vectorNodesOpen.MinBy(x gt x.Value.f).Key) remove current from open. if (currentNode.Value.pos waypointEnd) if current node end position we are done. goal true addNodes(currentNode.Value.pos, waypointEnd) Add and update nodes The line that is giving me trouble is the first line inside the while loop. I need a way to return the Dictionary item with the smallest "F" value, this would be pretty easy if it were an integer but the F value resides in the Node class. I don't have to use MoreLinq, I would be happy to do it any other way that someone can come up with. Cheers! One more note the code above is incomplete in an effort to minimize it down to only what is necessary to understand the problem more complete code can be provided if necessary.
0
How to keep a round body rotating without rotating it's center I want to make a game in Unity in which the Player is a sad star. I want to have the points (The "arms and legs and head") of the star to rotate like a circle but to keep it's face (which is in it's center) still. How can I do that ? The body should rotate and it's center should stay still. Many thanks in advance!
0
How to place grass on custom terrain mesh I made a custom terrain mesh and textured it, now I want to place grass on it, but I don't know how. I only find info about grass with the unity terrain. I am not even sure what exactly to look for. What is the best easiest way to place grass on a terrain? I'd like to do it in the shader if possible, but I guess I will need additional geometry if I want it to "stick out"? (Random example picture http www.beamng.com attachments stuff png.16516 ) I'd appreciate a general outline on how to tackle this problem and maybe some links for further reading. Thanks.