_id
int64
0
49
text
stringlengths
71
4.19k
0
Unity Failed to build APK. See console for details i am getting this error whenever i am trying to build a project. i looked at so many solutions but this one just doesn't go away. This is the error CommandInvokationFailure Failed to build apk. C Program Files Java jdk 9 bin java.exe Xmx2048M Dcom.android.sdkmanager.toolsdir "C Users Mohit AppData Local Android sdk tools" Dfile.encoding UTF8 jar "C Program Files Unity Editor Data PlaybackEngines AndroidPlayer Tools sdktools.jar" stderr Exception in thread "main" java.lang.reflect.InvocationTargetException at java.base jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java 62) at java.base jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java 43) at java.base java.lang.reflect.Method.invoke(Method.java 564) at SDKMain.main(SDKMain.java 130) Caused by java.lang.NoClassDefFoundError sun misc BASE64Encoder at com.android.sdklib.internal.build.SignedJarBuilder. lt init gt (SignedJarBuilder.java 177) at com.android.sdklib.build.ApkBuilder.init(ApkBuilder.java 446) at com.android.sdklib.build.ApkBuilder. lt init gt (ApkBuilder.java 422) at com.android.sdklib.build.ApkBuilder. lt init gt (ApkBuilder.java 362) at UnityApkBuilder. lt init gt (UnityApkBuilder.java 214) at UnityApkBuilder.main(UnityApkBuilder.java 34) ... 5 more Caused by java.lang.ClassNotFoundException sun.misc.BASE64Encoder at java.base java.net.URLClassLoader.findClass(URLClassLoader.java 466) at java.base java.lang.ClassLoader.loadClass(ClassLoader.java 563) at java.base java.lang.ClassLoader.loadClass(ClassLoader.java 496) ... 11 more stdout exit code 1 UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.HostView OnGUI() what i have tried so far 1) downgrading android sdk 2) moving zipalign file from build tools to tools folder 3) setting up keystore
0
How to approach a coloring app? I want to make a coloring app in unity. I don't need flood filling. THe player will select a color and click the shape to fill that color. The app will have designs as shown below Here the problem is, design has to be empty with black outline. One way would be to create textures using the jpg of each shape. However, there are thousands of shapes and each can be colored in about 7 colors. So, i will have to create 7 textures for each shape.Is there any way to create model with black outline so that only inner color can be changed?
0
AddForce doesn't work anymore when Acceleration is added Everything worked fine until I added acceleration on the x axis..now when I try to jump it just lifts up very little from the ground in a weird way and then it slowly sinks down like having 0 gravity. Here is the code I'm using public class PlayerMovement MonoBehaviour public float baseSpeed 10f public float maxSpeed 10f public float timeFromZeroToMax 10f public float jumpSpeed 10f public Collider coll float accelRatePerSecond float forwardVelocity Rigidbody rb void Awake () rb GetComponent lt Rigidbody gt () coll GetComponent lt Collider gt () accelRatePerSecond maxSpeed timeFromZeroToMax forwardVelocity 0f void FixedUpdate() transform.Translate(transform.right baseSpeed Time.deltaTime) forwardVelocity accelRatePerSecond Time.deltaTime forwardVelocity Mathf.Min(forwardVelocity, maxSpeed) if (isGrounded() amp amp Input.GetKeyDown("w")) rb.AddForce(transform.up jumpSpeed Time.deltaTime, ForceMode.Impulse) void LateUpdate() rb.velocity transform.right forwardVelocity bool isGrounded() return Physics.Raycast(transform.position, Vector3.down, coll.bounds.extents.y 0.1f)
0
How to serialize animation state? In Unity, I have an Animator on a character. Upon saving loading the game, I want to preserve the pose and animation state the character is in. However, I can see no way to read write all the data from the Animator Animation Controller in such a way that I can store it in and retrieve it from a binary file. Is there a non obvious way to achieve this?
0
Depth write and depth test in Unity Scenario several objects (o1, o2,.., on) have to be rendered with the z test disable, but the z values must be written to the depth buffer. In another pass, some other objects (t1, t2,..., tm) need to be rendered considering with the z test enabled, and considering the prior values from the previous pass. Is it possible to achieve this with Unity's material script? The goal is to support a custom order for the rendering of transparent objects (the o1,..,on in the scenario description) alongside with matte objects (t1,..., tm). I tried using the features mentioned here, but the results were incorrect, i.e. as if the z values were completely discarded inbetween passes. Can anyone, perhaps, share a code stub for this scenario?
0
Object made of cubes looks different based on the distance in Unity3D? I made a "Wall" from basic Unity3D cubes. They are placed tightly so the wall looks like one big rectangular prism. If I look at it from close distance, it looks as it should be one big rectangular prism. But if I start moving backwards, away from the wall, the cubes' edges become visible And this whole thing happens in a circular way. If I just start moving backwards from the wall, first I start to see the cubes' edges just at the further parts of the object, and then the pure white circle starts shrinking, the edges become visible at bigger and bigger parts of the object. then the blurrier edges appear at the further places and the previously appeared sharper edges circle starts shrinking as well. (this phase is shown on the image above) This should be some kind of shading optimization, like mipmap, right? How can I fix this? I want the wall to be seamless from all distances. Update Changing the shader to Unlit gt Color, fixes the issue. This thing only occurs on the lit side of the wall. The shadowy side of the wall, (which isn't lit directly by the directional light of the scene) is rendered normally.
0
How to "place" object in a 3d world without overlapping them ? I would like to place object in a 3d world "like minecraft player can do". What I'm trying to do is to allow the user to place objects, without overlapping them (like in minecraft you can do). So if the player try to place an object partially over another, my game automatically "move and place" the object in the allowed position. What can be the right approach ?
0
How do I account for the velocity difference between a ship and it's fired projectile? In my project, I have a ship that moves and increases it's movement speed with respect to time and how long the acceleration button is being pushed(just like the way a real life car works), now as expected, the ship fires projectiles when I press the fire button. The problem here, is that at a point in the game, the ship reaches it's highest speed terminal velocity, and now it's faster than the projectile it fired which is not what I want, so, how do I create a realistic projectile movement based on the ship's velocity? This is so that if the projectile is fired when the ship is moving slowly through the game scene, it doesn't move so fast that we can't see it travelling in the forward direction, and at the same time if it is fired when the ship is moving at top speeds, the ship is not seen to be faster than or as fast as the projectile's speed. I want to keep the code as optimized as possible, so I am using this line for the projectile's movement public float velocity 100f void Update() transform.position transform.forward Time.deltaTime velocity
0
Moving script not working after SetActive Pause change I have a pause menu for my game which instantiates a texture and sets a text frame to active and slides both objects onto the screen using the code below Instantiating the menu texture and activating the text frame public void MenuPressed () Vector3 newPosition new Vector3 ( 13, 0.06f, 2) Quaternion newRotation Quaternion.Euler (0, 0, 0) Instantiate (menu, newPosition, newRotation) menuButton.SetActive (false) textFrame.SetActive (true) Time.timeScale 0 Moving the menu items float xLimit 5 float speed 0.6f void Start () StartCoroutine ("MoveMenu") IEnumerator MoveMenu () while (true) transform.position Vector3.right speed if (gameObject.name "Main Text Frame") xLimit 7 if (transform.position.x gt xLimit) yield break yield return new WaitForEndOfFrame () Now this all works fine, but the issue that I have is on a multiple pause situation. When the pause button is pressed and spawns the menu and activates the text, the game pauses as expected. One of the options on the menu is to resume playing, when the pressed the game carries on as expected. The problem I am having is that if the pause button is pressed again, the menu texture spawns in and slides on screen as intended, but the frame for the text does not. The frame gets set active but does not actually move. Any ideas for how to fix this? P.S Here is the code I use to resume the game after it had been paused public void Button1Pressed () Time.timeScale 1 GameObject menu GameObject.FindWithTag ("Menu") Destroy (menu) gameController.paused false textFrame.SetActive (false) menuButton.SetActive (true) textFrame.transform.position new Vector3 ( 15.2f, 4.0f, 2.5f)
0
Making a new instantiated prefab as a child for existing GameObject I've been searched about how to make these fruit to move as the basket movement if it collided with it, and I've been found that if I want to perform this I've to let these fruit to be a child to the basket game object .. for example banana.transform.parent basket.transform banana and basket each of them of type "GameObject" ... BUT unfortunately this way didn't work !! and I don't know why ?? So now I need to know if it is possible to destroy the banana if a collision with the basket happened and instantiate a new banana in the basket as a child at run time ?!! I need to try this stupid way because I've tried all the other ways and nothing worked (
0
Correct way to project a texture with alpha and colors onto surfaces in Unity I am experimenting with Unity and wanted to project a unit circle beneath a unit and my very first naive approach was to create a child plane below the unit, assign the material to it and stretch it using the Pro Builder UV editor but it looked horrible In order to figure out what's wrong I read a lot of various approaches to "fix" that issue which were mostly the following use a higher resolution for the texture do not use any compression do not use a POT resolution change the filtering option from bilinear to point ... Eventually I figured that I have to do something completely different and that is how I stumbled upon the idea to use a shader attached to a projector game object in order to project a material. Unfortunately though it turns out the shader expects a grayscale image and only tints the projection based on a parameter. For reference this is the shader I have just copied from the web (source) Shader "Projector AdditiveTint" Properties Color ("Tint Color", Color) (1,1,1,1) Attenuation ("Falloff", Range(0.0, 1.0)) 1.0 ShadowTex ("Cookie", 2D) "gray" Subshader Tags "Queue" "Transparent" Pass ZWrite Off ColorMask RGB Blend SrcAlpha One Additive blending Offset 1, 1 CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" struct v2f float4 uvShadow TEXCOORD0 float4 pos SV POSITION float4x4 unity Projector float4x4 unity ProjectorClip v2f vert (float4 vertex POSITION) v2f o o.pos UnityObjectToClipPos (vertex) o.uvShadow mul (unity Projector, vertex) return o sampler2D ShadowTex fixed4 Color float Attenuation fixed4 frag (v2f i) SV Target Apply alpha mask fixed4 texCookie tex2Dproj ( ShadowTex, UNITY PROJ COORD(i.uvShadow)) fixed4 outColor Color texCookie.a Attenuation float depth i.uvShadow.z 1 (near), 1 (far) return outColor clamp(1.0 abs(depth) Attenuation, 0.0, 1.0) ENDCG With that shader I was able to render the following effect Since I have no experience with shaders at all I just blatantly copy amp pasted it and do not know (yet) how to customize them or even write custom ones in the first place. Assuming my approach to combine a projector with such a shader is the way to go, I'd like to know whether there is any shader you can share that allows me to project an unlit texture with transparency and its own color such as the following example
0
Reopening Unity project after two week break, project is trashed I've spent about 6 months using Unity nearly every day. Then I take a two week break, re open my project, and the entire build is trashed. There are 166 errors, here are a few Assets TextMesh Pro Examples amp Extras Scripts ChatController.cs(6,14) error CS0101 The namespace ' lt global namespace gt ' already contains a definition for 'ChatController' private Renderer renderer Assets Scripts Board Tile.cs(23,22) warning CS0108 'Tile.renderer' hides inherited member 'Component.renderer'. Use the new keyword if hiding was intended. Assets TextMesh Pro Examples amp Extras Scripts ObjectSpin.cs(8,18) error CS0101 The namespace 'TMPro.Examples' already contains a definition for 'ObjectSpin' I've re imported Text Mesh Pro Examples amp Extra, restarted my project multiple times, to no avail. This is very concerning to me because it makes me feel like Unity is not a stable plaform ... Are Unity projects attacked by gremlins if not used every couple days?
0
Chroma depth shader unity I'm trying to reproduce a post effect with unity seen in the answer here. Chromadepth answer For the moment I just manage to reproduce the wave effect with a quick edge detection. I tried multiple textures but can't find one that fit do the same effect. I am using this texture The result for far. Shader "Unlit ChromaDepthEdge" Properties MainTex ("Texture", 2D) "white" Ramp ("Texture", 2D) "white" Threshold("Threshold", Float) 0.1 SubShader Pass ZTest Always Cull Off ZWrite Off CGPROGRAM pragma vertex vert pragma fragment frag pragma target 3.0 include "UnityCG.cginc" struct appdata float4 vertex POSITION sampler2D MainTex sampler2D Ramp Request camera depth buffer as a texture. Incurs extra cost in forward rendering, "just there" in deferred. sampler2D CameraDepthTexture float4 MainTex TexelSize float4x4 InverseViewMatrix float Threshold void vert ( float4 vertex POSITION, out float4 outpos SV POSITION) outpos UnityObjectToClipPos(vertex) fixed4 frag (UNITY VPOS TYPE screenPos VPOS) SV Target Convert pixel coordinates into screen UVs. float2 uv screenPos.xy ( ScreenParams.zw 1.0f) uv.y (uv.y 1) 1 Depending on setup platform, you may need to invert uv.y Sample depth buffer, linearized into the 0...1 range. float depth Linear01Depth( UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv))) float2 uvDist 3 MainTex TexelSize.xy float depthUp Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2(0, 1)))) float depthDown Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2(0, 1)))) float depthLeft Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2( 1, 0)))) float depthRight Linear01Depth(UNITY SAMPLE DEPTH(tex2D( CameraDepthTexture, uv uvDist float2(1, 0)))) float mean ((depthUp depth) (depthDown depth) (depthLeft depth) (depthRight depth)) 4 Compressing the range, so we get more colour variation close to the camera. depth saturate(2.0f depth) depth 1.0f depth depth depth depth 1.0f depth return depth Use depth value as a lookup into a colour ramp texture of your choosing. fixed4 colour tex2D( Ramp, depth 6 Time.y 4) return lerp(colour, colour 6, mean gt Threshold) ENDCG What did I miss ? Thanks in advance.
0
How can I optimize coroutines? I have a script which has a Queue datastructure (code below). This queue holds more than 100 Actions. So currently my script does a yield return null after every Dequeue, which means that one Dequeue() call is executed every frame. private static readonly Queue lt Action gt DataQueue new Queue lt Action gt () private bool isHandlingQueue Helper bool to check if Coroutine is active private IEnumerator HandleQueue() isHandlingQueue true while (DataQueue.Count gt 0) DataQueue.Dequeue().Invoke() yield return null isHandlingQueue false yield return null I'm trying to achieve that multiple Dequeue and Invoke actions take place in the same frame. One Dequeue and Invoke takes between x and y ms, this varies depending on the Action itself. Example Lets say the Queue has 100 entries and the game runs at 60 frames per second (minimum). One iteration (Dequeue Invoke) in the while loop takes about 5 ms in this example. Here is the thing In this case it is essentially waiting for 11.67 ms for the next frame (16.67 ms each frame at 60fps). I don't want the system to wait, but use the remaining 11.67 ms to Dequeue and Invoke 2 more Actions, so it only waits for 1.67ms each frame. In this ideal case the Queue get's cleared in 34 frames instead of 100 frames. All help to point me in the right direction is appreciated!
0
Assign a ScriptableObject to MonoScript through code Sample code public class Item MonoBehavior public ItemObject item the scriptable object void Start() do stuff Normally I would drag and drop the asset of the ScriptableObject in the inspector. How can I find and assign the asset (from Project View) through the script during runtime and possibly add it to a List lt gt or Array ?
0
How do I storing a Score in each level? I have a problem when I store the DistanceScore to text, the problem is why the DistanceScore always storing at text number 1, this happens when I play at level 2 which is the DistanceScore could be store in text number 2and so on, FYI I have 3 levels here. here the preview as you can see on the top of level 2 gameplay is distance so when i dead the distance saved and storing to text each level. and when I go to the main menu the Level 1text updated instead of Level 2. this is my script public Item item public int mapIndex public enum ITEM TYPE LEVEL public ITEM TYPE type private void Start() loadItemInformation() public void loadItemInformation() for (int i 0 i lt item.Length i ) if ( type ITEM TYPE.LEVEL) item i .bestScore.enabled true item i .distance.enabled true float distanceUi PlayerPrefs.GetFloat( quot distance quot i.ToString()) float value PlayerPrefs.GetFloat( quot Time quot i.ToString()) float minutes Mathf.FloorToInt(value 60) float seconds Mathf.FloorToInt(value 60) if (value 0) item i .bestScore.text quot No Record Yet quot else item i .distance.text quot Unstopable quot item i .bestScore.text quot Best Time quot string.Format( quot 0 00 1 00 quot , minutes, seconds) item i .distance.text quot Long distance quot distanceUi.ToString() System.Serializable public class Item public TextMeshProUGUI bestScore public TextMeshProUGUI distance here the distance script region Distance Header( quot Distance quot ) public Transform checkPoint public TextMeshProUGUI distanceText M GameManager GameManager private float distance private float highDistance float index endregion private void Start() GameManager FindObjectOfType lt M GameManager gt () checkPoint GameObject.FindGameObjectWithTag( quot Finish quot ).transform distanceText GameObject.FindGameObjectWithTag( quot DistanceTxt quot ).GetComponent lt TextMeshProUGUI gt () index (float)(PlayerPrefs.GetInt( quot Level quot )) typo here i call it set and now I've fix it index PlayerPrefs.GetFloat( quot Level quot ) distance (checkPoint.transform.position.x transform.position.x) if (transform.position.x gt checkPoint.transform.position.x) distance 0 PlayerPrefs.SetFloat( quot distance quot index, distance) if ( GameManager.isDead GameManager.isTimeout GameManager.fuelFinished) PlayerPrefs.SetFloat( quot distance quot index, distance) PlayerPrefs.Save() distanceText.text distance.ToString( quot F1 quot ) quot m quot and for item i .bestScore.text this work to storing each level but why for the distance not working.
0
Generating Mesh using Compute Shaders I am working on a game project in unity which has a procedurally generated terrain made up of 16 128 16 chunks of blocks. The map size is going to be finite (Possibly up to 100 100 chunks). Currently the data for the chunk is stored in a 1D Array, and takes a couple milliseconds to generate. But generating the mesh takes longer, averaging 30 40ms. So generating terrain as it enters the range of the camera isn't feasible as it's too slow, and generating all the meshes on load up would take a lot of memory as well as a long time. I've thought about attempting to try it on the GPU through Compute Shaders (although I don't have any experience with them). Would generating the mesh for each chunk in a Compute Shader be viable efficient? (The chunks could be made smaller if would be more performant)
0
How to scale game with orthographic camera correctly? During porting to android I encountered that the game does not fit on the screen in portrait mode. It uses an orthographic camera. How could I scale to game to fit the screen in portrait mode?
0
Why does 'InvalidCastException Specified cast is not valid.' occur for ARKitFaceSubsystem? Why does 'InvalidCastException Specified cast is not valid.' occur for ARKitFaceSubsystem in the snippet below? var faceManager FindObjectOfType lt ARFaceManager gt () if (faceManager ! null) m ARKitFaceSubsystem (ARKitFaceSubsystem)faceManager.subsystem
0
Performance of manipulating a mesh in realtime Does Unity allow streaming mesh data that can be continuously changed? I have a level that is dynamically changing based on some parameters. The number of triangles stays the same, they just change positions. I'm speaking of around 2000 triangles that need their position updated each frame (they follow a spline that is computed on CPU), running on mobile phones. I can't use a TrailRenderer because the object is a whole level. I can't use bones, because I need to know the final position for each vertex for my custom collision code. The mesh should be marked Mesh.MarkDynamic.
0
How to access specific child indices (directly, not using tags or searches)? I have a game object whose prefab is structured a very specific way. It is a conveyor belt. I intend to arrange them end to end and animate them all at once using a script. Right now I am trying to get the normalized heading vector between two children, TargetStart and TargetEnd (see images below) You can see that both of these objects are children of the prefab's first child. Because all of these instances will be structured the same, I want to compute the heading for the conveyor belt by accessing the locations of these children by their indices relative to the parent (which sounds like it should be simple and should be more efficient than searching by name or tag). I am anticipating a structure like this (pseudo code) heading targetEnd's position targetStart's position vector3 heading gameObject.GetChild 0 1 .position gameObject.GetChild 0 0 .position vector3 direction heading heading.magnitude How can this be done? I would like to know this so I can access any child I need to for any object by the child's index.
0
How to update UI after changing text in a view After applying a text change to a scrolling view, how do you get the new height of the text, resize other UI elements around the changed text length, etc? Many have posted this question. Some have noted that the rect size doesn't change or that they have to wait multiple frames to then react to the UI updates.
0
Why is there a gameObject inside a GameObject In order to manipulate a game object via script in Unity I need to access the gameObject inside the main GameObject. Why is it structured this way? What is the main GameObject representing compared to the gameObject? public class Sun MonoBehaviour private GameObject satelliteGameObjects private Rigidbody satelliteRigidBodies public GameObject Satellites private void Start() if (Satellites null) Debug.LogError( "You haven't added a nameof(Satellites) .'") throw new InvalidOperationException( " nameof(Satellites) should not be null") satelliteRigidBodies new Rigidbody Satellites.Length satelliteGameObjects new GameObject Satellites.Length for (var i 0 i lt Satellites.Length i ) var satellite Satellites i satelliteRigidBodies i Satellites i .gameObject.GetComponent lt Rigidbody gt () satelliteGameObjects i Satellites i .gameObject satelliteRigidBodies i .AddForce(Vector3.up 100) In the example above, I'm passing a GameObject into this class. However, in order to call members on the actual game object, I need to go through the gameObject property.
0
How to force Landscape Mode Unity3D Android Game? I am developing a small side project on Unity that will ultimately be for Android but I cannot figure out how to force landscape on the device and when I have tried it out the game just goes all over the place! I am using Unity Canvas and have spent a long time with binding position points etc. but I cannot work it out! Could someone please tell me how to force the phone into landscape mode?
0
How do I get my mouse based input system to work on Android? I am developing the ball breaker game in unity and right now my game work with mouse click button. but i want my game work in android. so what changes i want to do in this code? So when i set the arrow and its jump ball and hit the brick. Here is the code with image BallController.cs using System.Collections using System.Collections.Generic using UnityEngine public class BallController MonoBehaviour public enum ballState aim, fire, wait, endShot public ballState currentBallState public Rigidbody2D ball private Vector2 mouseStartPosition private Vector2 mouseEndPosition private float ballVelocityX private float ballVelocityY public float constantSpeed public GameObject arrow Use this for initialization void Start () currentBallState ballState.aim Update is called once per frame void Update () switch (currentBallState) case ballState.aim if (Input.GetMouseButtonDown (0)) MouseClicked () if (Input.GetMouseButton (0)) MouseDragged () if (Input.GetMouseButtonUp (0)) ReleaseMouse () break case ballState.fire break case ballState.wait break case ballState.endShot break default break public void MouseClicked() mouseStartPosition Camera.main.ScreenToWorldPoint(Input.mousePosition) Debug.Log (mouseStartPosition) didClick true public void MouseDragged() didDrag true Move the Arrow arrow.SetActive(true) Vector2 tempMousePosition Camera.main.ScreenToWorldPoint(Input.mousePosition) float diffX mouseStartPosition.x tempMousePosition.x float diffY mouseStartPosition.y tempMousePosition.y if (diffY lt 0) diffY .01f float theta Mathf.Rad2Deg Mathf.Atan (diffX diffY) arrow.transform.rotation Quaternion.Euler (0f, 0f, theta) public void ReleaseMouse() arrow.SetActive (false) mouseEndPosition Camera.main.ScreenToWorldPoint(Input.mousePosition) ballVelocityX (mouseStartPosition.x mouseEndPosition.x) ballVelocityY (mouseStartPosition.y mouseEndPosition.y) Vector2 tempVelocity new Vector2 (ballVelocityX, ballVelocityY).normalized ball.velocity constantSpeed tempVelocity if (ball.velocity Vector2.zero) return currentBallState ballState.fire
0
How to get consecutive voice clips to sound natural In the game I'm working on I have to play several short consecutive voice clips to form a complete sentence. Example (each bracket is a different voice clip) Bob here, we're at some town and are on our way to some city . Stitching together different voice clips like this makes it sound stilted and disconnected. This is because there are unnatural pauses when switching clips, and the pitch and tone of the speaker changes. My current efforts include two methods for removing the unnatural pauses starting the next clip early if a silence is detected at the end of the preceding clip skipping the first few milliseconds of the new clip up to the first detected 'sound'. These work OK at removing the unnatural pausimh, but detecting what 'silence' is is difficult, especially when dealing with multiple voice actors and microphones. How could I make stitching together voice clips sound more natural? Any advice would be appreciated. This has to be done in real time inside the game (I'm using Unity), and can't be pre processed or done ahead of time.
0
Unity ScrollView not scrolling with Clamped or Elastic I have a ScrollView object in my project. It is set to Clamped. Inside the ViewPort, I have Content and what I actually want to scroll, a TextViewMesh. The Content has a Content Size Fitter, with its Vertical fit set to Preferred Size. The problem is, when I run it, and try to scroll, it does not scroll at all, in ScrollView to the current setting. If I set the ScrollView mode to Unrestricted, it scrolls to the infinity. What I am doing wrong? How can I set my ScrollView to scroll the text (which can vary in lenght)?
0
Mesh disapears before out of fov I use a C script to move the vertecies of my quad around the world space. It works perfectly fine, but when I move rotate the camera away, so it does not look at the position of the quad, the quad disappears. I cannot change the size of the quad, since that would not work with my other scritps. How can I force the camera to allway render the mesh of the quad?
0
How to give individual tiles their own collider in Unity's tilemaps? My floor tile is a 2D drawing of a 3D platform, for lack of a better description. I want my player character to stand not on the top of the tile but a little inside it, as the red circle does in the picture. How do I give this tile its own collider that would fit this shape, while letting others have a normal, square one?
0
Unity 3d 4.6b New GUI system doesn't take touch when already a touch event is occurring in 3d scene I know this is beta version but.. I have a Canvas Button which works fine when I tap it normally. I have a joystick in my scene which is drawn by separate camera other than mainCamera. now, while i am operating joystick without leaving it, if I tap on he Canvas Button it does not respond. When I lift finger from joystick and tap on it, it works fine. Same goes for another Canvas Toggle control. It has something to do with the layering or anything else...I'm not sure?
0
How do I make an object not appear grey regardless of distance? My moon texture is on a plane 500m away and I would like to know if there is a way to keep displaying the texture As opposed to it turning grey as pictured here regardless of the distance it is from the camera. Any help is greatly appreciated, Thanks.
0
In unity, making a navmesh for a tiny planet? I'm trying to build a scene in a small planet, and baking will always give me the result on the half top of the planet. But what I want is to create a navmesh all around the small planet. I am wondering if there is a way to convert a mesh that I well built in blender, to be a navmesh in Unity. That means using the mesh totally without baking. Or, if there is some other ways to create navmesh for my poor planet.
0
How to go back to the old input system? I have tried using Unity's new input system, but it's incredibly hard to learn, the documentation is poor, and the old system is much easier to work with. I would like to revert my project back to the old system, but I am unsure how to do that. How do i disable the package and reconfigure my project so it will accept code using the old system?
0
Unity how intercept Mouse Click on UI and not fire "shoot"? I've a classic void Update() if(Input.GetMouseButtonDown (0)) Fire() What i want to do is that if I click on a UI button , the Fire() routine not will be called. How to do to say Unity if InputGetMouseButtonDown(0) amp amp !UI clicked ?
0
Object goes straight through game object without colliding The "shot" is supposed to collide with the left bumper and then be destroyed, but the shot goes right through it. Both objects have a box collider. The following is the code I am using pragma strict var speed int 2 var collided with GameObject function Update () transform.Translate(Vector3( 1 speed Time.deltaTime, 0, 0)) function OnCollisionEnter (col Collision) if (collided with.tag "Left") Destroy(gameObject) I have made sure that all the tags are assigned correctly and that there are no spelling errors. The variable collided with is also assigned to the left bumper. What am I doing wrong?
0
Draw GUI.Button on certain position on a scrollable background Problem is in a 2D game I have a large background around 2 screens wide. And on there I got 4 buttons placed on top of background all over complete width. Now when I swipe of move my mouse around I scripted that the camera will move with it. So for the GUI.Buttons (Unity4.5) to stick on their place I used a variable drawX drawX Camera.main.transform.position.x 100 The 100 is for calculating it to pixels. I then add this to my buttons when drawing. scaleX Screen.width 1920f scaleY Screen.height 1200f if (GUI.Button(new Rect((500 drawX) scaleX, 700 scaleY, 325 scaleX, 425 scaleY), "")) Now the problem is that under 1920x1200 my target resolution everything works exactly pixel perfect. But when changing the resolution or aspect ratio to something else the drawX increases to much or not enough so the buttons don't move on the same pace as they did in the 1920x1200 version. Somebody got the solution for me?
0
360 Orbital Camera Controller I have a stationary cube in my scene that I'm orbiting a camera around. I have my MainCamera nested under a GameObject that I'm calling 'OrbitalCamera'. I setup the script so that a click (or tap) and drag will rotate the camera around the object in space so it feels like you're rotating the cube (ie if I click the top of a face on the cube, and pull down, I'm rotating the X value) but you'll actually be rotating the camera. For the most part, my script works. However, after rotating the Y so much, the camera is upside down and the X gets inverted. Here's my script public class OrbitalCamera MonoBehaviour public bool cameraEnabled SerializeField private float touchSensitivity SerializeField private float scrollSensitivity SerializeField private float orbitDampening protected Transform xFormCamera protected Transform xFormParent protected Vector3 localRotation protected float cameraDistance void Start () cameraEnabled true xFormCamera transform xFormParent transform.parent cameraDistance transform.position.z 1 void LateUpdate () if (cameraEnabled) TODO FIX PROBLEM WHERE WHEN CAMERA IS ROTATED TO BE UPSIDEDOWN, CONTROLS GET INVERSED if (Input.GetMouseButton(0)) if (Input.GetAxis("Mouse X") ! 0 Input.GetAxis("Mouse Y") ! 0) localRotation.x Input.GetAxis("Mouse X") touchSensitivity localRotation.y Input.GetAxis("Mouse Y") touchSensitivity Quaternion qt Quaternion.Euler(localRotation.y, localRotation.x, 0) xFormParent.rotation Quaternion.Lerp(xFormParent.rotation, qt, Time.deltaTime orbitDampening) Is there a good method to achieve this type of 360 camera? I'd like dragging from right to left to always move the camera left and dragging left to right to always move the camera right no matter how the camera is oriented.
0
Unity Hub 2.3.0 Buggy Setup? I recently downloaded the new Unity Hub 2.3.0 setup and since I hadn't used (or downloaded Unity Core) using the previous version of the Hub, I simply deleted the folder containing Unity Hub instead of uninstalling it like any normal person would. Now, every time I open the Unity Hub Setup and try and install it, it always shows the same "Installation Aborted, could not install successfully," error. I can't even uninstall the previous version from Windows Settings! I've tried changing the destination folder, but still doesn't work. Any help is appreciated! P.S. This error occurs when installing UnityHub, not the Unity Core Platform! I've also looked at all other similar posts. Thanks.
0
first person character controller error I have opened new scene, deleted camera and imported first person character controller from Standard assets. I placed plane on scene and put first person character controller on plane. I got this error Assets Standard Assets Characters FirstPersonCharacter Scripts RigidbodyFirstPersonController.cs(3,27) error CS0234 The type or namespace name CrossPlatformInput' does not exist in the namespaceUnityStandardAssets'. Are you missing an assembly reference? How to fix it?
0
How do I create a toggle button in Unity Inspector? I want to create a tool similar to Unity's Terrain tool, which has some nice toggle buttons in the inspector How can I achieve similar design to this? I know how to create normal buttons and other UI components in the inspector, but I can not find enough information to make the buttons toggle. So far I have used normal toggles that produce a checkbox var tmp EditorGUILayout.Toggle( SetAmountFieldContent, setValue ) if ( tmp ! setValue ) setValue tmp if ( setValue ) smoothValue false tmp EditorGUILayout.Toggle( SmoothValueFieldContent, smoothValue ) if ( tmp ! smoothValue ) smoothValue tmp if ( smoothValue ) setValue false Setting the toggle GUIStyle to "Button" does not produce the wanted result. The text or image content goes on left of the button instead of inside. var tmp EditorGUILayout.Toggle( SetAmountFieldContent, setValue, "Button" ) Also none of the options found in GUISkin does not seem to help.
0
How to find the angle of an arc for reflection I am using the following code to calculate points for a circle arc drawn with a Line Renderer. for (int i 0 i lt pts i ) float x radius Mathf.Cos(ang Mathf.Deg2Rad) float y radius Mathf.Sin(ang Mathf.Deg2Rad) arcLine.positionCount i 1 arcLine.SetPosition(i, new Vector2(x, y)) ang (float)totalAngle pts How can I change the angle ang to create a reflected arc along the line P1P2 as in the image below? Please note that totalAngle represents the portion of the circle that is to be drawn between 0 and 360.
0
Weird behavior using TextMeshPro I have a very simple scene setup. What I want to do is to create a button prefab composed of a sprite and a TextMeshPro object. When I group the sprite and the text under a GameObject, the pivot of the compound object appears very far from the center of the GameObject (please see the attachment). I can't move the pivot of the text to the center no matter what I do. Is this an expected behavior?
0
Projecting grid textures to select parts of the terrain (Unity) So I'm trying to be smart and not use 500 some tile prefabs to make a grid, and so far the back end portion has gone swimmingly. I initially used a dedicated mesh to represent the grid, but as I'm now opting for 3D terrain (and not tilemapping), I figured that was a lot of unnecessary vertices especially if I want to have the grid conform to the terrain. My shader inexperience, on the other hand, is causing me to stop and overthink this. Using FE as inspiration, I'm thinking about projecting the transparent grid texture onto a base terrain layer. If I wanted parts of the terrain to not be covered by the grid (such as the water area in the picture), would I simply use the world coordinates to tell the shader don't do anything there? The most confusing part for me, however, is how to go about highlighting tiles. I want movement and attack tiles to also be 'painted' onto the terrain in specific colors, but obviously they only affect an even smaller portion than the terrain than the grid. Would I simply be using the same shader to grab world coordinates once again and more or less start stop overlaying the movement attack texture over the grid terrain? And if I'm really being efficient, those textures belong to the same png and I just use UV's to switch between them like a sprite sheet? Is this even a good practice for shaders in the first place? Redrawing and adding textures to only parts of a material? Should I be redrawing and updating the whole texture instead? I guess I get thrown off because I'm only familiar with a 1 1 mesh to material design, so the so the thought of a single mesh but multiple textures on discrete parts that may or may not overlap makes somewhat sense on paper but implementation in Unity is just above me atm. Thanks!
0
Can't refer mesh size after using .BakeMesh() in Unity I can't figure out how to refer to the size of a particular mesh. The mesh is created through .BakeMesh(), then a box collider is added. Unfortunately the box collider has a scale of 1 by 1 by 1, regardless of how big the mesh I'm adding it to seems to be. This doesn't match my understanding of how creating a box collider should work, so I've set up a Debug.Log that outputs the mesh size. Here the plot thickens. The mesh's size just comes back at 0, 0, 0. My attempts at getting the size of the object are as follows objectToMeasure.GetComponent lt Renderer gt ().bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().mesh.bounds.size objectToMeasure.GetComponent lt MeshFilter gt ().sharedMesh.bounds.size Assuming I'm referring to the size of the object in the correct way, this seems like it must be an issue created by baking the object. Do I need to wait a frame (via starting a coroutine) before trying to access the size of the object, or am I referring to the wrong component of the object, or is the BoxCollider setting it's size based on objectToMeasure's scale rather than it's size in the world? I feel sure that objectToMeasure.GetComponent().mesh.bounds.size should be right, since the script I use to bake to the mesh is meshToBake.BakeMesh(meshToMeasure.GetComponent().sharedMesh) I've been driving myself to the edge of sanity for 24 hours with this script not working, so advice is greatly appreciated.
0
How can I grab the script component of a collided object without knowing what script it is? CalculateDamage() is an animation event called at a point during the character's animation in my 2D game. The commented out code is before I realized that not all of my pirates will be of class MeleePirateUnit, so I'm trying to do things more generically here. My order of inheritance is like so MonoBehaviour Unit MeleePirateUnit, RangedPirateUnit. So sometimes, the collidedobj is a MeleePirateUnit, sometimes it's a RangedPirateUnit, etc etc. How do I set pirateUnit to the correct type of the script component of my gameObject? I thought just getting component of type monobehaviour would work since RangedPirateUnit and MeleePirateUnit both derive from monobehaviour but I'm getting an error of Assets Scripts Combat Scene RangedPirateUnit.cs(72,56) error CS1061 Type UnityEngine.MonoBehaviour' does not contain a definition forhealth' and no extension method health' of typeUnityEngine.MonoBehaviour' could be found (are you missing a using directive or an assembly reference?) public void CalculateDamage() if (!isDestroyed) var pirateUnit collidedObj.GetComponent lt MonoBehaviour gt () MeleePirateUnit pirateUnit collidedObj.GetComponent lt MeleePirateUnit gt () pirateUnit.health pirateUnit.health (damage pirateUnit.defence) if (pirateUnit.health lt 0) Destroy(pirateUnit.gameObject) isDestroyed true didAttack false
0
Unity WebPlayer WWW GET Requests fail in webplayer only, not in editor My question is about my game requesting data from my server side cloud based storage (I have the option of free public Dropbox or Amazon S3) via GET and the WWW class, and it not working only in the WebPlayer (works fine in the Editor). By not working, I mean that the request is sent successfully, authorized and responded to by the cloud service, but that WWW shows an error in the logs. In the case of using Amazon S3, the Web Player even crashes, otherwise it just fails gracefully and the user is unable to move forward. The Error log left by the webplayer says the following WWW Error Error when creating request. GET request with custom headers is not supported. for URL https my storage.s3.amazonaws.com myDir myFile.json Here's when I use a similar request to a public directory on Dropbox. There is no crash, but the request also fails. WWW Error Failed downloading dl.dropboxusercontent.com u 7782207 spare change weapons 0.json for URL dl.dropboxusercontent.com u 7782207 spare change weapons 0.json Try it for yourself http webroleplay.appspot.com (currently using Dropbox, so not crashing the player) username test1 password t
0
Unity Display array of Objects in inspector I have an array of ScritableObject's, which should only be displayed in the inspector if a boolean is true. How would I do this? With my current code, I get an error saying Cannot implicitly convert type Tile to Tile This is my current code using System.Collections using System.Collections.Generic using UnityEditor using UnityEngine CreateAssetMenu (fileName "Data", menuName "Tiles Map", order 1) public class Tile ScriptableObject public ETile eTile public Sprite sprite Space(5), Header("Variety") public bool variety Range(0f, 1f) public float varietyChance public Tile varietyTiles lt This should be hidden if variety is true public enum ETile Water, Grass CustomEditor(typeof(Tile)) public class MyScriptEditor Editor override public void OnInspectorGUI() var tile target as Tile tile.variety EditorGUILayout.Toggle("Hide Fields", tile.variety) if (tile.variety) tile.varietyTiles (Tile)EditorGUILayout.ObjectField("Tile", tile, typeof(Tile), allowSceneObjects true)
0
Why does my ship look like it's going backwards instead of fowards? I'm making an Asteroids clone based on this tutorial. I'm stuck on the 5th part of the tutorial. For some reason my ship is going backwards instead of forward or it looks like its going forward, but in the tutorial the ship gos toward the asteroid. In the debug log, the z axis increments in a positive value. so I assume it is going forward but for some reason the ship it self doesnt go towards the asteroid like it does in the tutorial. The ship itself is an fbx export from Maya 2014. Here's an annotated screenshot Full size version It's probably something really stupid, but I just can't figure out why this is happening.
0
Is it better to have object components in a variable than using GetComponent everytime? (Unity c ) Is this Rigidbody2D rb GetComponent lt Rigidbody2D gt () void Update() rb.AddForce(transform.up 20 Time.deltaTime) Better than this? void Update() GetComponent lt Rigidbody2D gt ().AddForce(transform.up 20 Time.deltaTime) And can you please tell me why?
0
Why is my custom Texture2D blurry? Have some WWW object downloading a .PNG image. ((SpriteRenderer)renderer).sprite Sprite.Create(request.texture, new Rect(0,0,100,100)) My sprite looks fine. Now, let's be a bit redundant and create a Texture2D out of the bytes from the download Texture2D t new Texture2D(100,100) t.LoadImage(request.bytes) ((SpriteRenderer)renderer).sprite Sprite.Create(t, new Rect(0,0,t.width,t.height)) Technically, this should produce something identical to the above snippet. However, the sprite is blurry (as in, low quality). I suppose it is when calling LoadImage. What may be causing this?
0
How do I determine distance of a point within a ProBuilder mesh? As in the title, I have an effect prepped for my game which applies certain derived parameters to a post processing effect after the player enters a boundary I created with ProBuilder. Finding how far inside the bound the player is that is, how far the player would have to travel, at minimum, to leave it would help me scale this effect. It is not an axis aligned boundary, and its sloped shape is fairly important. Having the effect go full on on crossing the boundary would be jarring to the player. I'm tempted to resort to traditional edge testing with this, but I would like to highlight that it will be done at least once per frame on multiple objects, so I would like to keep it as simple, and non home rolled, as possible. The other possibility would be to keep track of time exposed and scale it by that but this isn't ideal and I'm seriously curious as to whether a penetration depth testing method exists out of box. A requested image of my setup It is laterally symmetric, and that is unlikely to ever need to change. However, future volumes are likely to have varying angles and heights. Depth is more or less irrelevant, as while I'm using 3D, this game has the physics of a 2D platformer so you can consider it to have infinite depth if you need to. As you can see on the right, I've added almost nothing to it, other than the MagneticField.cs custom script (which does not even reference the mesh, only whether it's been crossed) and a debug class, TriangleReport.cs, that I'm working on right now. One thought I had was to get triangles for the top, bottom, left, and right edges, use them to define planes, and then determine the distance from those planes but if you've got something better I am all ears!
0
My script to play the intro scene the first time the player hits play from the main menu wont work The script I am using determines if it is the players first time hitting the play button and if it is it will load the intro scene, but if they have played before it will take them strait to the game scene. The problem is that it just takes them strait to the game scene. public class SeenBefore MonoBehaviour public string SceneName AsyncOperation preload Start is called before the first frame update void Start() preload SceneManager.LoadSceneAsync(SceneName) preload.allowSceneActivation false Update is called once per frame void Update() public void before() if (PlayerPrefs.HasKey("HasSeenIntro")) preload.allowSceneActivation true else PlayerPrefs.SetInt("HasSeenIntro", 1) SceneManager.LoadScene("Intro")
0
Duplicate a Prefab as a separate asset in Unity 5.2 I have a Asset which is a collectable object Pickup and I currently have eight in my scene, I'd like to duplicate this asset and use it to harm the player Bad Pickup . I decided to duplicate the asset because I wanted both assets to have the same components (Animation script, rigid body, mesh colider, etc...). However, when I edit the texture of my new asset Bad Pickup , it changes the texture used for the original asset Pickup as well. I've tried GameObject Break Prefab Instance on the object with the new asset but it doesn't appear to make a difference. Is there a way to break this instance so that I don't have to make a completely new GameObject and add the same components manually?
0
How to make player stay on a moving object I've made an obstacle course with various moving parts to test out movement of a player. In the obstacle course there is a section where there are multiple cubes moves from side to side, and you have to jump from one to the other. But regardless of their speed, I can't seem to get the player to stay on top of any of the moving cubes. I have no clue how to fix this my only guess would be to use materials, but I can't apply any to the character controller. I appreciate any suggestion that you can give. Also the movement is done as an animation that I created in unity in the animation window. Thanks, Nova
0
How to efficiently keep the player from moving outside the gameobject he is colliding with? I am developing a game with Unity 2017. The game mechanics are as follow Classic top down RPG Movements are UP, DOWN, LEFT and RIGHT Player evolves in a 16 16 map He can dig in the direction he wants to make his way through the map one tile at a time At first I was using a very classical approach using tilemaps, RigidBody2D and BoxCollider2D on tiles and the player GameObjects. Collision detections went fine and my tilemap looked pretty much like that (red being the walls and white the empty spaces) The problem with this approach is that I have to keep in memory the state of 256 tiles in a List lt Vector2f gt and to create the 256 expected GameObjects representing either my walls (which a totally black), or my floor (the empty space). Creating a black GameObject with its own BoxCollider2D for each of the tile seems a little bit overkill. And this brings me to the second iteration of my game to keep in memory only the tiles the player digged. What I would like to achieve efficiently, is to let the player evolve as long as he is colliding with an underlying tile, but stop moving as soon as he doesn't. This is ok This isn't, and player should be placed to previous state. I could take advantage of OnTriggerEnter2d and handle custom collision and response, but I have the feeling that something more simple and more optimized may exists somehwhere in the wild! Thanks to any help provided!
0
Path solving for a game with a similiar pathing mechanic to Anno I cant quite wrap my head around how to solve pathing in my game. The basic premise is you will place buildings and roads on a 2d field and then you will be able to create routes from one building to another where the pathing alghorithm should figure out the shortest path between them (if there is one). Something to keep in mind is that the game is going to be quazi infinite scale (think factorio) and i cant think of a performant enough solution. Currently what i am working with is that i have every straight Path segment saved as two (startPoint, endPoint) Vector2Int points in a list. And everytime a new road gets added or some road segment deleted i update this list depending on what happened, example situation I have this road This would be represented in my Roads list as 0 startPoint(0, 0) gt endPoint(5, 0) 1 startPoint(5, 0) gt endPoint(5, 3) 2 startPoint(5, 3) gt endPoint(10, 3) I now add another road so we have something like this Which would change the road list to something like 0 startPoint(0, 0) gt endPoint(5, 0) 1 startPoint(5, 0) gt endPoint(5, 2) 2 startPoint(5, 2) gt endPoint(5, 3) 3 startPoint(1, 2) gt endPoint(5, 2) 4 startPoint(5, 3) gt endPoint(10, 3) What i am doing currently when a new route is to be calculated is that i create a 2d bool array which i am feeding into a A solver to get the shortest path so the above road gets transformed into 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 With some starting and endpoint. This works fine for now but when the player will build on a huge size 10kx10k, i cant imagine generating 10kx10k bool array everytime will be a good solution. Anybody knows how to optimize this?
0
How to figure out what's moving my GameObject? I have a GameObject as part of a complex scene with a handful of interconnected parts, that's moving when it shouldn't be. I've tried running under the debugger and setting breakpoints on all of the script points that are supposed to move its Transform, and ensured that none of them are firing. There seems to be some "spooky action at a distance" going on, some rogue script doing something I don't want it to be doing, but I can't for the life of me figure out where it is. What I'd really like is some way to set a "breakpoint" on the object's Transform that will break me into the debugger when it gets moved by any script, but that doesn't appear to be supported. Is there any way to figure out exactly what it is that's moving my object around when it shouldn't be? (And before anyone says "trial and error, disable components and see when it stops moving," I already know exactly which component to disable to make it stop moving. Unfortunately, that isn't helping track down the problem because the movement isn't coming directly from that component's MonoBehaviour script.)
0
Step by step 3D Game Design in Unity My main question is related to 3D game design for Unity, but please let me introduce my idea so that you can understand what I really mean. I am very eager to develop an adventurous travel 3D game (Unity), where the main character is given some kind of task in country A and if he deals with it, he goes to the upper level, which is in another country and so on. I have never developed a computer game before. I have knowledge of c and a bit of java (for the programming part of the game). But I really don t know where to start with the design. I have to think of a main character, episodic characters, environment and distinctive buildings for each country in 3D (for e.g. The Eiffel Tower in Paris, The Colloseum in Rome, The Great wall of China etc. ). My question is where to begin with the 3D design of the characters, the cities and the buildings? Can you please give me step by step instructions so that I can do something good and meaningful? I know that Blender is a good option for 3D modeling, but is it the only thing needed for the 3D game design? I have experience with Adobe Illustrator, so can I use it to some extent in this case (for 3D game elements)? Can I use Illustrator then import it in Blender and finally import the Blender product in Unity? I accept every advice given. I really need someone to explain these things to me because for now I am really puzzled and not orientated from where to begin. Thank you!
0
Playing an animation relative to current Transform in unity? I have an animation created with the built in dope sheet. It plays correctly but I would like it to be played relative to current object transformation. For example I have a palm tree that moves its leaves. If I rotate the palmtree and then start the animation leaves does not play animation relative to its new position orientation. I know it is playing this way because of the animation being absolute. Is there any way to make it realtive to current transformation?. Thanks in advance.
0
Profiling unity games on Android devices I would like to profile our Unity mobile game on Android devices in a way similar to profiling Unity games on iOS with Instruments. I am aware of how to do this using Unity's profiler, I would however like to use a third party profiler for the following reasons to validate Unity's profiling data to have more visibility into how the app is running, including Unity's functions, etc. the largest lag spikes cause unity's profiler to run out of samples. I'm however very interested in precisely these spikes I'd like to have profile data for longer periods than unity records for I'd like to do analysis over time (not just detailed data for each frame, but also aggregated over a time span) Essentially I'd like as much visibility as possible to make Android on device profiling as comprehensive as possible. As close to Instruments on iOS as possible. So far I've tried with DDMS, but could only get visibility into Andoid OS functions and seeminly nothing in the actual apk at least nothing I recognised. I tried with mono2x and il2cpp, with all debug features that I'm aware of in build and player settings enabled. The game is developed with Unity 5,4 with Mono2x. All help is appreciated. I've listed my intents above, so even if profiling on device is not possible in this way on Andoid, alternate solutions to the listed intents are still very appreciated. Thanks!
0
Unity How to add a shader to a material via c script? I found already some things but those seem not quite what I need. (perhaps outdated functions?) https docs.unity3d.com ScriptReference Material shader.html here, it seems you can add a shader to a renderer using UnityEngine using System.Collections public class ExampleClass MonoBehaviour public Shader shader1 public Shader shader2 public Renderer rend void Start() rend GetComponent lt Renderer gt () shader1 Shader.Find("Diffuse") shader2 Shader.Find("Transparent Diffuse") void Update() if (Input.GetButtonDown("Jump")) if (rend.material.shader shader1) rend.material.shader shader2 else rend.material.shader shader1 well i dont have a renderer. i only have a material. and there is no "material.setShader" , only a material.setTexture" sooo can anyone solve this mystery of how to add a shader to a material via script?
0
Export Spriter animations to Unity I want to use bone animations in my 2D game for Unity (5.0 beta). I am trying Spriter. Apparently, it has no official Unity support. There was some guy, back in 2014, who posted a plugin to convert Spriter files to Unity prefabs here http brashmonkey.com forum index.php? topic 3365 spriter for unity 43 updated integrated . However, the plugin does not seem to work (perhaps it is because I am using 5.0 beta). There are deprecated lines, like AnimationUtility.SetAnimationType(animClip, ModelImporterAnimationType.Generic) Or UnityEditor.Animations.AnimatorController.AddAnimationClipToController(controller, animationClip) If you remove them, of course it won't be able to properly export your files. So my question is is there a reasonable to use Spriter animations in Unity? I know I could just export to a spritesheet, but I was hoping to use bones for super fluid animations (I have several characters so I don't really want to make lots of spritesheets). Or perhaps there is a better bone based solution for 2D animation in Unity?
0
How do I storing a Score in each level? I have a problem when I store the DistanceScore to text, the problem is why the DistanceScore always storing at text number 1, this happens when I play at level 2 which is the DistanceScore could be store in text number 2and so on, FYI I have 3 levels here. here the preview as you can see on the top of level 2 gameplay is distance so when i dead the distance saved and storing to text each level. and when I go to the main menu the Level 1text updated instead of Level 2. this is my script public Item item public int mapIndex public enum ITEM TYPE LEVEL public ITEM TYPE type private void Start() loadItemInformation() public void loadItemInformation() for (int i 0 i lt item.Length i ) if ( type ITEM TYPE.LEVEL) item i .bestScore.enabled true item i .distance.enabled true float distanceUi PlayerPrefs.GetFloat( quot distance quot i.ToString()) float value PlayerPrefs.GetFloat( quot Time quot i.ToString()) float minutes Mathf.FloorToInt(value 60) float seconds Mathf.FloorToInt(value 60) if (value 0) item i .bestScore.text quot No Record Yet quot else item i .distance.text quot Unstopable quot item i .bestScore.text quot Best Time quot string.Format( quot 0 00 1 00 quot , minutes, seconds) item i .distance.text quot Long distance quot distanceUi.ToString() System.Serializable public class Item public TextMeshProUGUI bestScore public TextMeshProUGUI distance here the distance script region Distance Header( quot Distance quot ) public Transform checkPoint public TextMeshProUGUI distanceText M GameManager GameManager private float distance private float highDistance float index endregion private void Start() GameManager FindObjectOfType lt M GameManager gt () checkPoint GameObject.FindGameObjectWithTag( quot Finish quot ).transform distanceText GameObject.FindGameObjectWithTag( quot DistanceTxt quot ).GetComponent lt TextMeshProUGUI gt () index (float)(PlayerPrefs.GetInt( quot Level quot )) typo here i call it set and now I've fix it index PlayerPrefs.GetFloat( quot Level quot ) distance (checkPoint.transform.position.x transform.position.x) if (transform.position.x gt checkPoint.transform.position.x) distance 0 PlayerPrefs.SetFloat( quot distance quot index, distance) if ( GameManager.isDead GameManager.isTimeout GameManager.fuelFinished) PlayerPrefs.SetFloat( quot distance quot index, distance) PlayerPrefs.Save() distanceText.text distance.ToString( quot F1 quot ) quot m quot and for item i .bestScore.text this work to storing each level but why for the distance not working.
0
How to smooth terrain to lower polygon count? I'm using Unity. I've created a simple Beach using Terrain editor. The problem is that Stats show me already a lot of Triangles only for Terrain renderer 40K . So my question is how can I create a Unity Terrain suitable for Mobile game ? How can I smooth terrain edge ? Thanks
0
Scaling Uma Character Unity 3d My room is bigger than my UMA character so on spawn my character looks tiny. I have found this link http answers.unity3d.com questions 988134 uma how to increase npc avatar scale.html but everywhere I put my code, it does not change my avatars features. Here is my code using UnityEngine using System.Collections using UMA public class UMACreator1 MonoBehaviour public UMAGeneratorBase generator public SlotLibrary slotLibrary public OverlayLibrary overlayLibrary public RaceLibrary raceLibrary public RuntimeAnimatorController animator Range(0.0f, 1.0f) public float bodyMass 0.5f private UMADynamicAvatar umaDynamicAvatar private UMAData umaData private UMADnaHumanoid umaDnaHuman private UMADnaTutorial umaDnaTutor private int numberOfSlots 20 void GenerateUMA() GameObject go new GameObject("MyUMA") umaDynamicAvatar go.AddComponent lt UMADynamicAvatar gt () umaDynamicAvatar.Initialize() umaData umaDynamicAvatar.umaData umaDynamicAvatar.umaGenerator generator umaData.umaGenerator generator umaData.umaRecipe.slotDataList new SlotData numberOfSlots umaDnaHuman new UMADnaHumanoid() umaDnaTutor new UMADnaTutorial() umaData.umaRecipe.AddDna(umaDnaHuman) umaData.umaRecipe.AddDna(umaDnaTutor) CreateMale() umaDynamicAvatar.animationController animator umaDynamicAvatar.UpdateNewRace() go.transform.parent this.gameObject.transform go.transform.localPosition Vector3.zero go.transform.localRotation Quaternion.identity void CreateMale() var umaRecipe umaDynamicAvatar.umaData.umaRecipe umaRecipe.SetRace(raceLibrary.GetRace("HumanMale")) umaData.umaRecipe.slotDataList 0 slotLibrary.InstantiateSlot("MaleFace") umaData.umaRecipe.slotDataList 0 .AddOverlay(overlayLibrary.InstantiateOverlay("MaleHead02")) umaData.umaRecipe.slotDataList 1 slotLibrary.InstantiateSlot("MaleEyes") umaData.umaRecipe.slotDataList 1 .AddOverlay(overlayLibrary.InstantiateOverlay("EyeOverlay")) umaData.umaRecipe.slotDataList 2 slotLibrary.InstantiateSlot("MaleInnerMouth") umaData.umaRecipe.slotDataList 2 .AddOverlay(overlayLibrary.InstantiateOverlay("InnerMouth")) umaData.umaRecipe.slotDataList 3 slotLibrary.InstantiateSlot("MaleTorso") umaData.umaRecipe.slotDataList 3 .AddOverlay(overlayLibrary.InstantiateOverlay("MaleBody02")) umaData.umaRecipe.slotDataList 4 slotLibrary.InstantiateSlot("MaleHands") umaData.umaRecipe.slotDataList 4 .SetOverlayList(umaData.umaRecipe.slotDataList 3 .GetOverlayList()) umaData.umaRecipe.slotDataList 5 slotLibrary.InstantiateSlot("MaleLegs") umaData.umaRecipe.slotDataList 5 .SetOverlayList(umaData.umaRecipe.slotDataList 3 .GetOverlayList()) umaData.umaRecipe.slotDataList 6 slotLibrary.InstantiateSlot("MaleFeet") umaData.umaRecipe.slotDataList 6 .SetOverlayList(umaData.umaRecipe.slotDataList 3 .GetOverlayList()) umaData.umaRecipe.slotDataList 3 .AddOverlay(overlayLibrary.InstantiateOverlay("MaleUnderwear01")) umaData.umaRecipe.slotDataList 5 .AddOverlay(overlayLibrary.InstantiateOverlay("MaleUnderwear01")) umaData.umaRecipe.slotDataList 0 .AddOverlay(overlayLibrary.InstantiateOverlay("MaleEyebrow01",Color.black)) Use this for initialization void Start () GenerateUMA() Update is called once per frame void Update () if(bodyMass! umaDnaHuman.upperMuscle) SetBodyMass(bodyMass) umaData.isShapeDirty true umaData.Dirty() void SetBodyMass(float mass) umaDnaHuman.upperMuscle mass umaDnaHuman.upperWeight mass umaDnaHuman.lowerMuscle mass umaDnaHuman.lowerWeight mass umaDnaHuman.armWidth mass umaDnaHuman.forearmWidth mass And here's the image. I want him to be as big as the chair
0
Unity3d iOS build where are the textures? First time building and running my Unity3D app on my iPhone and it appears that all the textures are missing. Everything is just a solid block of whatever color I made it. When running in Unity I see everything correctly. See images below. To complicate things I'm using custom shaders, and all the objects are custom procedural meshes. Quads that I build in script. If I switch the paper backplate shader to a built in shader I still only see white on the iPhone. So I suspect that somehow the textures just aren't making it to the iOS project. When I look in the iOS project I can't find any textures. Where would they be in the iOS project? For example in Xcode under Build Phases Copy Bundle Resources the only thing there is the Images.xcassets, which only contains the splash screens and icons. Surely I'm missing something simple. I tried renaming the folder where I keep my textures to "Textures". Also my textures are not built in to the shader but added programmatically like this void Awake () meshFilterComponent GetComponent lt MeshFilter gt () Material material GetComponent lt MeshRenderer gt ().material material.SetTexture(0, paperTexture) material.color new Vector4(1f, 1f, 1f, 1f) Where paperTexture is set up in the GameObject to point to the correct texture. Is there any way to force a texture to be part of a build? Let's say that you swap out textures in code, like swapping themes, how would you make sure they're all there to be loaded as needed? Running On iPhone Running In Unity3D
0
Unity Rendering Pass Before Refraction not showing In the documentation it states Before Refraction Draws the GameObject before the refraction pass. This means that HDRP includes this Material when it processes refraction. To expose this option, select Transparent from the Surface Type drop down. I have selected the Transparent option for surface type but the Before refraction rendering pass is not in the drop down list for rendering pass. How can I get it to be there? Are there some other option that might be disabling it?
0
how can you use playerprefs to save an array in javascript on unity As I stated I can't find a working answer anywhere else. I have a game where you are to draw out your own weapon and I'm storing that information in an array. How?
0
Emissive material from white texture I have texture with black and white shapes. I would like that white parts are emissive and black parts are transparent glass. How to make such material ?
0
How to develop custom Unity graphics? Processing is a Java library for working with computer graphics, providing methods by which to draw primitive objects, custom meshes, etc., as well as mathematical methods (such as Simple Harmonic Motion) by which to animate and control them. p5.js is an equivalent library for JavaScript and working with graphics on the web. You also have openFramworks which is similar but for C . How can you achieve similar graphics capabilities in the Unity Game Engine? Suppose, for example, I wanted to build a game like Duet. I can imagine how I might go about creating those graphics in Processing or p5.js, but not in Unity and C . How can you have that kind of creative freedom to build and draw in Unity? Thanks.
0
How to create a puzzle where the player needs to rotate hexagons to connect to the neighbors? I was researching different puzzle ideas and came across a game called Warframe that requires the player to hack a console to progress further into the level. The player has to spin around the hexagons (randomly generated, and get more difficult later on) to link up the connections to other hexagon neighbors. It's simple for the player to do, but also quite fun from my research. How can I create something similar to this? Edit To be more specific I would like to know how to generate a puzzle like below and how to check for successful connections. The graphics, animations, and player input I can handle. I suppose it's more about the algorithms to create the puzzle and then check the conditions. I couldn't figure out good search terms to find something similar. So even if someone can point me in the right direction, that would be helpful. I will be doing this in Unity C . Example of doing a puzzle.
0
Does it make sense to export and use skeletal animation as sprites? As tools like Dragonbones, Spine lets you export animations as both sprite atlas and skeleton data (JSON binary), I'm not sure which format to use when importing to Unity. I have few concerns Will there be any differences between the quality of the animations, when imported as atlas vs skeleton data? Any other pros and cons, using one over the other? If I use a sprite atlas, I don't have to depend on a third party runtime though. It is for mobile, so performance is also a concern.
0
Unity Deactivating Keyboard Input Interpolation I'm working on a game in Unity, and it is a little jarring to use with keyboard controls. I'm using the built in Input Manager, where I have a set of axes mapped to the left and right keys. When the player is using the keyboard instead of a joystick, I'd like it to simply be 1 when hitting left, 1 when hitting right, and 0 otherwise, but this isn't the case. I've found that for the first few frames of the button being held, Unity automatically builds up to the value for example, if I'm holding right, the value wouldn't go straight from 0 to 1, but rather from 0, to 0.25, to 0.5 and so on, continuously up to 1. Can I deactivate this? If so, how? Thanks in advance.
0
Manipulating an animation towards a target object (ie. The hand and arm lean towards the target) I am trying to make a boxing game just for fun (I dont expect the end product to be anything decent lol) . I have my boxers in the ring and they are animated quite well so far, with Idle, and punch Left and Right. They also rotate so they are always looking at each other. What I want to do is give the punch some aim towards the head. I will give the punch a set amount which it can move from the standard animation and move the hand bone in the direction of the targets head object. But I don't know how to do this S So far i have used dragged the 3 animation files into Mecanim and coded it to do the animations when a button is pressed. Is there a way to manipulate the animation in this way? (ie. actually make the arm reach towards the target object )
0
How to create fallout intensity on a generated mesh in Unity? So I was able to generate a circle mesh in Unity to basically see the other characters when they are inside of it, and hide the characters when they are outside of it, and partially hide and show the character if they are partially in or outside of it. Below is an image of what I was able to generate, but the thing is, the edges are very sharp and I would like to have some Fallout Intensity on the mesh. Just like with Lights in Unity, where they have a fallout intensity at the edge of the lights. Image of Generated Mesh As you can see, the edges of the mesh are very sharp and thats not the kind of effect am after, I would like to add some fallout to that, and adjust it. Here is The Code That Generates The Mesh using UnityEngine using System.Collections using System.Collections.Generic public class FieldOfView MonoBehaviour public float fieldOfView 360f public int numberEdges 360 public float initalAngle 0 public float visionDistance 8f public LayerMask layerMask private Mesh mesh private Vector3 origin private void Start() mesh new Mesh() GetComponent lt MeshFilter gt ().mesh mesh origin Vector3.zero private void LateUpdate() GenerateUpdateMesh() private void GenerateUpdateMesh() float actualAngle initalAngle float incrementAngle fieldOfView numberEdges Vector3 vertices new Vector3 numberEdges 1 int triangles new int numberEdges 3 vertices 0 origin int verticeIndex 1 int triangleIndex 0 for (int i 0 i lt numberEdges i ) Vector3 actualVertices RaycastHit2D raycastHit2D Physics2D.Raycast(origin, GetVectorFromAngle(actualAngle), visionDistance, layerMask) if (raycastHit2D.collider null) No hit actualVertices origin GetVectorFromAngle(actualAngle) visionDistance else Hit object actualVertices raycastHit2D.point vertices verticeIndex actualVertices if (i gt 0) triangles triangleIndex 0 0 triangles triangleIndex 1 verticeIndex 1 triangles triangleIndex 2 verticeIndex triangleIndex 3 verticeIndex actualAngle incrementAngle We form the last triangle triangles triangleIndex 0 0 triangles triangleIndex 1 verticeIndex 1 triangles triangleIndex 2 1 mesh.vertices vertices mesh.triangles triangles Vector3 GetVectorFromAngle(float angle) float angleRad angle (Mathf.PI 180f) return new Vector3(Mathf.Cos(angleRad), Mathf.Sin(angleRad)) public void SetOrigin(Vector3 newOrigin) origin newOrigin What do I do here to add some Fallout Intensity? All the help is really appreciated. And Thank you in advance.
0
Keeping a Character Controller grounded? I've got a character that makes use of isGrounded() to determine whether I can jump, whether my air jump is reset, and the amount of friction to be applied. I've run into a common problem, isGrounded() is fluctuating every frame returning true and false randomly resulting in jagged movement. The standard suggestion is to constantly apply gravity. Unfortunately, aside from any other more nuanced issues that this could result in, this only works for me if I apply so much gravity that I am no longer able to climb up slopes. I need a way to keep the character grounded without applying large amounts of gravity every frame.
0
Agents going to the same position So more often than not I have a case where two agents get the same destination vector3. This causes some hiccups because they won't be able to get to their target because they block for one another. I was thinking that I am not the only one who has faced this issue and was wondering what you guys do to fix such an issue? An example of this could be if I want my agents to go to the nearest tree and chop it down. Since both agents have the destination which is the trees transform they will go to the same position.
0
How to set "useGravity" for Rigidbody to entities in Unity For the position you can use this Inject private ComponentDataFromEntity lt Position gt position But cant use it for Rigidbody. How to access the parameters for Rigidbody for entities?
0
Issues with Flashlight Handle position with player rotation I want the flashlight to look same while looking up and down as when looking straight. Normal Position for Hand and flashlight Looking up and down, position is completely off More images for character camera prefab rotation Basically the position of the Hand held flashlight changes when I look up or down, as well as the arm stretches. How do I fix this? Code for character rotation private void CharacterRotation() float posX Input.GetAxis(mouseX) ((StructsInitializers.Sensitivity 5) StructsInitializers.Sensitivity 50) Time.deltaTime float posY Input.GetAxis(mouseY) ((StructsInitializers.Sensitivity 5) StructsInitializers.Sensitivity 50) Time.deltaTime yAxisClamp posY if(yAxisClamp gt 90.0f) yAxisClamp 90.0f posY 0.0f ClampYAxisRotation(270.0f) else if(yAxisClamp lt 90) yAxisClamp 90.0f posY 0.0f ClampYAxisRotation(90.0f) transform.Rotate(Vector3.left posY) PlayerBody.Rotate(Vector3.up posX) private void ClampYAxisRotation(float value) Vector3 eulerRotation transform.eulerAngles eulerRotation.x value transform.eulerAngles eulerRotation PS I am new to game developing. I have lack of experience.
0
How unity works on Web How Unity can work on Web if the code is written in C ? I understand that you can compile the C code to a shared library and use it in Java (for Android) in ObjectiveC (for iOS) to enable Unity on multiple platforms, but you cant use shared library on JS. Does Unity do language to language translation from C to JS to enable Unity on Web? As I understand now starting from Unity 5.0 it even doesn't use Unity Web Player.
0
How to generate mesh at runtime using raycast points? I'm trying to make a clone of the trail line renderer with the difference that everything is perfectly flat, i.e. the faces are not designed to face the camera. I'm using two raycasts to get the position of the edges of where I want those faces but now I'm struggling to generate the mesh...I've gone through the mesh docs but I don't really understand it. Could someone help me do this? Here is my code so far public Transform probes public float probeDistance public Vector3 newVertices public Vector2 newUV public int newTriangles void Update () Generating the mesh Mesh mesh new Mesh() GetComponent lt MeshFilter gt ().mesh mesh mesh.vertices newVertices mesh.uv newUV mesh.triangles newTriangles Defining the rays Ray l ray new Ray(probes 0 .position, probes 0 .forward probeDistance) Ray r ray new Ray(probes 1 .position, probes 1 .forward probeDistance) RaycastHit l hit RaycastHit r hit Debug.DrawRay(probes 0 .position, probes 0 .forward probeDistance, Color.blue) Debug.DrawRay(probes 1 .position, probes 1 .forward probeDistance, Color.red) Getting the position of the left ray point if(Physics.Raycast(l ray, out l hit)) print (l hit.point) Getting the position of the right ray point if(Physics.Raycast(r ray, out r hit)) print (r hit.point)
0
How to give a Jerk Effect when the player is moving left of right float amttomove Input.GetAxis("Horizontal") playerspeed Time.deltaTime transform.Translate (Vector3.right amttomove) Currently, I have above script in Update function to move the object to left or right.But this movement is way smoother.To give it more realistic feel, I want it to have a slight jerk when it stops moving to left or right and not just stop right there and then. What exactly needs to be done to have that effect?
0
Getting array of points shaping curve from 2 vector3 points What I want is to get path for DoTween method DoPath(), which as a parameter expects array of vectors shaping the direction of the path. I googled some stuff and found out nothing. Just think bezier curve is good idea but i dont even know how it works. Here is an ilustration of my problem The movement must be curved, don't need linear one. Thanks in advance
0
How to create a searchlight in Unity ? I'm trying to create a WW2 simple game and I'm experience issue creating the light emitted from a Flak Searchlight. The final lighting effect will be something like this http s1115.photobucket.com user k4kittycrew media K4KITTY3 Slide2 zpsfccf1590.jpg.html I know that it is called "volumetric light" and this is not supported by Unity. Thanks
0
Placing a gameobject with restrictions I am newbie in programming and I am making a tower defense game 2d. My problem is I want to make a restriction to place a tower only, if the mother tower is in place or within its range. I'm sorry if my explanation is a bit confusing. For example, you can oly place a certain tower within the range of the mother tower and only if that mother tower is placed. I don't exctly know if I have to create a function for this or create a range game object for the placement attached to the mother tower. Any help and tips would be appreciated, thank you. This is by the way unity C .
0
SpriteRenderer batching issue, with Z Position and Order in Layer I have two sprites (they look the same but with different colors) I want them to be positioned like on the image above, so there's a feel like blue is standing on the green one. There are two ways to achieve that Blue block with Order in layer 1, Green block with Order in layer 0 Blue block with lower Z coordinate, so it's physically in front of the green one. Both of the concepts appear to break batching between these two objects. They're on the same atlas (I've tested it by setting the same Z position and Sorting Order and batching works). How can I achieve batching here?
0
It lags when it collides. Help? ( I am trying (and believing) to make a game of pong. I have got a slightly decent working game. I haven't implemented the scoreboard or AI yet because I want the physics to work first. I am trying to reverse the direction of the ball when it hits either paddle just to make it work cleanly and am having the issue where it changes direction twice, it bounces off the paddle as expected and then goes in the opposite direction to when it hit the paddle . If anyone could help me, it would be much appreciated. using System.Collections using System.Collections.Generic using UnityEngine public class BallController MonoBehaviour private float randomNumber private float range private float pointOfContact private float paddleTop private float paddleBottom private float limits private int speed private int caseNumber private Vector2 direction private Rigidbody2D ballRigidbody void Start () Getcomponent finds the rigidbody of the attached object. ballRigidbody GetComponent lt Rigidbody2D gt () speed 5 caseNumber Random.Range (0, 2) range PickARange (caseNumber) ballDirection (speed, range) void FixedUpdate() void OnCollisionEnter2D (Collision2D coll) if (coll.gameObject.tag "Player" coll.gameObject.tag "Computer") pointOfContact ballRigidbody.position.y print (pointOfContact) ballRigidbody.velocity new Vector2 (ballRigidbody.velocity.x, ballRigidbody.velocity.y 1) void ballDirection (int ballSpeed, float yDirection) randomNumber (Random.Range (0, 100)) if (randomNumber lt 49) direction new Vector2(Random.Range ( 1.0f, 0.5f), yDirection) ballRigidbody.velocity (direction ballSpeed) else direction new Vector2(Random.Range (0.5f, 1.0f), yDirection) ballRigidbody.velocity (direction ballSpeed) float PickARange (int number) switch (number) case(0) range Random.Range (0.5f, 1.0f) return range case(1) range Random.Range ( 1.0f, 0.5f) return range default range 1.0f return range I thought to multiply the whole velocity by 1 but that just caused a loop because of the lag. Even though that's the right way to reverse the direction. I think. Thanks Peeps!
0
2D active ragdoll physics based procedural animation I'm trying to make a 2D quadraped robot stand and walk via physics. My robot looks like this. (art is not mine. Source is vapgames) It's rigged via Unity's 2D animation package and each joint bone has it's own collider rigidbody with the legs also having hingejoints connecting the lower part to the upper part and the upper part to the main body of the robot. I've also set up IK for both legs using the 2D IK package with the IK target being attached to their respective leg via fixedjoint and can be moved programmatically to move the legs with respect to IK. I want it to stand up, as at the moment is just falls and acts as a generic limp ragdoll. I've tried these methods Adding downward force to the legs via the IK targets Adding upward force to the torso Animating the IK targets to try and get the bot to stand up with animatePhysics enabled. All of these failed (downard force to legs did pretty much nothing, upward force to torso just made it float if there was no ground, animating the IK targets was too glitchy). I'm out of ideas on how to actually do this now. I've looked around for guides but there seems to be nothing good (I keep getting this suggested to me but it doesn't help. It's in 3D and the only thing that could help, spider legs, isn't finished and probably never will be) There's very little information on how to do this sort of stuff and even when I find people who know about active ragdolls they just say add force to the head (for a 3D active ragdoll), which I've already tried (see 2. on the list of what I've already tried) and don't explain anyt further. If anyone could help, that'd be great!
0
Oculus Rift DK1 and DK2 compatability issues For a project I need to make a multiplayer game using Unity and the Oculus Rift. My project works fine with the DK2 but it turns out the second rift is a DK1 and it won t work with Unity. I was thinking the best way forward would be to use an older version of the Oculus Runtime and Unity. Does anyone know what versions of Unity and the Runtime I need to have both the DK1 and DK2 work with Unity?
0
Getting "Non invocable member 'items.item' cannot be used like a method." when invoking a class I have my item class (items.cs) not attached to any gameObjects, I want to use items for all items in my game so I can use arrays as inventories. I have Stone.cs which is attached to a gameObject. On the line inv items.item(100f, "Stone", "Rock used for building") I get a compiler error Non invocable member 'items.item' cannot be used like a method. I am confused by this as I copied it from the Unity class tutorial, just splitting creating the item to another script. items.cs using System.Collections using System.Collections.Generic using UnityEngine public class items MonoBehaviour public class item public float iQuan public string iName public string iDesc public item(float iQ, string iN, string iD) iQuan iQ iName iN iDesc iD Stone.cs using System.Collections using System.Collections.Generic using UnityEngine public class Stone MonoBehaviour Use this for initialization public items.item inv public float iMax public float iCur void Start () inv items.item(100f, "Stone", "Rock used for building") Update is called once per frame void Update ()
0
How can I make an instantiation random? I'm trying to do it so when I have an instantiated an item upon the game starting, it is random as to whether it actually instantiates or not. Here's the code I have so far public GameObject anyItem void Start() Instantiate(anyItem, new Vector3(0, 0, 0), Quaternion.identity) Instantiate(anyItem, new Vector3(11, 0, 0), Quaternion.identity) How can I do it so these items (individually, not both together) are decided randomly as to whether they will actually be instantiated or not?
0
Component based programming with child objects I am presently working on a game in Unity3d and have come to a cross road regarding scripting for repetitive child objects. Should these child objects handle its own scripting for best practice? For example, I have a parent game object, Game Board, that spawns repetitive child objects, Tiles, on the board. Right now, I let these child objects handle its own position on the board and its own animation when the tiles move. However, I can just as easily do this with the parent object's scripting class. The reason I chose to let the child object do so is because I believe that child objects should be as independent to the parent object as much as possible. But since these are repetitive child objects, I start to wonder if it is just as easy to do all the scripting in the parent object. This way I decrease the number of class instances in the child objects. According the component based programming, which method is recommended?
0
Seams between tiled textured cubes I've created a textured cube in Blender, which I have uv mapped like this The tiles are 256x256, and I've mapped the coordinates exactly at the edges (e.g. x 256, y 512). I then export my model as an fbx file to Unity. In Unity, if I put many cubes adjacent to each other, seams appear between the cubes, like this I think I understand why this happens, because the uv coordinates are exactly on the edges, and thus two faces sample from the same points along an edge. I could solve this in some ways By making the uv tiles smaller, but it would look ugly with patterns. By adding some space between the tiles in the texture, and aligning the uv coordinates to them. My question is there a better proper way for achieving this? UPDATE So, about half a year later I still have issues with the seams. I've tried many things Start uv coordinates at 256.5 instead of 256, and so on... Turned of mipmapping. Set wrap mode to clamp. Set filter mode to point filter. Edge padded the texture atlas with first 4px, 8px, 16px, 32px. But still bleeding occurs at certain angles. Also updated the uv coordinates accordingly. Changed my atlas to be of Power of 2 instead, i.e. 1024x1024 instead of 1024x768. Set quot Non Power of 2 quot in Unity to None so Unity doesn't rescale my texture to nearest Power of 2. Set texture format to Automatic Truecolor instead of Compressed. With 32px edge padding it actually gets a lot better, but it still isn't perfect, I guess I could go on and try even more padding, but my textures will get bigger and bigger. I understand now that it is the mip levels that are causing the bleeding. At far distances I don't think this is a problem, but I can see this occuring just about 5 7 units away from the player, if the player is looking down. I believe there is something trivial about this that I'm missing. This is really a showstopper for me, forever grateful to the one who helps me solve this. Thanks in advance! This is how I have edge padded my texture (lines not visible on real texture), the problem does not only occur when the faces has such extremes distinct difference in colors as this one. It also occurs when the faces have patterns.
0
Unity I need to edit my prefab but I can't move anything inside it! I imported a character into Unity and turned him into a prefab. I couldn't get my custom "Look At" script to work for the eyes, which are children of the prefab I imported. So I opened the prefab and discovered (to my HORROR) that I am unable to transform his eyes AT ALL, even in the prefab view. It's like his body parts are made of stone, or something! I checked his eyes in the Blender scene and don't see any animation data attached to them. So how could this happen? How can I fix it? The eyes ARE children of a bone called "root", which I don't think has any keyframes in any animation. Further, all my bones imported as empties.
0
How to change AddForce code to MovePosition or SetVelocity? Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1f) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized targetPosition (camF vec.y camR vec.x) MoveSpeed Vector2 targetVelocity (targetPosition transform.position) Time.deltaTime rb.AddForce(targetPosition rb.velocity, ForceMode.VelocityChange) My problem is my character doesn't affects by the gravity when i changed my code from transform.position to rb.AddForce. I searched online and even asked here how to calculate gravity and add it to my character, nobody knew, so i think if i can change this code to rb.MovePosition or rb.SetVelocity maybe it does affects by the gravity?
0
How can I highlight words in a word search puzzle? For days I am struggling to implement the highlighting functionality in game as there is not much tutorial also for this. I did how ever make the cell of the grid change the material color but it looks ugly that's why I prefer to choose this method (see pic). How can I implement a highlighting method that will work the same on link. My try private bool first sel false private void Update() if (Input.GetMouseButton(0)) ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out pressed)) if (pressed.transform.tag "cell") if (!first sel) GameObject sel Instantiate(sel cell, new Vector3(pressed.transform.position.x, pressed.transform.position.y, pressed.transform.position.z 0.55f), Quaternion.identity)
0
Why is Vector3.MoveTowards only working on a single frame? I have three laptops in my scene and I am trying to bring them to front when I click on them. I am able to recognize which laptop is clicked by using the code below, but it doesn't move to the focus position in a single click it moves only one frame so I have to keep clicking it. void Update () if (Input.GetMouseButtonDown (0)) RaycastHit hit Ray ray Camera.main.ScreenPointToRay (Input.mousePosition) if (Physics.Raycast (ray, out hit)) if (hit.transform.name "Laptop 1") Debug.Log("Laptop 1 is clicked") Laptop1Trans.position Vector3.MoveTowards (Laptop1Trans.position, FocusPointTrans.position, moveSpeed) else if (hit.transform.name "Laptop 2") Debug.Log("Laptop 2 is clicked") else if (hit.transform.name "Laptop 3") Debug.Log("Laptop 3 is clicked") else I tried moving the move part to a method but still same behaviour. Are there any workaround?
0
Why one colorKey in ParticleSystem cannot be changed without a new Gradient? My question is partly a continuation of this question. So, why I can't change just one GradientColorKey this way (without replacing the whole Gradient instance) ColorOverLifetimeModule colorOverLifetime particle.colorOverLifetime MinMaxGradient color colorOverLifetime.color color.gradient.colorKeys 1 new GradientColorKey(new Color(1, 0, 0), 0.5f) colorOverLifetime.color color colorOverLifetime.color is MinMaxGradient struct, so I copy its value in a variable color. The colorOverLifetime.color.gradient property is Gradient class and there is no need to copy it. The colorKeys property is just an array of GradientColorKey struct. So, I assign a new GradientColorKey value to the array element that already exists. Why shouldn't this work?
0
Get all the gameobjects for a SceneManager scene in Unity I'm using the new SceneManager to load multiple scenes in the same structure adopting the Additive method. I find it extremely useful but I wonder if there is a way to get all the GameObjects for a specific scene. When multiple scenes are loaded I see the GameObjects clearly separated by scene in the hierarchy but I cannot find a way to access the specific hierarchy of a single scene via script. Is that possible? The findGameObject method I think returns the GameObjects for all the scenes..
0
Unity Lerping Following Camera is too slow I'm using this script to follow a game object in 2D public class CameraFollow MonoBehaviour ... void LateUpdate() Vector3 position target transform.position float targetX position.x float targetY position.y targetX Mathf.Lerp(transform.position.x, targetX, 1 m DampTime Time.deltaTime) targetY Mathf.Lerp(transform.position.y, targetY, m DampTime Time.deltaTime) transform.position new Vector3(targetX, targetY, initial z) I've set damping time to 2. But with this when the object's speed gets higher it can't follow anymore, it lags. Any suggestions or solutions ? Here is the current situation