_id
int64
0
49
text
stringlengths
71
4.19k
0
Disable global fog from camera Does anyone know how to disable global fog from a particular camera? I have two cameras in my scene one is a mini map camera, where I need to disable global fog. I have checked this answer and the wiki, but have found nothing that works.
0
Why does Unity think my RectTransform has changed? I am working with UI. I want to know when my RectTransform changes its position. I am using transform.hasChanged void Update() if (transform.hasChanged) Debug.Log("Updated Position") transform.hasChanged false However, it thinks it has always changed. "Updated Position" is constantly printing out. If I remove and then readd the component while in play mode, the issue resolves itself. However, I don't want to have to do this, as it is very hacky. I could just throw a bunch of if statements in there to check, but I'd prefer to make use of the build in transform.hasChanged property. How can I check to see if my RectTransform has changed its position efficiently and elegantly?
0
Unity DirectoryInfo not working in OSX standalone build So I'm building an application in unity which I hope to use at a market day coming up soon at my school (it's not a game, it's basically like a checkout app, kind of...) Anyway, I'd like to be able to import images from the app and to have the option to change them while the app is running. Currently I have the images in a folder and I'm using DirectoryInfo to get the contents of that folder and load the images. Works like a dream inside the editor but as soon as I build the app (on OSX), everything is blank. Other people seem to have similar issues but I'm a little unsure as to how they fixed it. Could someone please help me, this is kind of urgent!
0
Get VertexSize of Instance in VertexShader I'm using Unitys DrawProceduralIndirect function to directly render the content of a ComputeShader. I setup the argumentBuffer for this function as follows int csArgs new int ptsOnLine, 2, 0, 0 argsBuffer new ComputeBuffer(4, 4, ComputeBufferType.IndirectArguments) So every instance consists of ptsOnLine (lets say 10) vertices. My vertexShader then looks like this fsInput vert(uint id SV VertexID, uint instanceId SV InstanceId) fsInput fsIn float3 worldPos linePoints id (instanceId 10) fsIn.pos mul(UNITY MATRIX VP, float4(worldPos, 1.0f)) return fsIn The question is simple. My problem is (instanceId 10). Is there a built in variable telling me the length of one instance? I couldn't find anything. I mean, its in the argument buffer so it shouldn't be too much of a problem? I could forward this value from the compute buffer but thats ugly. ) Help is much appreciated!
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
Null instance on manager class extending from singleton class I have four classes class A, which is abstract and partial extending from singleton class C. class A1, which is partial and extending from class A . class B, extending from class A. class C, a singleton which has code to throw an exception if the instance is null, and otherwise uses DoNotDestroyOnLoad(). In scene view, I add class B to the scene. It works, but throws a null instance exception for class A, as it's instance is not present in scene. I think this is because class A extends from a singleton class, and it has ability to throw exceptions when the instance is null. I can not add the class A to the scene because it is abstract. What can I do to in order to add the class A component to the scene, or otherwise not to get this error?
0
Loading player position from file but player object not at right position sometimes In my current project I am developing a game saving system and I have encountered a problem where in some cases when I save the game and re load it the player will not be loaded in at the correct position. I've printed the position that is loaded in from file to the console to see if it's being changed and it's not. Is there anything i'm not seeing? For reference here's the two methods I use when loading the game public void LoadData() if (File.Exists(filename)) byte soupBackIn File.ReadAllBytes(filename) string jsonFromFile encryption.Decrypt(soupBackIn, JSON ENCRYPTION KEY) copy JsonUtility.FromJson lt SaveData gt (jsonFromFile) print(copy.playerPosition) DataToLoad() private void DataToLoad() player.transform.position copy.playerPosition player.transform.rotation copy.playerRot player.playerHealth copy.playerHealth player.agility copy.agility player.attack copy.attack player.defense copy.defense player.strength copy.strength for (int i 0 i lt copy.inventory.Count i ) inv.AddItem(copy.inventory i .id)
0
Adding a feedback survey to a game So I am currently making a game that aims to help people with anxiety management. I , however, would like to ask them how they feel before playing the game and then again after playing the game. Would it be possible to do this directly on Unity? I would like for them to be able to log their entries much like an online journal. I have attached pictures from the daylio app. I would like to do something similar. At this point, I really do not know how to begin doing this on Unity. Any advice, or tutorial suggestions would be appreciated. This far I have managed to do the following (in the picture below) This is how the survey looks (its pretty rudimentary at this point) And this is where the information is getting displayed (in the inspector) So now, what I would like to know, is how would I go about sending this data to somewhere else i.e. as it is in the daylio app?
0
Rendering part of an equirectangular video on a plane For a Unity project I have a 360 camera which produces an equirectangular video. I need to realize preview of this video for putting it on a plane. In most cases the part of the video to be drawn on the plane is the central part of the video, which is not so stretched and so it can be drawn as is. In some cases, instead, the camera has to be put above the scene, upside down, in order to capture the scene below, as shown in the following image. In this kind of situation I need to produce a preview from the upper part of the video in other words I need to project a portion of the upper part of the video on a plane. I imagined two ways, the first one is easy but not so effective, the second one is tricky but surely better. I project the video on a sphere and capture, with a virtual camera, the interesting part, which is taken and rendered on a plane. I write an appropriate shader which, given the equirectangular video, crops the portion of it and draws it correctly on a plane. May you give me a hand on writing the shader?
0
Surface Depth Intersection Shader I recently asked a question about the creating an accurate Depth Intersection Shader. When creating this in a fragment vertex shader it could be achieved by the following code SubShader Blend SrcAlpha OneMinusSrcAlpha ZWrite On Tags "RenderType" "Transparent" "Queue" "Transparent" Pass CGPROGRAM pragma target 3.0 pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct appdata float4 vertex POSITION float2 uv TEXCOORD0 float3 normal NORMAL struct v2f float2 uv TEXCOORD0 sampler2D MainTex float4 MainTex ST sampler2D CameraDepthTexture fixed4 Color fixed4 GlowColor float FadeLength v2f vert(appdata v, out float4 vertex SV POSITION) v2f o vertex UnityObjectToClipPos(v.vertex) o.uv TRANSFORM TEX(v.uv, MainTex) return o fixed4 frag (v2f i, UNITY VPOS TYPE vpos VPOS) SV Target float2 screenuv vpos.xy ScreenParams.xy float screenDepth Linear01Depth(tex2D( CameraDepthTexture, screenuv)) float diff screenDepth Linear01Depth(vpos.z) float intersect 0 if(diff gt 0) intersect 1 smoothstep(0, ProjectionParams.w FadeLength, diff) return fixed4(lerp(tex2D( MainTex, i.uv) Color, GlowColor, pow(intersect, 4))) ENDCG However, when I try to put the same logic into a surface shader, the result does not show any depth intersections. SubShader Blend SrcAlpha OneMinusSrcAlpha ZWrite On Tags "RenderType" "Transparent" "Queue" "Transparent" CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard fullforwardshadows alpha fade Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D MainTex struct Input float2 uv MainTex float4 screenPos float eyeDepth half Glossiness half Metallic sampler2D CameraDepthTexture fixed4 Color fixed4 GlowColor float FadeLength Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader. See https docs.unity3d.com Manual GPUInstancing.html for more information about instancing. pragma instancing options assumeuniformscaling UNITY INSTANCING CBUFFER START(Props) put more per instance properties here UNITY INSTANCING CBUFFER END void surf (Input IN, inout SurfaceOutputStandard o) float2 screenuv IN.screenPos.xy ScreenParams.xy float screenDepth Linear01Depth(tex2D( CameraDepthTexture, screenuv)) float diff screenDepth Linear01Depth(IN.screenPos.z) float intersect 0 if (diff gt 0) intersect 1 smoothstep(0, ProjectionParams.w FadeLength, diff) fixed4 col fixed4(lerp(tex2D( MainTex, IN.uv MainTex) Color, GlowColor, pow(intersect, 4))) o.Albedo col.rgb o.Alpha col.a o.Metallic Metallic o.Smoothness Glossiness ENDCG
0
Using Euler angles to rotate object 360 degrees I'm trying to create script that rotates object in given axis by set amount of degrees. That's my 2 core methods public Vector3 rotation public void RotateDegreesFast () transform.DOLocalRotate (GetTargetRotation (), rotationTime) private Vector3 GetTargetRotation () Vector3 newRotation new Vector3 ( rotation.x transform.localEulerAngles.x, rotation.y transform.localEulerAngles.y, rotation.z transform.localEulerAngles.z) return newRotation I was using this script for a little while, it was working perfectly in Y and Z axis. Now I try to rotate object 45 degrees in X axis (rotation new Vector3(45f, 0f, 0f)). It works until rotation in x value equals 135. Transform.localEulerAngles.x is returning 45 instead of 135. So it's stuck between 90 and 135 degrees. I was trying to use transform.localRotation.eulerAngles.x instead, but it doesn't work as well. I am aware this works that way because specific Euler angle can be represented in many ways. I also know that DOTween has DOLocalRotateQuaternion method, but the thing is that this component is often reused by a designer that sets value of rotation variable in the inspector. It's way easier to use Euler angles for him.
0
How do I add an "offset" to LookAt? I have created a Third Person Controller. The camera is behind the player I would like to make it so that the player aims at the mouse pointer position. To do that, I use the following code to rotate the chest towards the position var mousePos Input.mousePosition mousePos.z 10 Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) Chest.LookAt(aim) The hands do not perfectly straightly point forwards, so I need to add an quot offset quot to the LookAt. I tried this approach var mousePos Input.mousePosition mousePos.z 10 Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) aim new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0) Chest.LookAt(aim) Of course I do all rotation patching in LateUpdate(). In Update(), it would simply be erased by the animation itself. It does work, but when the model is rotated around the Y axis, something goes wrong The offset is quot wrong quot , it doesn't have the same effect. This surprises me because all I do is rotate the entire model. So I think this line is not correct aim new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0) Is this not the way to offset the LookAt results?
0
UDP server in unity not working I know there are a lot of UDP examples out there, but I really need to know specifically what I am doing wrong. I have Wireshark monitoring my data traffic and according to that program Unity is not sending data at all. Could some of you coding wizards look over this and help me find my mistake? public class heatLampControl MonoBehaviour Ben Stewart, june 6th, 2016 this code controls the "Position" of the heat lamps, ie what angle the heat should be coming from. The value will be added to a new UDP connection to the dSPACE machine Update 6 10 Added UDP functionality, as accessing the UDP class that was created for this purpose turned out to not function correctly public float lampIntensity 0.0f Multiplier for relative intensity of the sunlight GameObject sun public GameObject player dropped in via GUI public bool isNight false is it night? if so, heat lamp should turn off public double sunAngle angle about the y axis. that is the only angle that can be controlled. public bool isOn false public string keyDown public int port public string dataStr byte data public GameObject cycle following three keep track of day night cycle public Day Night.TimeOfDay tod public Day Night dayNight public int strLength private IPAddress ip private UdpClient udp private IPEndPoint ipep public float fruitIntensity public float hayIntensity OlfactoryControl olfactory string hostname IPAddress ipList void Start () hostname Dns.GetHostName () ipList Dns.GetHostEntry (hostname).AddressList port 13722 cycle GameObject.Find ("DayNight") dayNight cycle.GetComponent lt Day Night gt () sun this.gameObject olfactory GameObject.Find ("Olfactory").GetComponent lt OlfactoryControl gt () ip ipList 0 ipep new IPEndPoint (ip, port) udp new UdpClient (13722) Update is called once per frame void Update () sunAngle player.transform.eulerAngles 1 Math.Atan2 (sun.transform.position 2 , sun.transform.position 0 ) gets the positional angle of the sun compared to the player keyDown Input.inputString if (isNight Input.GetKeyUp (KeyCode.L)) IF L is pressed down, light will come on lampIntensity 0f isOn false if (!isNight amp amp Input.GetKeyDown (KeyCode.L)) lampIntensity 1f isOn true tod dayNight.tod if (tod Day Night.TimeOfDay.Idle) lampIntensity 1.0f if (tod Day Night.TimeOfDay.SunRise) lampIntensity (dayNight.timeOfDay (dayNight.sunSet dayNight.StartTime)) hayIntensity olfactory.hayIntensity fruitIntensity olfactory.fruitIntensity sendUdp () june 30th edit void sendUdp() dataStr hayIntensity.ToString () fruitIntensity.ToString () lampIntensity.ToString () byte sendBytes System.Text.Encoding.ASCII.GetBytes (dataStr) Debug.Log (dataStr) udp.Send (sendBytes, sendBytes.Length, ipep) Debug.Log ("Data sent to IP Address " ip.ToString() " on port " port.ToString())
0
Null Reference Exception while getting Components I'm trying to access my enemy and spawning values from two different classes into a class that is trying to change them both. Although when I do this I keep getting a Null Reference Exception error. The error is where spawnManager first gets called. This is the code that is trying to get the two values. (And just to note I am trying to access these two values from my Welcome scene and these two values are in my Game scene but I do not know if this is affecting anything) private EnemyAI enemy private SpawnManager spawnManager void Start() spawnManager GetComponent lt SpawnManager gt () enemy GetComponent lt EnemyAI gt () public void onEasy() spawnManager.enemyShipWait Random.Range(1f, 3f) lt This line has the error spawnManager.randomPowerupWait Random.Range(7f, 12f) enemy.speed 2.75f These are the two pictures of my scenes Game Scene Welcome Scene
0
Unity higher Z position tiles rendered underneath When placing tiles in an isometric tile map in Unity, I try to place blocks on top using the quot Z Position Value quot However it looks like higher Z position values get rendered underneath. In this picture, the green cubes have a z position of 0 whereas the yellow cubes have a z position of 1. I want the yellow cubes to render on top, but they are underneath. I'm using an Isometric Z as Y tile map and have the Transparency Sort Axis set to (x 0,y 1,z 0.26).
0
How to make a character sit in Unity? So I've got the animation, it has root motion but activating it in the settings doesn't seem to do much. What would be a good optimized way to have the character sit on the stool with the animation matching the movement? Would I need to do it through code?And if that's the case, could I specify in which frame do the movement? Or add a second animation that is in charge of Root Motion? I know either of these two options I give could work but I'm checking to see if there is a better way or if I'm missing something here. Thanks! EDIT Following DMGregory's comment I disabled the collider to see if it improved... it did change, but it isn't much better EDIT 2 This is how the animation preview looks like (what I'm expecting) Then I just hold the last frame while they're sitting and play the animation backwards for when they're getting off this is just while I get it to work.
0
how do I set an int to the scroll wheel data in unity i need to set an int to data from the scroll wheel so I can have the script use this int to display an item attached to a number from that int. i'm using c i set up my scroll wheel input, what am i doing wrong? here is the script counter Mathf.RoundToInt(Input.GetAxis("ScrollWheel")) Items.text counter.ToString()
0
Unity Trying to copy the render texture for the scene rendered by a camera but it is blank? I'm trying to copy the scene rendered by a particular camera to a render target. I know this should be possible to do without using the camera's target texture as I read through this official Unity article about Command Buffers which avoids any use of them. Instead, I found that they use the following code in the renderer for blurry refractions (CommandBufferBlurRefraction.cs) to copy the scene to a render target. buf new CommandBuffer() buf.name "Grab screen and blur" m Cameras cam buf copy screen into temporary RT int screenCopyID Shader.PropertyToID(" ScreenCopyTexture") buf.GetTemporaryRT(screenCopyID, 1, 1, 0, FilterMode.Bilinear) buf.Blit(BuiltinRenderTextureType.CurrentActive, screenCopyID) The problem is that I can't get this to work for myself using a very simple scenario of Camera renders the entire scene which is a single hexagonal sprite The command buffer assigned to the camera grabs the BuiltinRenderTextureType.CurrentActive (Scene Render Target) The command buffer then copies that to another render target That render target is then drawn in the upper left of the screen on a yellow background This results in the scene render target being completely blank and not including the white hexagon. The code I am using is Camera cameraUsedToRender CommandBuffer commandBuffer RenderTexture debugRT Texture2D debugRTBackground void Awake() Create debug texture to render debugRTBackground new Texture2D(2, 2) debugRTBackground.SetPixels(new Color 4 Color.yellow, Color.yellow, Color.yellow, Color.yellow ) debugRTBackground.Apply() cameraUsedToRender Camera.main cameraUsedToRender.orthographicSize 10f Create debug render texture to render to using our camera debugRT new RenderTexture(cameraUsedToRender.pixelWidth, cameraUsedToRender.pixelHeight, 16) debugRT.Create() Create command buffer commandBuffer new CommandBuffer() commandBuffer.name "Debug" Add the camera buffer to the main camera cameraUsedToRender.AddCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, commandBuffer) void OnRenderObject() Clear the command buffer commandBuffer.Clear() Set the render target commandBuffer.SetRenderTarget(debugRT) Clear the render target commandBuffer.ClearRenderTarget(true, true, Color.blue) Copy scene into a render target RenderTarget.active SceneView RT (UnityEngine.RenderTexture) commandBuffer.Blit(BuiltinRenderTextureType.CurrentActive, debugRT) Release the render target commandBuffer.SetRenderTarget(null as RenderTexture) void OnGUI() Draw the debug render target (which should have the SceneView RT copied to it) GUI.DrawTexture(new Rect(0, 0, 130, 130), debugRTBackground) GUI.DrawTexture(new Rect(1, 1, 128, 128), debugRT) The complete small, simple project that demonstrates this issue can be found here. Does anyone have an idea how to resolve this as I'm finding the Unity rendering pipeline to be rather confusing at this point?
0
Determining value to add subtract scaling I have a menu panel. It appears if the user presses the Enter key, and it disappears if he presses the Enter key again. When the menu is still hidden, its X scale is set to 0. In its normal expanded state is 0.00175f. When the menu is shown or hidden, I want to smoothly scale from 0 to 0.00175f or from 0.00175f to 0. To do that, I have written a coroutine private IEnumerator pShrinkExpandMenu(bool uShrink) if (!uShrink) Menu.SetActive(true) the menu should be expanded enlarged, so we need to make sure it's visible float fWidthIfExpanded 0.00175f float TimeInSecondsToSwitch 0.3f TimeElapsedOnShrinkingExpanding Time.deltaTime while ( TimeElapsedOnShrinkingExpanding lt TimeInSecondsToSwitch) float fValue if (uShrink) fValue ... else fValue ... Menu.localScale.X fValue yield return 0 if (uShrink) if we shrink, and it's completely shrunken, hide it Menu.SetActive(false) I hope that my coroutine is fine. One thing that I just don't know is how to determine the value that the X scaling should be changed during one loop. I have no idea how to calculate fValue. Could anybody explain that to me, please?
0
how to sync clients and local avoidance in mobile RTS game? I have been making mobile RTS game in Unity look like Clash Royale similarly. Unfortunately, I faced to two big problems. First is two phones(clients) to be synchronized each other in game state. And second is "path finding" or "local avoidance"(collision check). To solve the path finding issue, I have searched about "Flow Field". Should I do consider on 3 layer map(cost field, integration field, flow field) to apply "Flow field"? If I do apply "flow field" to my game, can I have a liberty from the problem of Sync two clients? Thank you in advance.
0
How to use base.Function() in Unity I am using 3 classes EnemyBullet MonoBehavior EnemyBulletType1 EnemyBullet EnemyBullet Class void FixedUpdate() this.gameObject.transform.rotation Quaternion.Euler (new Vector3 (0,0,90)) EnemyBulletType1 Class override void FixedUpdate() base.FixedUpdate () Do something else here The reason is I'll have many EnemyBulletType classes and I want them all to do a common thing and then do something on their own. Question This code isn't working Error virtual or abstract members cannot be private How is FixedUpdate() defined in the MonoBehviour and how to change it to help my usecase?
0
What is the proper way to handle data between scenes? I am developing my first 2D game in Unity and I have come across what seems an important question. How do I handle data between scenes? There seems to be different answers to this Someone mention using PlayerPrefs, while other people told me this should be used to store other things like screen brightness and so on. Someone told me that the best way was to make sure to write everything into a savegame everytime that I changed scenes, and to make sure that when the new scene loads, get the info from the savegame again. This seemed to me wasteful in performance. Was I wrong? The other solution, which is the one I have implemented so far is to have a global game object that isn't destroyed between scenes, handling all the data between scenes. So when the game starts, I load a Start Scene where this object is loaded. After this ends, it loads the first real game scene, usually a main menu. This is my implementation using UnityEngine using UnityEngine.UI using System.Collections public class GameController MonoBehaviour Make global public static GameController Instance get set void Awake () DontDestroyOnLoad (transform.gameObject) Instance this void Start() Load first game scene (probably main menu) Application.LoadLevel(2) Data persisted between scenes public int exp 0 public int armor 0 public int weapon 0 ... This object can be handled on my other classes like this private GameController gameController GameController.Instance While this has worked so far, it presents me with one big problem If I want to load directly a scene, let's say for instance the final level of the game, I can't load it directly, since that scene does not contain this global game object. Am I handling this problem the wrong way? Are there better practices for this kind of challenge? I would love to hear your opinions, thoughts and suggestions on this issue. Thanks
0
.png file to Sprite(2D and UI) still not visible under source image I am trying to use an image as a UI Image but even after changing its texture type to Sprite(2D and UI), it isn't visible in the source image menu. The file was created in MS Paint and I'm accessing the source image menu via the "circle selector" next to Source Image in the Inspector. I'm pretty sure I've never had this issue before. I wish I could share more details but there's nothing much to say. What could be causing this issue?
0
Programatically Build List of Custom Class Objects (prefabs) This seems like it should be a simple thing, but I cannot seem to figure out a method. Currently, I have a public List lt MapGraphItem gt roomList variable, and in the inspector, I add prefabs from Tiled2Unity for a given biome currently a list of nine tiles for my test biome. Map generation works great via this method. MapGraphItem is a custom class that is applied to these prefabs via script. I'd like to programmatically build the list so that I can build it appropriately based on the biome that's being called (dungeon, forest, desert, et cetera). I seem to be having trouble getting unity to put together a list of the items anyhow (they are in a specific assets folder and also have a specific prefix, in this case "dng "). I tried this and some variations on it List lt GameObject gt obj GameObject.FindObjectsOfType(typeof(GameObject)).Select(g gt g as GameObject).Where(g gt g.name.StartsWith("dng ")).ToList() But it seems the objects need to be loaded first (plus, I'd need to convert it to a List lt MapGraphItem gt before using it). I could add another field to the MapGraphItem class for biome type and basically load ALL of the assets, but that's a huge waste of resources. Manually adding these for each biome is really not ideal, and really not efficient. Thanks!
0
Blocking Physics Raycasts with Unity's 4.6 UI? I use raycasts to determine hit objects and object selection in our game. I want these to be blocked by UI elements. Before I had a crude form of that where I just excluded rects of the screen, though with a non rectangle shaped UI that's pretty difficult. I want to have physics raycasts NOT go through UI objects, can this be done? My initial thought it adding colliders to the UI objects, though I'm not sure if the colliders will scale with elements based on screen size. Note Canvas Group does not apply to physics.raycast
0
Instantiating problems I'm beginner here, I'm trying to instantiate a single object every specific duration, either form the left of the screen or from the the right, at the same time I want this object to move to the other side of the screen So the troubles I'm facing here are sometimes 2 objects are being instantiated at the same time. the objects move in the direction that are defined in the first if statement (both objects on the left and the right move in one direction) the part where I instantiate objects is in the script(smallFishes) that's attached to an empty gameobject is void Start () timer gameObject.AddComponent lt Timer gt () width 2f timer.Duration 3 timer.Run() left Resources.Load("Left") as GameObject right Resources.Load("Right") as GameObject void Update () if (timer.Finished) lr Random.Range(1, 3) if (lr 1) var generetx 8.8f width 2 Instantiate(left, new Vector2(generetx, Random.Range( 4.8f,4.8f)), Quaternion.identity) else var generetx 8.8f width 2 Instantiate(right, new Vector2(generetx, Random.Range( 4.8f, 4.8f)), Quaternion.identity) timer.Duration 3 timer.Run() public int state get return lr the part where I make the object move from the script that's attached to the object prefab void Start () small gameObject.AddComponent lt smallFishes gt () rb2d gameObject.GetComponent lt Rigidbody2D gt () void Update() var fishes GameObject.FindGameObjectsWithTag("small") if (fishes! null) if (small.state 1) moveright new Vector2(4 Time.deltaTime, 0) rb2d.AddForce(moveright, ForceMode2D.Impulse) else moveleft new Vector2( 4 Time.deltaTime, 0) rb2d.AddForce(moveleft, ForceMode2D.Impulse) Thanks in advance.
0
Programmatically creating new tags in Unity I'm writing a custom editor script to add tags programmatically. I got the error of IndexOutOfRangeException Array index is out of range from the lines below SerializedObject tagManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings TagManager.asset") 0 ) SerializedProperty tagsProp tagManager.FindProperty("tags") These are my codes SerializedObject tagManager new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings TagManager.asset") 0 ) SerializedProperty tagsProp tagManager.FindProperty("tags") Adding a Tag string s "Instantiated" First check if it is not already present bool found false for (int i 0 i lt tagsProp.arraySize i ) SerializedProperty t tagsProp.GetArrayElementAtIndex(i) if (t.stringValue.Equals(s)) found true break if not found, add it if (!found) tagsProp.InsertArrayElementAtIndex(0) SerializedProperty n tagsProp.GetArrayElementAtIndex(0) n.stringValue s Latest Update Error IndexOutOfRangeException Array index is out of range is solved by resolving file location in my original script. I apologized for that. Fixed Added a line in the script to update the properties if (!found) tagsProp.InsertArrayElementAtIndex(0) SerializedProperty n tagsProp.GetArrayElementAtIndex(0) n.stringValue s tagManager.ApplyModifiedPropertiesWithoutUndo()
0
How to make a cell shader like BOTW in Unity? It seems most cell shader tutorials focus on individual shaders for materials, but the effect used in BOTW seems to be more like a filter, that is applied to everything. I've researched multiple examples that have been done in UE4 like here and here but nothing in Unity. How would I apply something like this in Unity?
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
Instantiate two objects at random non overlapping positions I'm making an endless runner game. I have the script that make coins and walls appear at the same time in front of the player. The problem is that sometimes the coin and wall appear in the same place position. How can I ensure that coins and walls do not appear in the same place position? public class Instantiate MonoBehaviour public float betweenSpawn 1.05f public float angle public Vector3 spawnValues Range of appearing public GameObject coinPrefab public GameObject wallPrefab public Transform coinInstantiate public Transform wallInstantiate void Start() InvokeRepeating("Spawn", 0f, betweenSpawn) void Spawn() Vector3 coinPosition new Vector3(Random.Range( spawnValues.x, spawnValues.x), 1, Random.Range( spawnValues.z, spawnValues.z)) Vector3 wallPosition new Vector3(Random.Range( spawnValues.x, spawnValues.x), 1, Random.Range( spawnValues.z, spawnValues.z)) Instantiate(coinPrefab, coinPosition coinInstantiate.TransformPoint(0, 0, 0), Quaternion.AngleAxis(angle, Vector3.forward)) Instantiate(wallPrefab, wallPosition wallInstantiate.TransformPoint(0, 0, 0), Quaternion.AngleAxis(angle, Vector3.forward))
0
Sprite Image in Canvas not displaying correctly (distorted) I have a problem with displaying images in my Canvas, as they're not displaying exactly like the imported image. In the image below, the sprite on the left is how it looks when it's imported. The sprite on the right is how it looks in the canvas. Notice that some of the pixels have incorrect colours, like the lighter pink in the center of the staff's top is gone, the eyeball is a darker shade, some of the colouration under the hood is wrong, and other errors. ( The sprite is just a test I took from somewhere else, not what I intend to use as a final product. ) The project is 3D (going for a 2.5D look with billboard sprites) set to 384x224 resolution, orthographic camera size of 3.5, no anistropic textures, no anti aliasing. Is there some setting I missed somewhere to ensure that images display 100 exact like the source sprite when used in the Canvas? EDIT Sprite in the Inspector (Seems to also not be correct) EDIT Added entire inspector
0
Do I need to be careful about PPU and Camera size and Device Resolution even if I'm not creaing a pixel art 2d game? I was reading this blog post https blogs.unity3d.com 2015 06 19 pixel perfect 2d and was wondering if I need to be super careful about those numbers, although my game's art is not pixel art.
0
How to hide a sprite on trigger when the player enters the trigger zone? I am making a roof for my 2D top down survival game, and I want to make it so that the roof disappears when the player enters the building, and re appears when they leave. Here is the code I've written so far using System.Collections using System.Collections.Generic using UnityEngine public class Roof MonoBehaviour public GameObject roofGameObject void OnTriggerEnter2D(Collider2D collision) roofGameObject.SetActive(false) void OnTriggerExit2D(Collider2D collision) roofGameObject.SetActive(true) I got it to work so that, when I go in, the roof it disappears. But when I leave it stays disappeared. How can I fix that?
0
Recursive method causes an OutOfMemory error If a GameObject in my game has a special ability it triggers it, but I want all the special GameObjects that this GameObject affects to also trigger their abilities, for example if a bomb hits some objects, if these objects are also bombs, trigger them too. I though this would be easy by calling the method that handles all the special abilities recursively, but it wasn't. Basically what happened is a chain reaction of bullcrap that caused Unity to show an OurOfMemory error. Also makes my PC freeze completely while politely turning all the screens off. The question is, how can I make it so it triggers all the affected cubes' special abilities, without everything going nuts? Code Triggers the cube's special ability, if it has any private void TriggerSpecialCubeAbility(GameObject specialCube) switch (specialCube.tag) Destroy all cubes in a radius from the special cube case "Bomb" TriggerBombAbility(specialCube) break Destroy all cubes of the same color as the special cube case "Lighting" TriggerLightingAbility(specialCube) break default break private void TriggerBombAbility(GameObject specialCube) var nearbyColliders Physics2D.OverlapCircleAll(specialCube.transform.position, explosionRadius) Instantiate(particles 0 , specialCube.transform.position, specialCube.transform.rotation) Instantiate(particles 1 , specialCube.transform.position, specialCube.transform.rotation) foreach (var collider in nearbyColliders) if (collider.tag "Indestructible") return var affectedCube collider.gameObject TriggerSpecialCubeAbility(affectedCube) Destroy(affectedCube) destroySelectedCubes true
0
Sticky Conveyor Belt I'm working on having a sticky conveyor belt, so that objects can also go around it. But my objects currently get stuck half way, as seen in the picture. This is the movement code of the conveyor belt. private void HandleCargo() var speed speed Time.deltaTime foreach (var cargo in cargo) var change cargo.Key.transform.right speed cargo.Key.transform.Translate(change) And the code taking care of the rotation to the surface. private void Update() Debug.DrawRay(transform.position, transform.up, Color.black) if (!Physics.Raycast(transform.position, transform.up, out var hit, distance)) return var normal hit.normal transform.up (transform.up hit.normal) 0.05f If someone has pointers as to why this happens, that would be great. I kind of have an idea, since the transform right of the conveyor code is pointing inwards at this angles so the movement doesn't happen around the belt anymore, but I exhausted my attempts to fix it... Edit After DMGregory answer a new issue appeared. As soon as the cube starts to adjust to the spheric surface it is not exactly on the mesh anymore, which triggers my on collision exit code and stops movement on the object. I have some code that is supposed to stick the object to the belt, but that doesn't seem to work? The sticky code private void Update() Debug.DrawRay(transform.position, transform.up, Color.black) if (!Physics.Raycast(transform.position, transform.up, out var hit, distance)) return transform.rotation Quaternion.FromToRotation(transform.up, hit.normal) transform.rotation transform.position new Vector3(transform.position.x, hit.point.y 0.5f, transform.position.z)
0
Is my collision free location script working? I've recently been learning C and I wanted to take one of my 2D tutorials to Unity. I reached a step where I need to spawn my new sprite into a collision free location. I've followed direction generated random location, calculating Vector2s using the location and collider, and then used a while loop to check Physics2D.OverlapArea using my 2 vectors. But, because I'm still only just learning C , I'm finding it difficult to know if I have actually written my code correctly. Is there any simple way of being able to figure this out? Using Debug or something? Vector3 spawnLocation new Vector3 (Random.Range (minSpawnX, maxSpawnX), Random.Range (minSpawnY, maxSpawnY), Camera.main.transform.position.z) Vector3 spawnPoint Camera.main.ScreenToWorldPoint (spawnLocation) Vector2 lowerLeftCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) Vector2 upperRightCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) while (Physics2D.OverlapArea (lowerLeftCorner, upperRightCorner) ! null) spawnPoint.x Random.Range(minSpawnX, maxSpawnX) spawnPoint.y Random.Range(minSpawnY, maxSpawnY) lowerLeftCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) upperRightCorner new Vector2 (spawnPoint.x teddyBearColliderHalfWidth, spawnPoint.y teddyBearColliderHalfHeight) Debug.Log (Physics2D.OverlapArea(lowerLeftCorner, upperRightCorner)) I was trying to use a debug at the end there, but it doesn't seem to continue running every single time that there's a spawn, so I am still unsure if it is working. I'm terribly sorry for my nooby code. Feel free to direct to me some place else if you feel I need to do so.
0
How to create a material with variable color I'm new to Unity and trying to create a Carrom game. Since all the White and Black pieces, Queen basically have the same material and physical properties and texture except for their color, I'm trying to create a single material that I could assign to all 3 types of objects but could then set the material color per object type. Can this be achieved in Unity (I'm using 5.3.2)?
0
OnTriggerEnter2D or OnCollisionEnter2D not getting called I checked the other answers for this but mine didn't get fixed Here's the code using System.Collections using System.Collections.Generic using UnityEngine public class DestroyCollectibles MonoBehaviour private void Start() Debug.Log( quot Hallo quot ) private void OnTriggerEnter2D(Collider2D collision) Debug.Log( quot Trigger quot ) private void OnCollisionEnter2D(Collision2D collision) Debug.Log( quot Collsion quot ) if (collision.gameObject.CompareTag( quot Collectible quot )) Debug.Log( quot Apple quot ) Destroy(collision.gameObject) And screenshots
0
how to make my camera follow script work for Photon Pun2 I m currently working on the Multiplayer part for a 2D top down game. I m using Photon Pun2, to do this. My problem is, that always just the last player, who joined the game get s my camera follow script attached. I ve tried setting an if (!myPV.IsMine) return on top of the function, but it doesn t seem to work. I give you the script here, so it would be nice, if you tell me, where I have to do what, to get 2 (and more) different views of the camera using System.Collections using System.Collections.Generic using UnityEngine public class CameraFollow MonoBehaviour public Transform followTransform Update is called once per frame void FixedUpdate() this.transform.position new Vector3(followTransform.position.x, followTransform.position.y, this.transform.position.z)
0
Unity2D How to destroy my Instantiate particle system I'm having trouble trying to destroy my Instantiated particle system, I can only destroy my gameobject using UnityEngine using System.Collections public class meteor destruction MonoBehaviour public GameObject meteor d effect public GameObject meteor explo effect public GameObject meteor explo2 effect public int pointsIncrement 1 void OnCollisionEnter2D (Collision2D col) var effect explo Instantiate(meteor explo effect, col.gameObject.transform.position, col.transform.rotation) var effect explo2 Instantiate(meteor explo2 effect, col.gameObject.transform.position, col.transform.rotation) var effect d Instantiate(meteor d effect, col.gameObject.transform.position, col.transform.rotation) Destroy (gameObject) Destroy (effect explo,3) Destroy (effect explo2,3) Destroy (effect d,3) It's generated after the meteor collide, but those 3 particle effects keeps adding inside my Hierarchy panel.
0
Knockback when shooting I am currently working on a shooter and I could use some help with this. I want to make my character knock back when he shoots, but also the knock back should be different when the player uses a different weapon. How can I do this?
0
Will my Admob Unity Plugin be Obsolete? When I got back to Google Admob Console I received this announcement "Beginning on 23 Jan 2018, Google Mobile Ads SDK versions older than 7.0.0 for Android and 7.0.0 for iOS will no longer be supported. Publishers with these older versions will not be able to serve ads in their apps(s). Please ensure that you have upgraded to the latest version of the Google Mobile Ads SDK." I am concerned about whether the Unity game I released eight months ago will continue to serve Admob ads. I think this pertains to many Unity developers. It seems that the Google Mobile Ads for Unity uses a different versioning system. Its current version is version v3.10.0. So what is the latest version of Admob Unity Plugin that will be affected by this? Will we be affected at all?
0
Can I keep get out of Unity editor features if I'm using ECS Pattern? I'm learning about ECS Pattern to use it in my Unity game, as I saw until now, most of stuffs is created by code. As I know, each Unity GameObject is a Entity which contains many of Components and GameObjects are instantiated by code (created by my script, for example). My question is, when I use ECS Pattern, can I keep using the bunch of features offered by Unity editor (like Prefabs, ScriptObjects, Drag Dropg to position, etc) or I need to control all of them by code?
0
Unity3d simple material color display correctly in windows built but yellow color turns to blue in android build? I have a simple roll a ball game as shown in unity 3d tutorials, and I have set the wall color as a shade of yellow using the standard shader and material. This runs flawlessly in windows application, however when running in android phone( Nexus 5 MM) the wall turns into a blue color. Can anyone tell me how to fix it?
0
unity and maya how to export import fbx animation with rootmotion and non rootmotion clips? I've started learning about and playing around with animations in Unity and I've installed the Basic Motions Pack by Kevin Iglesias. I wanted to know how they work and to see if I can modify them so I've looked at the animation files which are .fbx. The animation hierarchy in Unity looks like this where BasicMotions Walk01 is the in place animation and RootMotion is the root motion variant which has velocity. I've looked into what root motions are and I think I've grasped what they are, but here's where things have gotten interesting. I've imported the BasicMotions Walk01.fbx into Maya and it looks like this it has a root joint for root motion and the animation moves the rig in each keyframe. So far so good! I've modified the animation so that it plays in reverse, basically made a sketchy reverse walk animation. Exported it to .fbx with the following parameters And then opened that in Unity, however when I import the animation and rig it it only has one clip and it's the Root motion clip, and I can't get the non rootmotion clip. The Root Transform Position (XZ) Loop match is always red and if I don't bake it into pose the animation functions like the Kevin's RootMotion animations, but I don't know how to get the non RootMotion clip. What am I doing wrong here?
0
Can the GUI be used to create game objects? I want to be able to position 10 various game objects (sprites) within the area of the screen which will be dynamically sized accordingly to the screen size of the device. The area in which I want to position the items will be about 70 of the screen. The objects will be rectangles with irregular size (slightly irregular). The object should be positioned randomly (or in grid) within this area but they should not overlap. The objects will be a drop targets for other object which I will drag onto them. To summarize I need The area in which I can place objects. Random object position er. As I have been reading and watching various tutorials I have become very confused about how should I approach this. Should I use a Rect to draw the area on which I will then place the objects, or should I use GUI UI elements i.e. panel? Are the GUI UI elements suitable for achieving this or are they meant to be only used to create games menus not for actual game play?
0
How can I avoid a stack overflow when recursively checking adjacent game objects? I am building a simple game on Unity to learn the system. I am using C . The game is a basic "blocks" game, whereby when the player clicks on a block, the block and its neighbours of the same colour all disappear (get destroyed). My process is this To keep a track of which blocks are neighbours of the same colour, on each refresh each block checks their details on the event OnCollisionEnter and adds these collision neighbours to a List of valid neighbouring gameobjects. When a block is clicked, this list is checked and each neighbour has its own neighbours list checked, after list checking each block is distroyed. Somehow, this process is causing a StackOverflowException StackOverflowException UnityEngine.GameObject.GetComponent setupscript () (at C buildslave unity build artifacts generated common runtime GameObjectBindings.gen.cs 35) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 86) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 87) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 87) setupscript.checkNeighbours () (at Assets scripts setupscript.cs 87) .... Here is my script, first my List establishment private List lt GameObject gt neighbours new List lt GameObject gt () Next, here is how the neighbours list is populated void OnCollisionEnter (Collision other) Rigidbody other rb other.rigidbody if(rb.velocity.magnitude lt 1f amp amp other rb.velocity.magnitude lt 1f amp amp other.gameObject.tag tagName amp amp !neighbours.Contains(other.gameObject)) Same tag so add to list of valid neighbours neighbours.Add(other.gameObject) Now, there are four conditions above to check when adding to the list Is the current block stationary. Is the "other" colliding block stationary (so they're at rest next to each other). do these blocks have the same tag (so they're the same type colour) does this block not already exist in this list. So once all four conditions are met, the block GameObject is added to the List. ( On conditions of OnCollisionExit blocks are removed from the List in a similar fashion. ) Now, my CheckNeighbours() script public void checkNeighbours() if (neighbours.Count gt 0) foreach (GameObject othercube in neighbours) setupscript otherCubeScript othercube.GetComponent lt setupscript gt () otherCubeScript.checkNeighbours() Destroy (gameObject) This should, as far as I understand it, run once through each List element and check that element for any neighbours who match. As I write this question out I think I'm realising that the issue is that we're in a loop as block 1 references neighbour block 2, which references neighbour block 3, which references neighbour block 1, etc. etc. But my StackOverflow exception occurs when there are only two blocks, so one refers to the other, refers to the first, etc. But as they should destroy after running the reference, this shouldn't (ideally) be an issue? Do I need to make the checkNeighbour() a Corountine to allow it to not hold up destroying the GameObject? If this repetition cycling is indeed what's going on, what would be the best way of getting each neighbour to be checked only once? Or checking that the GameObject referenced in the List still exists in the game itself? I have a quick edit here foreach (GameObject othercube in neighbours) if (othercube ! null) setupscript otherCubeScript othercube.GetComponent lt setupscript gt () otherCubeScript.checkNeighbours() But I'm not sure this will work as I feel this List will purely be a reference rather than the actual GameObject in the level?
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
Why is Unity 2D Alpha Blurring my pixel sprite? So I have just brought in a place holder block for the ground in unity 2D, and it's 16 by 16 pixel image, and for some reason unity is automatically blurring the image. So I was wondering if there was any way to stop unity from automatically blurring the image. I would really appreciate if someone could tell me how to stop the image form being blurred. Also sorry if this is, just something that is incredibly simple to fix, I just started using unity 2D instead of 3D so it's different for me. Thanks, Nova
0
unity 5.x performance After I downloaded unity 5, it became very power consuming. For example, my pc becomes hotter and makes a lot of noise. Also building, compiling, baking of game takes a lot of time. I am making a multiplayer game and need to build the game almost on every change, but it takes hours or sometimes it doesn't even build the game. There are also bugs with directional light, it doesn't work. So yeah, any suggestions? My internal PC specs Intel core i3 3130M, 8gb of ram, video card Intel R4000 I installed unity 5 after Windows 10 came out, maybe it's something with the OS? Also yesterday, I updated Unity but with the same problems. Also here are some screens Directional light is turned off but everything except models is dark, i mean terrain is black. Also this baking process is more than one hour and stays on 5 11 clustering 41 jobs
0
Method Animator.SetBool sometimes is not working (or not triggering) in Unity2D I have trouble with Animator in Unity2d. I have a main character for my game. The character has his own animation clip for fighting. When the player touches the screen, i am starting animation. When the player touches the screen slowly (every second) everything is working fine, but when the player touches the screen fast, the animation clip is playing about 10 times, and then nothing happens (the clip isn't playing). I've checked the touch event is triggered normaly, may the problem is with animator. Does anyone have ideas how to fix this issue? public bool UseAxisInput false private Animator Anim Use this for initialization void Start () Anim GetComponent lt Animator gt () Update is called once per frame void Update () for (var i 0 i lt Input.touchCount i) if (Input.GetTouch(i).phase TouchPhase.Began) Anim.SetBool("IsFighting", true) May be this is because of that at the end of my animation i have an animation event which calls the method, that stops animation. This is my method, that is called, after the animation ends public void stopFighting() Anim.SetBool("IsFighting", false)
0
Why every character I drag to timeline is disabled in the timeline? I dragged 3 different characters to the timeline window and each one asked for track so I did animation track for all of them but on each track on the left side there is a yellow triangle say "The component is disabled" I created cinemachine virtual camera and it added the brain component to the main camera and created a timeline automatic for the virtual camera but when dragging a character to the timeline window I'm getting this yellow triangle with the message it's disabled. You can see in the screenshot on the left side in the timeline window the yellow triangles with the message.
0
Inventory View Screen Looking to create an inventory screen in Unity, and trying to think of the best way to do it. My current line of thinking is having a few rows of squares for inventory items that are drag and droppable onto a paperdoll, a la Diablo. When dragging and dropping on the items, it would update a 3D model of your current playable object with the items. The menu itself would be easy enough to do with a simple square and a hierarchy of game objects for the items, each responding to mouse hovering over. The problem I am trying to figure out is being able to render the 3D model on the side. Granted, this is a nice to have, and not necessarily a need, but browsing the documentation, the only way I can think of accomplishing this is using a render to texture which requires Unity Pro with a separate camera completely out of bounds of the current space. Anyone have suggestions on how to accomplish this?
0
How to fix this elbow issue when converting to humanoid Good day, how can I fix this? it looks fine in Blender and generic but not when I switch to humanoid. There is no error on rig tab but there are in animation tab under the import message that say quot is in between humanoid transforms and has rotation animation that will be discarded quot and I can't seem to fix it. Here are the things I've tried so far Put the right bones to the right slots. Enforce T pose. Translation DoF. Clicked Generate Retargeting and applied it.
0
Backround turning, follow the character In my Unity2d platformer, I need background to follow the character, so I just attach it. And when character turn left from right (or right to left), background turn too. How can I make my background constant?
0
How to change animation start end proprieties via script? Is there a way of changing the start end proprieties (Transform, Rect Transform, etc..) of an animation via script? Like, I have 5 objects that start at the same position but should end in different positions, so I would like to change the end positions of each one via script. As I haven't found a way to do this, I created 5 animations for this, but I'd like to just have one animation and change its proprieties in runtime.
0
How to add a bolt into my unity project In my game, one of the character you pick as a special ability called the dash. It allows the player to quickly move forward. Included below is the code. It just throws up a bunch of errors. This is a 3d scene using System.Collections using System.Collections.Generic using UnityEngine public class PlayerJump MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKeyDown("q")) transform.Translate(Vector3.KeyDirection 260 Time.deltaTime, Space.World)
0
Converting to JSON String with JsonUtility.ToJson I am working on converting and displaying the JSON String with unity. I have done coding for it using UnityEngine using System.Collections using LitJson using SimpleJSON using System.IO public class TestDelete MonoBehaviour JsonData json void Start() Data2 data new Data2() Payload2 data2 new Payload2() data.command "state" data.payload new Payload2() text "wwwwwww", image "hello" data2.option new Option () A1 "k", A2 "J" string dataValue data data2.ToString() string json JsonUtility.ToJson(data,true) P(json " t n") Use this for initialization void P(string aText) print (aText " n") System.Serializable public class Payload2 public string text public string image public Option option System.Serializable public class Data2 public string command public Payload2 payload System.Serializable public class Option public string A1 public string A2 This code of working fine.But with the output Iam having problem.The out is displayed as follow "command" "state", "payload" "text" "wwwwwww", "image" "hello", "option" "A1" "", not getting displayed "A2" "" not getting displayed the string value A1 and A2 is not getting displayed.What will be the issue with my code.Can anybody help me sorting out this issues
0
How to implement the graph for pathfinding using A The game I am working on is based on a maze where each level is procedurally generated. The pathfinding grid is a 2D array where each node holds its connections. Path requests are handled one at a time so there can't be two path calculations going on simultaneously. So far I have each node hold its data required for the A (H,F,G scores and its parent) and manipulate them directly in the algorithm. Since the nodes are the actual nodes and not copies of them, every time the algorithm runs the data changes permanently and I have to manually set them on default values before the next run. So my questions are 1) Is this a valid way of handling pathfinding in a game? 2) What other data manipulation techniques I could use in order to avoid that? If you need a copy of the code it's all on my github under Pathfinding and Managers PathfindingManager.
0
Can both High poly model go with a low poly scene? I'm in the process of developing a game, and I've found a model that would go perfectly for the character. However, the scentre I already have is low poly and I can't find a good enough high poly to go with it. So tell me whether or not I should I should carry on with the art I have or find a low poly model.
0
How to remove gameobjects that have the same transform position as each other? If I have 4 copies of the same gameobject in my scene and they all have the exact same transform position as each other, how can I remove the 3 duplicates so that only one unique gameobject remains? This is what I tried so far... private void Update() if (Input.GetKeyDown(KeyCode.Space)) RemoveDuplicate(GameObject.FindGameObjectsWithTag("Path")) private void RemoveDuplicate(GameObject other) for (int i 0 i lt GameObject.FindGameObjectsWithTag("Path").Length i ) if (GameObject.FindGameObjectsWithTag("Path") i other i ) continue if (GameObject.FindGameObjectsWithTag("Path") i .transform.position other i .transform.position) Destroy(other i ) But it doesn't work at all. Any ideas?
0
I can't find a way to make my projectile gameobject collide with my ofscreen collider so my code on my collider is as followed public class Collide MonoBehaviour private void OnCollisionEnter2D(Collision2D collision) Debug.Log("Collision") the projectile has a rigidbody2D and a capsule Collider 2D. collider has a box collider 2D. the projectile spawns from my player and moves upwards in the direction of the collider (the collider is large enough that the projectile cant miss it). the projectile however goes straight through the collider and no message appears and I have no idea why. what I've tried and made sure of both are on the same layer and plane(z axis) gave the collider a rigidbody but changed nothing made the collider on trigger and not on trigger made the projectile dynamic and kinematic changed collider script to onCollisionEnter and onCollisionEnter2D
0
Minimum hardware requirements for developing for iOS and Android with Unity, Cocos2d x and GameSalad on a Mac I intend to create iOS and Android games. My main priority is to create 2D games. The software that I m planing to use are Unity, Cocos2d x and GameSalad. I am a bit interest in the Mac Mini, because it is cheap compared to other Apple machines. What are the minimum hardware requirements for an Apple machine?
0
I want a variable field to only be declared when a specific condition is true. I used Compiler Directives. Is the code I wrote valid? I want a field I declared (float attackRange) to be only declared when inheriting class set "bool haveLongRangeAttack" is set to true. I wanted to use Compiler Directives for this purpose. Here is the code I wrote using UnityEngine public abstract class Enemy lt T gt MonoBehaviour where T Enemy lt T gt SerializeField protected bool haveCloseRangeAttack false, haveLongRangeAttack false if haveLongRangeAttack true SerializeField protected float attackRange 1f endif SerializeField protected GameObject mainCharacter null protected GameObject enemy null protected virtual void ChasePlayer() if(haveCloseRangeAttack) ... else if(haveLongRangeAttack) ... I don't know if it is right way to of do what I want or using Compiler Directives so please review my code and tell me if there is a problem, or if there is a better way. It was before 6 months when I started writing code, and C was my first language. I am trying to learn new things concepts and writing at my own style. So there will be another way (maybe more efficient) if there is one, please teach me. I'm working on my own Game Project right now, I'm open to learn new things that will benefit me... TY for taking time . ! PS There is no compiler directives tag in Tags section. Maybe it will be useful to add this tag.
0
Still having problems using Json data in Unity I have the following classes and json file, i thought id followed the documentation exactly but I am clearly wrong. Can anyone see why I get an error just saying INVALID VALUE in my unity console using System.Collections using System.Collections.Generic using UnityEngine using System Serializable public class DataReader public float x public float y public float z GameController public class GameController MonoBehaviour public static GameController instance DataReader dataReader private string gameDataFileName "level1.json" private void Awake() dataReader JsonUtility.FromJson lt DataReader gt (gameDataFileName) instance this void Start () create level print("DATA " dataReader.x 0 ) and the json is stored in StreamingAssets folder (I also tried a copy in Resources folder) "x" 1 , 1 , 1 , 1 , "y" 1 , 1 , 1 , 1 , "z" 1 , 2 , 3 , 4
0
Canvas UI elements out of place in Unity3d I placed all elements in the places I want to show in the Game mode, nevertheless, when I go to Game Mode they are shown in the wrong place as it was shown in the pictures (they go to the center). I tried different modes of render mode but no one seems to work in this case. I want the elements to be fixed in the window no matter monitor size.
0
Instantiated prefabs dont trigger ontriggerEnter while prefabs created not on runtime, do I am new to unity and trying to make a bouble trouble game. I have enemy prefabs with BoxCollider with is triggered checked. I also have a shooting script. when I am trying to instantiate the enemy prefabs on runtime, they dont seem to trigger the OnTriggerEnter function, but if I am placing an Enemy prefab not ingame, it does trigger the funtion. I have no idea why. The on run time instantiate public class CreateBalls MonoBehaviour public Rigidbody prefab public Transform position1 void Awake() for (int i 0 i lt 1 i ) float random Random.Range( 45.08f, 44.41f) Vector3 vec new Vector3(random, position1.position.y, position1.position.z) Rigidbody ball Instantiate(prefab, vec, position1.rotation) as Rigidbody The funtion not being called public class DestroyBalls MonoBehaviour public Rigidbody potion public Transform posToSpawn private void OnTriggerEnter(Collider other) if (this.gameObject.tag quot Enemy quot amp amp other.gameObject.tag quot Bullet quot ) a code not relevent Any idea of why the funtion isnt being called? the bullets are tagged quot Bullet quot and the Enemies are tagged quot Enemy quot Update The funtion is triggered when colliding with another Enemy tagged, but not being trigged after collision with anyother tagged object Also, I have another component on the Enemy Prefab, which also instantiates enemies on run time and these trigger the function perfectly fine. very wierd. the code public Rigidbody ballToSpawn public Transform spawnPoint private void OnTriggerEnter(Collider other) if (this.gameObject.tag quot Enemy quot amp amp other.gameObject.tag quot Bullet quot ) if (this.gameObject.GetComponent lt Size gt ().size gt 1) Rigidbody small for (int i 0,y 1 i lt 2 i ,y 2) Vector3 vec new Vector3(spawnPoint.position.x y, spawnPoint.position.y, spawnPoint.position.z) small Instantiate(ballToSpawn, vec, spawnPoint.rotation) as Rigidbody small.gameObject.transform.localScale new Vector3(1, 1, 0) small.gameObject.GetComponent lt AutoMoveForBall gt ().GoToX this.gameObject.GetComponent lt AutoMoveForBall gt ().GoToX small.gameObject.GetComponent lt AutoMoveForBall gt ().GoToY this.gameObject.GetComponent lt AutoMoveForBall gt ().GoToY small.gameObject.GetComponent lt Size gt ().size this.gameObject.GetComponent lt Size gt ().size 1
0
How to know if mouse coordinates is delta or absolute on Window and Android in Unity? I wrote sample application, that allows to "rotate" object by mouse. Rotation occured by rotating of camera object around central object and the code is following float mouseX Input.GetAxis("Mouse X") float mouseY Input.GetAxis("Mouse Y") float magnitude transform.position.magnitude Vector3 mouseSwipe new Vector3(mouseX, mouseY, 0) Vector3 startPoint new Vector3((float)camera.pixelWidth 2, (float)camera.pixelHeight 2, magnitude 1) Vector3 startPointWorld camera.ScreenToViewportPoint(startPoint) Vector3 endPointWord camera.ScreenToViewportPoint(startPoint mouseSwipe) Vector3 mouseSwipeWord endPointWord startPointWorld float dragLat mouseSwipeWord.y float dragLng mouseSwipeWord.x Vector3 oldPosition transform.position magnitude float lat Mathf.Asin(oldPosition.y) float rsmall Mathf.Acos(oldPosition.y) float lng Mathf.Atan2(oldPosition.z rsmall, oldPosition.x rsmall) lat dragLat 10 2 Mathf.PI if( lat 180 Mathf.PI gt 80 ) lat 80 Mathf.PI 180 else if( lat 180 Mathf.PI lt 80) lat 80 Mathf.PI 180 lng dragLng 10 2 Mathf.PI 2 float y Mathf.Sin(lat) rsmall Mathf.Cos(lat) float x rsmall Mathf.Cos(lng) float z rsmall Mathf.Sin(lng) Vector3 newPosition new Vector3(x, y, z) newPosition magnitude transform.position newPosition LookAtTarget() The code assumes that mouse returns delta value on each swipe and this works well on Windows. For example, if I do several separate swipes, I can gradually rotate object for full circle. Unfortunately, when I run this on Android, it doesn't happen. Each swipe object restarts from some position, depending on swipe point. I.e. on Android, swipes return in absolute value. Is it possible to know, whether swipes retunrs delta or absolute values and how? Is it possible to claim compatible return units?
0
How can shader code duplication be reduced in Unity? In our current Unity project we have a few shaders that are basically just supersets of another shader. For example, we have a shader that performs lighting calculates with diffuse, normal, specular, and gloss maps, and a shader that performs lighting calculations with a diffuse, normal, specular, gloss, and glow map. The first is a subset of the second, but for performance reasons we've decided to separate them. This leaves us with heaps of duplicated code. On top of this, I need to add stencil buffer operations to some of these materials, which is about 3 lines, but from what I can see, requires the entire shader file to be copied again. How can we reduce this code duplication? In an object orientated language we'd used inheritence and polymorphism. What can we do here?
0
Fill all unallocated space with texture I have a system of bunkers underground, and I need to fill all the free space where there are no buildings with earth. Yes, I can manually add a ground texture to the plane, but I have procedural level generation. I thought there might be some kind of filter on the camera that I don't know about. Or maybe there are some other solutions?
0
In Unity, why does my IndexOutOfRange exception disappear when trying to debug it? I don't get errors when playing from Unity "Game" tab. But when I build an executable (development or not) it stucks. I get "IndexOutOfRange" exception. Which also magically disappears (yes) when I add some debug lines This does not work for (int i x1 i lt x2 i ) for (int j y1 j lt y2 j ) int a, b a 7 i Out of range b 7 j Out of range submap a, b world.WalkableMap (int)CurrentWalkableTile.x i, (int)CurrentWalkableTile.y j This works for (int i x1 i lt x2 i ) for (int j y1 j lt y2 j ) int a, b a 7 i b 7 j if (a lt 0 a gt 15) now with this never gets out of range Debug.Log("A out of range " a) if (b lt 0 b gt 15) now with this never gets out of range Debug.Log("B out of range " b) submap a, b world.WalkableMap (int)CurrentWalkableTile.x i, (int)CurrentWalkableTile.y j I can't find any sense. The exception literally hides from me Additional info maybe is useful x1 (CurrentWalkableTile.x 7) gt 0 ? 7 (int)CurrentWalkableTile.x x2 (CurrentWalkableTile.x 7) lt world.wmap x size ? 7 (world.wmap x size (int)CurrentWalkableTile.x 1) y1 (CurrentWalkableTile.y 7) gt 0 ? 7 (int)CurrentWalkableTile.y y2 (CurrentWalkableTile.y 7) lt world.wmap y size ? 7 (world.wmap y size (int)CurrentWalkableTile.y 1) I'd like to post more information, but I can't even debug to find the problem.
0
Prevent counterclockwise rotation So I have an object that has a handle attached to it, the player is supposed to rotate this handle. For that, I'm taking in the horizontal and vertical axis of a controllers analogue stick and transform these values into degrees, which I then use to rotate the object. The problem is that I can't seem to completely block out the possibility of rotating the handle counterclockwise, as the player is only supposed to rotate it clockwise. What happens is that every couple of frames while I try rotating counterclockwise it detects a clockwise rotation, executing my according code, even though I was rotating counterclockwise consistently. The principles I use to determine which direction the rotation is going is done by comparing the input angle of the last frame to the current input angle, like Variant 1 var inputAngle Mathf.Atan2(x, y) Mathf.Rad2Deg float angleDifference inputAngle previousAngle if (angleDifference gt 180f) angleDifference 360f if (angleDifference lt 180f) angleDifference 360f if (Mathf.Sign(angleDifference).Equals( 1)) Counterclockwise rotation else Clockwise rotation ... previousAngle inputAngle In another attempt, I tried to do this comparison by simply checking if my current angle is larger than my previous one while having the input transformed in a 0 to 360 range and also handling the overflow from going back to 0 from 360 , which did not work consistently either. So I tried to see what the values are giving in this faulty case, but what this told me was simply that the values are not as I expected them to be, as the current angle should be smaller than the previous one while rotating counterclockwise, in those cases and I can't figure out why or how to prevent it? So I guess in the end my question would be how can I consistently prevent a player from rotating counterclockwise by reading a controller's analogue stick input.
0
How to add a bolt into my unity project In my game, one of the character you pick as a special ability called the dash. It allows the player to quickly move forward. Included below is the code. It just throws up a bunch of errors. This is a 3d scene using System.Collections using System.Collections.Generic using UnityEngine public class PlayerJump MonoBehaviour Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKeyDown("q")) transform.Translate(Vector3.KeyDirection 260 Time.deltaTime, Space.World)
0
How to output to the Oculus and a 2D screen? We'd like to present an Oculus game to a large group of people. Not everyone will have an Oculus headset, so we'd like to output to both the Oculus and a second display. The problem is that the project uses an Oculus plugin to render its output, so all they output is two distorted circles, which doesn't display well when not wearing the Oculus headset. I thought of making a second Unity client (the "audience" client, running on the same computer as the Oculus application) that receives the output texture of an "audience" camera from the client running the Oculus version. My question is Can I use the network to send the output of a camera to the "audience" client so I can set it up for the second display, bypassing the Oculus plugin? How would I get the input on the "audience" client to map it to the screen?
0
How can I switch between cinemachine free look cameras by script? using System.Collections using System.Collections.Generic using UnityEngine using Cinemachine public class CamerasManager MonoBehaviour public CinemachineFreeLook freeLookCameras public float timeBeforeSwitching Start is called before the first frame update void Start() StartCoroutine(SwitchCameras(timeBeforeSwitching)) Update is called once per frame void Update() IEnumerator SwitchCameras(float TimeBeforeSwitching) yield return new WaitForSeconds(TimeBeforeSwitching) for(int i 0 i lt freeLookCameras.Length i ) freeLookCameras i .en If I have two or more cameras I want that after X seconds start switching between all the cameras in the array by disabling enable the cameras. disable the first enable the second then disable the second enable the third and so on.
0
C Script file is not showing in Onclick Event in Unity 5.0.4f1? I uploaded the levelLoader file to the gameobject. Still, when I drag the script file onClick Event, the no function is null. Why? Can anybody help me? C code using UnityEngine using System.Collections public class LevelLoader MonoBehaviour Use this for initialization void Start () Update is called once per frame public void LoadLevel(int a) Application.LoadLevel(a) public void Quit() Application.Quit() Correct me where I am wrong. I am following this racing car game tutorial. At 7 58 he added this event. Please help me!!!
0
Unity installed version higher than game project version can't open the game project anymore Long story short I had to uninstall Unity and Unity Hub and reinstall them again. I ended up installing Unity version 2020.2.1f1. Some of my game projects were made using version 2020.1.6f1 Now I cannot open them there is a yellow warning triangle next to those games in Unity Hub. I am installing version 2020.1.17f1 as I type these. So my questions Is there no backwards compatibility between newer versions of Unity and older games? How do people deal with this? I've heard people transition their games during development into newer versions of Unity but I wasn't even able to open the games made with older version. How would I go around this if I had spent 2 years or more of development time and was suddenly locked out from my game project how do I prevent situations like these? Here are my Unity versions installed And here are my games (tutorials mostly) I may have answered my own question, but still need your input guys. I just noticed that there is a 'Select Version' dropdown on the right that allows me to open a game project in Unity version I have installed on my system. Is this how you deal with those issues?
0
How heavy is a scene load in Unity assuming all referenced objects are in memory? From what I understand, resources that are local to a particular scene( not a prefab, or texture, material asset etc ) are embedded in the scene file itself, while external resources are just referenced and loaded if needed. The game I'm working on requires all scene be loaded from an asset bundle. Which means by the time the level is loaded, all data should be in memory. In order to show relatively accurate load progress, I sum of the total bytes of all the needed asset bundles to load the level and divide that by the (approximate) number of bytes loaded so far( calculated using the file size of the asset bundle in bytes multiplied by Unity's AssetBundleRequest.progress value ). However, this isn't possible with Application.LoadLevel since there's no way to weigh how long it might take relative to the time it took to load the asset bundles. So, my question is, does Application.LoadLevel take long enough to be an issue if ignored? The presence of an async version of this method leads me to believe there is some need for this. That might only apply for scenes that were built into the game rather than into an asset bundle though.
0
Any problems with flipping a sprite by scale? (2d Platformer) I am wondering if there are any problems with flipping a sprite on the x axis using vector2 to tell which direction it is facing flip. Though doing this helps me write less code for Ray cast direction and creating single states with a single animation (using 1 animation player facing right than using 2 animation facing left and right). If there is a better solution please tell me and thanks. Btw I am still pretty new and learning.
0
Rotation around arbitrary vector (using quaternions?) I currently have a camera which orbits a specific target object, always looking at it. The user can drag the mouse to move the camera left right up down and the camera will move over the surface of a sphere of fixed radius (note, I clamp the vertical angle to 89 ). Currently it looks something like this... Store position of camera for future reference private Vector2 rotation new Vector2(120, 25) Was intended to be the vector from planet to target. Only works with up private rotationalPole Vector3.up if (isDragging) rotation new Vector2( Input.GetAxis( quot Mouse X quot ) xSpeed radius 0.02f, Input.GetAxis( quot Mouse Y quot ) ySpeed 0.02f) target is the GameObject to center on... var pos target.transform.position camObj.transform.position pos (Vector3.back actualRadius) camObj.transform.LookAt(pos, rotationalPole) camObj.transform.RotateAround(pos, Vector3.right, rotation.y) camObj.transform.RotateAround(pos, rotationalPole, rotation.x) This works fine when up is in the y direction. Now, however, instead of an object on the ground, the target is something in orbit around a planet (currently on an equatorial orbit but hopefully on an arbitrary one in future). I want the camera to behave the same as before, but with up being the vector from the center of the planet through the target. Nominally forward will be the direction of orbit (but since the user can spin through 360 quot horizontally quot , that's less important). Currently it looks like this... Basically, I'd like to rotate the image above counter clockwise by 90 (which I believe I can do by playing with the camera transform's up and right vectors) but also that my arbitrary rotation honors the new orientation. Some research shows that I need to use quaternions but while my mental model for basic trig is fine, I can't picture how to use quaternions correctly in this situation. Following on from Jon's answer below... I've now got the following. var planetToTarget (target.transform.position planet.transform.position).normalized quot Reset quot the camera before I do any transforms this.transform.position target.transform.position tgtMovement actualRadius this.transform.up Vector3.up this.transform.LookAt(target.transform.position) var camToTarget (transform.position target.transform.position).normalized Debug.Log(string.Format( quot targetMotion 0 , planetToTarget 1 , camToTarget 2 quot , tgtMovement, planetToTarget, camToTarget)) Line that's not working... this.transform.Rotate(camToTarget, 90) To be added in when the above is working... this.transform.Rotate(Vector3.Cross(camToTarget, planetToTarget), rotation.y) this.transform.Rotate(planetToTarget, rotation.x) this.transform.up planetToTarget The uncommented code (excluding the last line) keeps the camera behind the target, looking forward... Initially, I get targetMotion (0.0, 0.0, 1.0), planetToTarget ( 1.0, 0.0, 0.0), camToTarget (0.0, 0.0, 1.0) Which generates However, as the target moves around the planet, it changes to targetMotion (0.4, 0.0, 0.9), planetToTarget ( 0.9, 0.0, 0.4), camToTarget ( 0.4, 0.0, 0.9) By which point, the camera is slewing to the side... So I'm clearly still missing something. I don't appear to be rotating around camToTarget correctly?
0
Way to check overlaps of a collider2d that's not set to "is trigger" in Unity I have a system where physics2d objects are spawned and I need to know when they spawn outside of a region defined by a box collider set to quot is Trigger quot . Using onTriggerEnter and onTriggerExit to know if an object exits re enters the bounds (with some other conditions determining whether to kill the object when it exits the bounds). That stuff works fine. However I can't detect when an object spawns outside of the collider (which I want to allow, but just know when it happens). I tried the following in the Start method of the spawned object List lt Collider2D gt results new List lt Collider2D gt () boundsCollider.OverlapCollider(new ContactFilter2D(), results) bool spawned outside !results.Contains( thisCollider) However at the time that method runs, the booundsCollider doesn't register it. Subsequent frames it will, but that's too late. OverlapCollder can't be run on the collider for the spawned object since it isn't set as a trigger. Is there any way I can query the spawned object's own collider to determine if it is in contact with the bounds collider? Thanks! PS I can't trivially just reference the coords of the object and check if they're out of bounds because the bounds collider will move, and I want to know with precision wether just a corner is overlapping or whatever so I'd need something that amounts to my own simple collision system
0
OnCollisionEnter2D just flat out not running for certain objects I am working with the Unity3D Engine in 2D mode. Currently I am trying to make a circle collider bounce off of a composite collider for the walls of my game. The only issue is that for some reason the OnCollisionEnter2D function does not seem to even trigger when the circle collider hits the walls. I have used the log to determine this. I am curious as to why it has this behviour, since it does end up triggering when the player contacts the circle collider? Here is the important parts of the script public class sword MonoBehaviour public Rigidbody2D rb public CircleCollider2D coll public float speed public Vector2 trajectory public GameObject Player Use this for initialization void Start () speed 0.0f anim Player.GetComponent lt Animator gt () private void OnCollisionEnter2D(Collision2D collision) Debug.Log("collided") if (collision.gameObject.tag "player") transform.position new Vector2( 1000, 1000) Player.GetComponent lt movement gt ().equipped true if (collision.gameObject.tag "solid") ContactPoint2D otherObject collision.contacts 0 Vector2 hit otherObject.point Vector2 normal otherObject.normal trajectory Vector2.Reflect(trajectory, normal) private void FixedUpdate() constantly calculating new velocity rb.velocity speed trajectory speed speed 0.93f drag if (speed lt 0.0001f) speed 0.0f if (speed gt 1) Physics2D.IgnoreCollision(Player.GetComponent lt CircleCollider2D gt (), coll, true) else Physics2D.IgnoreCollision(Player.GetComponent lt CircleCollider2D gt (), coll, false) More Details My speed variable is set from a separate script, in case you are wondering. Everything is on the layer 0.. The Rigidbody for player is dynamic, for the ball it is kinematic, and for the walls it is static. Also here is an image of what the game screen would look like, I've labelled the walls and the circle collider (used for a sword). Thank you.
0
Restarting a level but with more time? So I'm trying to add a "Rewarded video ad" with the reward being more time to play in the next game. my RewardedAd.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Advertisements using UnityEngine.SceneManagement public class RewardedAd MonoBehaviour public static RewardedAd singleton private void Awake() if (singleton null) singleton this else if (singleton ! this) Destroy(gameObject) public void ShowRewardedAd() if (Advertisement.IsReady("rewardedVideo")) var options new ShowOptions resultCallback HandleShowResult Advertisement.Show("rewardedVideo", options) private void HandleShowResult(ShowResult result) switch (result) case ShowResult.Finished Debug.Log("The ad was successfully shown.") StartCoroutine(NewGameWithTime()) break case ShowResult.Skipped Debug.Log("The ad was skipped before reaching the end.") SceneManager.LoadScene(0) break case ShowResult.Failed Debug.LogError("The ad failed to be shown.") SceneManager.LoadScene(0) break IEnumerator NewGameWithTime() Debug.Log("NewGame Started") GameOverManager.singleton.GameOverAfterRewardAd() SceneManager.LoadScene(1) Timer.singleton.AddBonusTime(20) Debug.Log("NewGame Ended") yield return new WaitForSeconds(1) and my Timer.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement using UnityEngine.UI using System public class Timer MonoBehaviour public static Timer singleton public Text timeTF private float seconds 10f private void Awake() if (singleton null) singleton this else if (singleton ! this) Destroy(gameObject) private void Update() if (seconds gt 0f) seconds Time.deltaTime TimeSpan timeSpan TimeSpan.FromSeconds(seconds) string timeLeft string.Format(" 0 D2 ",timeSpan.Seconds) timeTF.text timeLeft TimeLeftCheck(seconds) public void AddBonusTime(float bonusTime) seconds bonusTime Debug.Log("New Timer script ") Debug.Log(seconds) private void TimeLeftCheck(float time) if ( time lt 5) Debug.Log("RunningOutTime sound") SoundManager.singleton.Sound RunningOutofTime() if ( time lt 2) Debug.Log("Out of Time sound") SoundManager.singleton.Sound OutofTime() if ( time lt 1) Debug.Log("Game Over") GameOverManager.singleton.GameOver() The video ad is playing fine and it's resetting my ad counter in my game over manager but I can't seem to figure out how to start the next game with more time (20 seconds to so) but ONLY if they've watched the ad. Also, I'm still learning so any suggestions or things I can improve, more than happy to take that criticism too!
0
Managing Character Bones in Unity 3D at runtime I'm trying to do the following Have a rotation only (no transforms) with x,y,z. Each rotation axis above respectfully having a minimal and maximum rotation angle with a current angle. This will be for each bone of said character's skeleton, note the weights will be applied as per usual when doing animations, however there will be no animation data. bones to rotation info, apply changes, info back to bones, apply changes, info back to bones... Q SetBones And GetBones, how would I get and set the bone data? imports... public class BoneControllerClass MonoBehaviour used to modify the bone data struct for each bone (ediable via Unity Editor) public BoneConstraintData BoneData gets refs to bone data from character public Bones GetBones() ..Help..Here.. public BoneConstraintData SetBoneConstraints(BoneConstraintData BoneData) ..CODE..HERE.. public void SetBones(BoneConstraintData BoneData) ..Help..Here.. public void Start() generate bone data with zeros BoneData GetBones() set bone data constraints BoneData SetBoneConstraints(BoneData) public void Update() do something for smooth clamping, optionally this could be applied above as with Delta Time... CODE EXAMPLE HERE, optionally another function can be added... BoneData 0 .currentXAngle 12.0f Time.DeltaTime or BoneDataNew 0 .currentXAngle 12.0f END CODE EXAMPLE HERE applies new bone rotation information, (note each bone carries the bone information of rotation like in IK Bone Logic...) SetBones(BoneData) holds Min, Max, Current Angles And Bone Ref. public class BoneConstraintData string bone name float minXAngle, maxXAngle, currentXAngle float minYAngle, maxYAngle, currentYAngle float minZAngle, maxZAngle, currentZAngle I'm using version 5.x.x of Unity 3D.
0
Can I always assume that fixed time step in Unity is reliable? I was thinking about games on low end machines or phones where the CPU would be limited. If I were to move all of my game logic into FixedUpdate() can I assume that it will always be called with the same time delta? Or would it still be worth adding code to make it take the actual time delta into account?
0
How to draw an arc between two angles? I'd like to draw an arc between two specific angles. For example, "draw an angle between 0 and 90 degrees" and it will draw only that part of the circle and ignore the rest.
0
How do I configure a joint for a sliding door in Unity? I have this sliding door where i want to use a joint to limit its motion ...but I am confused about how to configure a joint to provide this sliding motion. I've found the Hinge Joint component, but the comments below say this is for rotating motion. What kind of joint do I use to create a sliding motion?
0
Unity wall jump issue I've got a very annoying problem that I have been stuck on for a few days and I can't figure it out. It is for a wall jump. I basically want my wall jump to have a bit of force away from to wall to make it look and feel better than just jumping up straight. The problem is, when i add a force on the x axis, it does not register when i am also holding the arrow towards the wall. If I am not holding down the walking button, then press jump...then the x force works. I have a feeling that the horizontal axis force is competing with the opposite force that i want to add to the player when he hits the jump button... Walking code private void ApplyMovement() if (isGrounded) myRigidbody.velocity new Vector2(movementSpeed movementInputDirection, myRigidbody.velocity.y) else if (!isGrounded amp amp !isWallSliding amp amp movementInputDirection ! 0) Vector2 forceToAdd new Vector2(movementForceInAir movementInputDirection, 0) myRigidbody.AddForce(forceToAdd) if (Mathf.Abs(myRigidbody.velocity.x) gt movementSpeed) myRigidbody.velocity new Vector2(movementSpeed movementInputDirection, myRigidbody.velocity.y) else if (!isGrounded amp amp !isWallSliding amp amp movementInputDirection 0) myRigidbody.velocity new Vector2(myRigidbody.velocity.x airDragMultiplier, myRigidbody.velocity.y) if (isWallSliding) if (myRigidbody.velocity.y lt wallSlideSpeed) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, wallSlideSpeed) Jump code private void Jump() if (canJump amp amp !isWallSliding) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, jumpForce) numberOfJumpsLeft else if ((isWallSliding isTouchingWall) amp amp !isGrounded amp amp canJump) isWallSliding false numberOfJumpsLeft Vector2 forceToAdd new Vector2(wallPushForce facingDirection, wallJumpForce wallJumpDirection.y) myRigidbody.AddForce(forceToAdd, ForceMode2D.Impulse) Where I call The code void Update() CheckInput() private void FixedUpdate() ApplyMovement() private void CheckInput() movementInputDirection CrossPlatformInputManager.GetAxisRaw("Horizontal") if (Input.GetButtonDown("Jump")) Jump() if (Input.GetButtonUp("Jump")) myRigidbody.velocity new Vector2(myRigidbody.velocity.x, myRigidbody.velocity.y variableJumpHeightMultiplier) Any help would be much appreciated. Thanks in advance
0
How can I provide a csv file to a player on mobile? It seems many people do this with regards to game data so they recommend userprefs, but I just want the user to have the file in the end, whether this is the Files app on iOS or choosing a folder to save in on Android or even just attaching the file as an attachment to an email that they can send using their preferred mail app or something.
0
Stop animation from playing while waiting to destroy object I'm working on functionality in Unity where if a game object's health is zero, it does and the object is destroyed. This works fine as is, I reduce the health to zero, the die animation plays and the game object is destroyed. I want to have the script wait a certain amount of time and then run the destroy method. I thought using WaitForSeconds() would do the trick, and technically, it does, but the death animation continues to play until the object is destroyed. My question is, how do I get the animation to stop playing as the script waits to destroy the object? C void Die() GetComponent lt Animation gt ().CrossFade(die.name) If the current animation time is greater than 90 of the entire animation length, destroy the object. if(GetComponent lt Animation gt () die.name .time gt GetComponent lt Animation gt () die.name .length 0.9) StartCoroutine(RemoveBody()) IEnumerator RemoveBody() yield return new WaitForSeconds(5) Destroy(gameObject)
0
Unity Round(Circle) Buttons I have been using unity and C scripting now for the past 2 or 3 weeks. So yeah i am very new to unity and C . I wanted to know if there is a way to make a round(circle) button without using the rect. The problem I have now, I am using a 2d sprite to make the button appear round, however when you hover or click with in the rect, it still works. I saw this asset in the asset store called Alpha Raycaster Check asset out Alpha Raycaster on Unity Asset Store I cannot afford to pay for it right now so I was wondering if there is a free alternative to the Alpha Raycaster for now. Dose anyone know how we can solve this issue? I obviously only want the button to function when the user hovers or clicks within the sprite and NOT on the alpha surrounding the sprite.
0
Sprite disappears after adding a material to it I have background which is FirsLayer, order in layer 0 and platform over it which is FirstLayer, order in layer 1. Once I add a material to the platform, the layer doesn't seem to change but it gets rendered behind the background. The material that I add 1)Why do I get such results? 2) How can I add the material to the platform and still keep it above the background? P.S. For further clarification if somebody didn't understand, I expected the sprite to stay on its original position(i.e. not to go behind the background when a material is being added to it)
0
How to make an object jump an equal height whenever it hits the ground? So, I want to make an object jump an equal height whenever it touches the ground. Something like a bouncing ball. But I can't use Physics Materials. Here are some ways that I tried Used Physics.CheckSphere isGrounded Physics.CheckSphere(rayPoint.position, grounDistance, groundLayer) if(isGrounded ) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) Used Raycast bool groundHit Physics.Raycast(rayPoint.position, transform.up, rayDistance, groundLayer) if(groundHit) rb.AddForce(transform.up jumpForce, ForceMode.Impulse) In each cases, the object jumps a different amount of height each time it reaches the ground. How can I make it jump an equal height each time?
0
Allow player to restart animation after it plays fully I have this code that plays an animation when the player touches the screen. The animation lasts 3 seconds. public class canCDanim MonoBehaviour public Animator anim private void Start() anim GetComponent lt Animator gt () void Update() Touch touch Input.GetTouch(0) if (touch.phase TouchPhase.Began) anim.Play( quot CanReload quot ) The trouble is that if the player touches the screen again, the animation will not play again. How can I make it so that I can restart the animation, but only after it's finished playing?
0
Xcode workspace with Unity3D as a sub project? Let's say we're developing a 2D game with Cocos2d iPhone and UIKit and CoreAnimation. But we're also considering leveraging the 3D capabilities of Unity 3D. Is it possible that we add the Unity3D generated Xcode project as a sub project into the workspace and expose the 3D UI element as some kind of UIView subclass so that the native UIKit and CoreAnimation code could use them without the need to mess up with their underlying Unity3D implementation?
0
How to make an animation play when a button is pressed once? I have added an idle and jump animation to a character in unity. I can make the animation happen when the button is pressed. If the button is up middle at the animation the character goes to the idle position. But I want the whole animation happen in one press to the button and then go back to the idle position. My current script and Animator views are if (Input.GetKeyDown(KeyCode.Space)) Anim.SetBool("is jumping", true) ApplyInput(moveAxis, turnAxis) else if (Input.GetKeyUp(KeyCode.Space)) Anim.SetBool("is jumping", false)
0
Position child on the edge of the parent circle while scaling unity3d I have come across to some different situation. I have one circle sprite and i am rotating circle continuously while rotating i want to make circle smaller and larger. I have one object on the edge of the circle i have made that object as child of the circle. Now my problem is how to make this child object to stay at the edge while i scale circle sprite . I s this possible ? Thanks.
0
Unity 2D Position Child Object to center of Parent Object What I'm trying to achieve is snapping a child object to the center of its parent object after dragging and dropping it. The moving object successfully follows the mouse, and drops. It also successfully selects a dynamic parent when it moves over a new node. What it does NOT do is then snap to the center of its parent. It instead jumps all over the screen and snaps to nothing. Here is all of my code using System.Collections using System.Collections.Generic using UnityEngine public class Object Moveable MonoBehaviour private Vector2 mousePos public float moveSpeed public float offset 0f private bool following private GameObject SelectedNode Use this for initialization void Start() following false offset 10 void Update() if (Input.GetMouseButtonDown(0) amp amp ((Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position).magnitude lt offset)) following true if (following) transform.position Vector2.Lerp(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), moveSpeed) if (Input.GetMouseButtonUp(0)) following false Attach (Node, 0, 0) transform.localPosition SelectedNode.transform.position void OnTriggerEnter2D(Collider2D trigger) if (trigger.tag "pipenode") transform.SetParent(trigger.transform) SelectedNode trigger.gameObject
0
Why doesn't my SpriteRenderer's color change when setting .color new Color(166, 33, 33)? I need to change the color of my SpriteRenderer, and so I looked up how to do it and come up with this code spaceOne.GetComponent lt SpriteRenderer gt ().color new Color(166, 33, 33) (In case you are wondering, yes I checked that 'spaceOne' is correctly linked to a GameObject.) This should change the color, but it doesn't. As I was writing this, I found that replacing new Color(166, 33, 33) with Color.red actually does change it to red. So now I am wondering, why does the new Color(166, 33, 33) code not work, and how can I fix it? P.S. I made sure that it wasn't something simple, like it being RGBA rather than RGB, but no, it still doesn't work with new Color(166, 33, 33, 255) .
0
AR Foundation video player in Unity without Vuforia I am trying to follow this mini tutorial and I can detect an image and replace it with my 3D object. The object is an AR Session Origin tracked image prefab, but when I try to add a Video Player instead, nothing happens. I was using Unity 2019.2 and got an error when trying to put the video player on the object, then searched about it and Unity fixed that issue on 2019.3. I am now using 2019.3 and don't get the error anymore, but there is also nothing on the screen when the image is detected.