_id
int64
0
49
text
stringlengths
71
4.19k
0
High poly vs Low Poly when creating model I am new in game development, but I have some knowledge in Maya and 3ds Max, I want to create pirate ship for game. So I spoke with many 3d artists and there are different opinions about low polygons and high polygons modelling. I am an iOS developer too so I know that it's hard for computer to process many polygons, so we should reduce amount of faces as much as we can. But my question is much more connected to 3D. Do I need to create low polygons model at start and then smooth it to increase amount of faces or do I need to create high polygons model and then reduce amount of edges, faces and etc?
0
How can use a 3D map with 2D characters (Unity)? I tried to search something about it but I can't find any complete or well explained tutorials about how to use a 3D map with 2D characters and items, like Ragnarok or Final Fantasy Tactics. If there is no tutorials about this topic, are there any recommendations for studying the subject? I've already developed some games using XNA, but only 2D games, I've never tried to use 3D models, nor have I used Unity to develop games.
0
Rotating fps rigid body on the Y axis I'm currently attempting to make a first person character using a rigid body. I am aware that the character controller exists, but I believe my game will be very physics based so it's better if my character is a rigid body. I currently can walk, and rotate the camera up and down with the mouse. I am now trying to rotate my character left and right with the mouse, but this requires me to rotate my rigid body, not just the camera. Here's my code so far. using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour SerializeField float walkSpeed 3 SerializeField float cameraSpeed 3 Vector3 direction float cameraX Rigidbody myRigidBody SerializeField Camera myCamera Start is called before the first frame update void Start() myRigidBody GetComponent lt Rigidbody gt () Update is called once per frame void Update() direction new Vector3(Input.GetAxis( quot Horizontal quot ), 0, Input.GetAxis( quot Vertical quot )) cameraX Input.GetAxis( quot Mouse Y quot ) cameraSpeed myCamera.transform.Rotate(new Vector3(cameraX, 0, 0)) void FixedUpdate() myRigidBody.AddRelativeForce(direction walkSpeed, ForceMode.Acceleration) I believe that the rigid body function I should use to rotate left and right is MoveRotation (I'm still new to rigid bodies), but I'm open to ideas. MoveRotation uses Quaternions, and I have no idea how to translate my mouse axis into a quaternion. Here's my question, How do i implement the Y rotation for my rigid body first person controller? Should I use torque, or somehow directly alter my rotation without using forces? Also, How do i translate the Mouse Axis into something I can use to rotate something? thnx. Edit I tried adding this line of code myRigidBody.MoveRotation(Quaternion.Euler(0, mouseX cameraSpeed, 0)) for some reason it has no effect on my character at all, but I feel Like it's on the right track. Why isn't this working? Edit 2 I added this line in Update rotateDirection new Vector3(0, Input.GetAxis( quot Mouse X quot ), 0) And this line in FixedUpdate myRigidBody.MoveRotation(Quaternion.Euler(rotateDirection)) Now when I move my mouse (I commented out my camera up and down movement to test) my character moves left and right for a tiny bit, but jitters back to it's original position, so It feels like I'm fighting it. The rotation in the inspector jitters in the correct direction, negative if i move the mouse left, positive if right, but only for a very small amount, 1.45 being the most, and then reverts back to zero. Also, it doesn't rotate smoothly, but jitters. Anybody know whats going on? Edit 3 changed it from addforce to addrelativeforce because that make it move forward based on local coordinates not global.
0
Unity Why do my 2 gameObjects 'share' materials? no one has answered this on Unity answers yet so I thought I might as well ask this here recently, I imported my .blend game character and the character consisted of 2 colors Red and black. Therefore as unity always does it creates 2 red and black materials for the colors of the character. Then, I imported the grass platform for my game. Because the grass platform is green and brown, Unity should have created 2 new green and brown materials and the platform should have stayed green and brown. But, instead, my grass platform decided to use my character's materials and my platform is now red and black. (If I import the grass platform first, my character becomes brown and green). Please help, this is an extremely annoying problem, thanks!
0
Move camera from wherever camera is to pinned point So, I need to switch move animate camera from point X (not point A,as I don't know where the camera is at that momemnt) to point B (place where you want your camera to move). This is for cinematics...like when you press a button in game which does something (opens doors maybe) but you can't see where nor what did you activate, so you show the player with the camera where and what happened. I tried to animate camera to position, camera just goes crazy. Then I tried to make an empty object placed at the position where the camera should be and move camera with code to that objects position. I tried enabling Camera 2 and disabeling Camera 1 but it just doesn't work. Enable Disable Code public var door DoorAnim public var triggered boolean false function OnTriggerEnter() triggered true function OnTriggerExit() triggered false function Update() if (triggered amp amp Input.GetKeyDown(KeyCode.JoystickButton1)) Debug.Log("Door 1 built") camera1 GameObject.Find("Camera1") camera1.enable false camera2 GameObject.Find("Camera2") camera2.enable true door GameObject.Find("door1") door.animation.Play()
0
Is there a way to check if an object is currently colliding with anything? I need to test from another Script on a different GameObject, whether a particular GameObject is colliding with anything (in particular using trigger). So, for my purpose, I don't need OnCollisionEnter OnTriggerEnter events, but I need something like this if ( myObject.isOnCollision ) do something How can I do this?
0
How to properly interact with game objects in Unity3D? I am trying to make a game where player will be placed in the scene and the goal is to explore it. He can interact with game objects that player can find in the environment, like picking object, examining, dropping and putting back. Basically it is something like first person exploration... So the problem is how to properly implement code regarding interaction. One way I see and saw it on the internet is Raycasting. So the idea would be to in Update() method place Raycast fire code and see what it hits. Also all game objects with which player can interact are placed on separate Layer and also limit length of Raycast (which is obvious thing to do as player cannot interact with objects that are like 10 meters from him)... So as I understand, game objects should have at least some kind of collider (I know box and sphere colliders are simple, but sometimes I will need to use more complex one)... That being said, I wonder is this right approach Separate layer for interactable objects Raycast that checks objects in that layer Raycast length limited to like 1 meter This approach should not be that much CPU consuming or is there any other way? I am also thinking to putting some invisible box area (trigger) where raycasting would make sense, but I am not sure will this be overhead or not.... So, at the end what would be the right approach to this?
0
Need help with physics 2D Unity I'm making a 2D game in Unity. Basically there's just a rocket that goes where ever the user touches. With the code that i have right now, the rocket instantly rotates towards the point and moves there straight. Vector3 dir targetPos transform.position float rotZ Mathf.Atan2(dir.x, dir.y) Mathf.Rad2Deg rb.MoveRotation( rotZ) thrust 10.0f rigidbody2d.AddForceAtPosition(transform.up Thrust, transform.up) This code is placed in the Update function. I want the rocket to start moving in which ever direction It's currently facing and slowly rotate towards the point as it goes there.
0
How to get the loudness of the real world environment using the device's microphone in Unity? I am trying to create a game where the character's movement is dependent on the loudness of the real world environment. So if the person playing the game screams or do something loud the character will move accordingly. What I need is a function returning the loudness of the real world environment and use it in the Update() to control the character. Is there such a function or if not how can I make one?
0
Unity3D Cancel a build process (Windows, Unity 5) I accidently pressed build for iOS and just realized that it might take a few hours to build the project. I tried to kill the unity process in the task manager, but on next start up unity instantly starts to build it again. Is there any option to cancel the build?
0
How can I plug a Unity application into native Android and native iOS? There are a lot of questions about running native Android and iOS code in Unity. I am trying to run Unity inside of native Android and native iOS apps. My problem is that I have two native apps, and I don't want to write code twice when I add a feature. I currently have two native apps one in Android and one in iOS. I am trying to write code once, and add it to both. Can I write a Unity program, and put that into my native apps? I am thinking something along the lines of writing a Unity Android app, building it as an Activity instead of an APK, and launching that Activity from the native android app. Then also the equivalent in iOS, whatever that may be. Does anyone know a solution to this problem?
0
Unity Blender models animations showing gaps As part of a college project, a member of my group has made some simple chests with an open animation. Importing these into Unity though, I instantly noticed there were gaps where the faces should be. After a bit of experimenting, I figured it was because the Normals were facing the wrong way. The outside seemed fixed, but faces were missing when the chest opens during its animation. I'm guessing the inside of the chest will need another layer of faces with the Normals facing the right way...? Though surely this would means having doubles...?
0
Download Progress bar from Firebase Storage Im trying to make a progress bar based on downloaded images from Firebase storage, now firebase does provide a snipper which works per image Create local filesystem URL string localUrl quot file local images island.jpg quot Start downloading a file Task task reference.GetFileAsync(localFile, new StorageProgress lt DownloadState gt (state gt called periodically during the download Debug.Log(String.Format( quot Progress 0 of 1 bytes transferred. quot , state.BytesTransferred, state.TotalByteCount )) ), CancellationToken.None) task.ContinueWithOnMainThread(resultTask gt if (!resultTask.IsFaulted amp amp !resultTask.IsCanceled) Debug.Log( quot Download finished. quot ) ) but i would like to make that appear on a UI text based on the percentage of the Bytes downloaded like starting from 0 to 100 .Now i have come to this function so far which does work in the sense of downloading from storage and i do get the percentage in the console but im not sure how to convert that to a percentage to show on UI. if (CheckConnectivity) if the device is connected to the internet, initiate download. Debug.Log( quot Initiating download of quot platform file) if (!File.Exists(localPath)) Task task storageRef.GetFileAsync(localPath, new StorageProgress lt DownloadState gt (state gt called periodically during the download Debug.Log(String.Format( quot Progress 0 of 1 bytes transferred. quot , state.BytesTransferred, state.TotalByteCount )) ), CancellationToken.None) await storageRef.Child( child).Child( file).GetFileAsync(localPath).ContinueWithOnMainThread(files gt if (!files.IsFaulted amp amp !files.IsCanceled) if download is successful. Debug.Log( quot file saved as quot localPath) else otherwise report error. Debug.Log(files.Exception.ToString()) ) else Debug.Log( quot files Exist quot ) else otherwise don't bother. Debug.Log( quot Cannot Download file due to lack of connectivity! quot ) in which case my debug is this Progress 1731 of 52804 bytes transferred. Which i would like to say 0 and counting up to 100! Thanks!
0
Handmade Terrain vs. Terrain Engine in Unity? I'm planning a game right now, to be made in Unity, and I'm trying to decide how I'll approach the basic level construction. Essentially, my game takes place on an island in an infinite ocean, very similar to Wuhu Island My question concerns all the stuff heightmaps can't handle. To use Wuhu Island as an example, note the lighthouse cliff, and the nearby similarly jutting out cliff. The volcano itself is also empty, and there are some tunnels through it on the other side. I was thinking I would just model the entire island myself in Cinema 4D, but as I read more about the terrain system, it seems Unity has special optimized rendering systems in place for terrain objects. Would I be shooting myself in the foot performance wise if I just built my island entirely by hand? This will be for mobile, so the little stuff might well count. Am I even approaching this question correctly if not, how would you best go about creating (something very close to) Wuhu Island as a level in Unity? Is there any reason for me to not do it as one mesh? I have effectively zero experience with 3D game dev only rendered 3D video stills for other applications, so this is a learning process.
0
Unity AudioClip lags when played My AudioClip is lagging when I play it in Unity3d. The AudioClip is supposed to play when you left click inside the game window. Steps I've tried for fixing it Uncompressing the .wav sound file. Setting the clip variable of an AudioSource to a clip and then playing the sound, but that's a different story. How the issue occurs When I start the game, on the first click it plays fine. But then after a few clicks, it starts slowing down and or lagging. This is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI RequireComponent(typeof(AudioClip)) RequireComponent(typeof(AudioSource)) public class GameProcess MonoBehaviour public Canvas Game public AudioClip explosion AudioSource beatBox Transform btn Vector3 canvasMin Vector3 canvasMax Vector3 pointerMin Vector3 pointerMax Vector3 pointerPos void Start () btn Game.transform.FindChild("Pointer") canvasMin Game.GetComponent lt Collider gt ().bounds.min canvasMax Game.GetComponent lt Collider gt ().bounds.max pointerMin btn.GetComponent lt Collider gt ().bounds.min pointerMax btn.GetComponent lt Collider gt ().bounds.max beatBox GetComponent lt AudioSource gt () void Update () if (Input.GetMouseButton(0)) beatBox.PlayOneShot(explosion) if (!(pointerMin.x lt canvasMin.x) !(pointerMin.y lt canvasMin.y)) if(!(pointerMax.x gt canvasMax.x) !(pointerMax.y gt canvasMax.y)) btn.transform.position Input.mousePosition else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0) else btn.transform.position.Set(pointerPos.x 1, pointerPos.y 1, 0)
0
Efficient way to implement a lot of singletons I just came upon programming patterns and learned about singleton. I'm in the process of creating my first game and it contains several managers I wanted to implement singleton on each of the managers,but the only way I can think is copy pasting the singleton pattern on each awake method script attached to each manager. Is there a more efficient way to do it rather than pasting the pattern on each awake method?
0
Position GUI Text in 2D game I am working on a 2D game, and my camera is a orthographic with a size of 320. I want to display some text, but not with OnGUI(). Rather, with a GUI Text game object. I couldn't help but notice that positioning my GUI Text object is a real pain apparently, the onscreen coordinates where the text appears range from 0 to 1. That is, 0.5 is the center of the screen. If I wanted to put my label at exactly (100,50) regardless of the screen size, I would have to calculate something like (100f Screen.width, 50f Screen.height) Is there a way to tell the GUI Text to appear at the actual transform position as it appears on the scene editor? Currently, if you move the GUI Text game object's transform slightly to the right, the rendered text will be displaced a LOT to the right instead...
0
Cutout fragment shader pixels arent square It has been solved, link to the final shader Shader The problem (as portrayed by the image below) is that the pixels seem to be, for lack of a better word, cut off. I wish to either display a pixel, or not. My fragment function, it uses the red value of the vertex colors (displayed by the image blow) on the edge of the mesh which are assigned during mesh generation to determine the pixel cutout "weight" by multiplying it with the texture. fixed4 frag (v2f i) SV Target fixed4 tex tex2D( MainTex, i.uv) if (i.color.r tex.r gt 0.4f) discard return fixed4(tex.rgb clamp(i.color.r, 0.3f, 1.0f), 1.0f)
0
Moving a character according to the animation, rather than code I'm using 3ds Max to export character animations in which my character is moving. I expected this to mean that the character will move in Unity, but it doesn't... For example, if my animation (in 3ds Max) moves my character forward for a second, from 0,0,0 to 1,0,0, in Unity, the character snaps back to 0,0,0 once the animation ends. Is there a way to change the position of the character according to the animation, without something like CharacterController.Move?
0
Why does my Unity animator state "finish" before the visible motion does? Example The TopAppearing motion boost the alpha of the sprite from 0 to 1 for total of 2 seconds After TopAppearing state has been finished The TopAppearing's transition settings Question Why is the Top's sprite alpha 235 after the TopAppearing animatior state has been finished?
0
Spatial Jitter problem in large unity project I have a very large environment where i am getting very weird view of objects as picture given below As you can see there are black lines spot, maybe the vertex lit problem. Currently I am using Standard specular shader. Remember this problem is only occuring at the end of the project (away from origin like position 17000, 0, 144) As a workaround i tried to change my shader to Unlit and i found this shader Shader "Unlit UnlitAlphaWithFade" Properties Color ("Color Tint", Color) (1,1,1,1) MainTex ("Base (RGB) Alpha (A)", 2D) "white" Category Lighting Off ZWrite Off ZWrite On uncomment if you have problems like the sprite disappear in some rotations. Cull back Blend SrcAlpha OneMinusSrcAlpha AlphaTest Greater 0.001 uncomment if you have problems like the sprites or 3d text have white quads instead of alpha pixels. Tags Queue Transparent SubShader Pass SetTexture MainTex ConstantColor Color Combine Texture constant This shader has almost solve the problem but i have to tweak and set colour of each object as be default it is not according to my expectation.
0
ScreenToWorldPoint and ViewportToWorldPoint I'm currently following tutorials on Youtube to learn howto use Unity. My code runs perfectly as per the tutorial, but i just have some questions regarding the code, with regards to screenToWorldPoint amp viewportToWorldPoint. The purpose of the code is for a 2D platformer, where the character's arms will rotate and face where the mouse cursor is. Code using System.Collections using System.Collections.Generic using UnityEngine public class ArmRotation MonoBehaviour public int rotationOffset 0 Update is called once per frame void Update () Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position Gets the difference between difference.Normalize() Normalizing the vector float rotateZ Mathf.Atan2(difference.y, difference.x) Mathf.Rad2Deg transform.rotation Quaternion.Euler(0f, 0f, rotateZ rotationOffset) I've done some googling and am aware of the difference between screenToWorldPoint and viewportToWorldPoint as per the answer here https answers.unity.com questions 168156 screen vs viewport what is the difference.html Where Screen from 0,0 to Screen.width, Screen.height Viewport from 0,0 to 1,1 Questions Why do we have to calculate the difference between the position of the mouse cursor and the position of the character's arm instead of just setting the following . Vector3 difference Camera.main.ScreenToWorldPoint(Input.mousePosition) I've tried setting it to the position of the mouse cursor instead of using the difference between the arm amp the cursor and while the code still works and the arm is still able to rotate, it is a little "off" from the direction of the cursor. E.g A little higher than where the cursor is. Why does using the difference solve this issue? Why do we call difference.Normalize() ? To my understanding, Normalize returns a vector between 0 amp 1.However, Mathf.Atan2 returns the angle in radians whose Tan is calculated by y x. As such, calling Normalize and returning a vector to a value between 0 amp 1 makes no difference because the value calculated will be the same between a un normalised and normalised vector since the proportions are the same? When i use ViewportToWorldPoint instead of ScreenToWorldPoint, i do not use Normalize because to my understanding, the Vector returned by ViewportToWorldPoint should already be within 0 amp 1, hance we do not have to normalise it. However, when i test the code out in play mode,the arm barely rotates. Why is this so? I would appreciate any help or pointers in the right directions. Thanks! EDIT I had a look at the manual and realise that Normalize() returns a vector with the same direction, but magnitude 1, but i'm still just as confused
0
How do I expose a field with a generic class to the Inspector? I have some utilities implemented as generic classes. I would like to have fields of these types exposed to the inspector but they appear to not display. This test code Serializable public class TestGenericClass lt T gt public string testField public TestGenericClass(T testValue) testField testValue.ToString() Serializable public class TestNormalClass public string testField public TestNormalClass(string testValue) testField testValue public class MonoBehaviourClass MonoBehaviour public TestGenericClass lt string gt testGenericClass new TestGenericClass lt string gt ("generic") public TestNormalClass testNormalClass new TestNormalClass("normal") Produces this result As you can see the field for the generic class is missing. How can I expose a field with a generic class to the inspector?
0
Help understanding IEnumerator Move routine I have this code and I know what it does (it will move an object up and down) But I don't know how its elements work. Could someone please explain it to me? IEnumerator Move (Vector3 Target) What this IEnumerator do? while (Mathf.Abs ((Target transform.localPosition).y) gt 0.1f) Vector3 Direction Target.y Top.y ? Vector3.up Vector3.down Is this an if else? and if yes why if target.y top.y its first choice is vector3.up? transform.localPosition Direction 5 Time.deltaTime yield return null yield return new WaitForSeconds(1f) Vector3 newTarget Target.y Top.y ? Bottom Top Same line but result order is different ?.? StartCoroutine(Move(newTarget))
0
Generate 4 vectors rotated in cardinal directions from a central vector There is some unit vector, which is a coordinate in a spherical space. It is necessary to obtain from it 4 vectors diverted in different directions (right, left, forward, backward) by a certain number of degrees. For these actions I use the following code Vector3 center point Vector3 left Quaternion.Euler( 30, 0, 0) center Vector3 right Quaternion.Euler(30, 0, 0) center Vector3 back Quaternion.Euler(0, 0, 30) center Vector3 front Quaternion.Euler(0, 0, 30) center The problem is that this works when point is equal or close to Vector3.up. When deviating from the vertical position, the lateral vectors begin to "stick together". Here is a visualization of what I need Test code is attached using System.Collections using UnityEngine public class Test MonoBehaviour public GameObject centerGO public GameObject leftGO public GameObject rightGO public GameObject backGO public GameObject frontGO ArrayList list new ArrayList() void Start() SetCenterPoint(Vector3.up) void Update() DrawDebugRays() Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) SetCenterPoint(hit.point) void SetCenterPoint(Vector3 point) Vector3 center point Vector3 left Quaternion.Euler( 30, 0, 0) center Vector3 right Quaternion.Euler(30, 0, 0) center Vector3 back Quaternion.Euler(0, 0, 30) center Vector3 front Quaternion.Euler(0, 0, 30) center centerGO.transform.position center leftGO.transform.position left rightGO.transform.position right backGO.transform.position back frontGO.transform.position front list.Clear() list.Add(center) list.Add(left) list.Add(right) list.Add(front) list.Add(back) void DrawDebugRays() for (int i 0 i lt list.Count i ) Color color Color.red switch (i) case 0 color Color.green break case 1 case 2 color Color.blue break Debug.DrawRay(Vector3.zero, (Vector3)list i , color)
0
Unity 4 mecanim 'Quaternion to Matrix conversion failed, input quaternion is invalid' I'm trying to animate a stick figure in Unity, with placeholder animations. Character is built animated in Blender, exported to FBX. When imported to Unity, everything appears correct in the editor. All animations are imported, and i can preview them normally. I set up the "rig" section of the model import to use generic rigging. This creates the avatar which is used in mecanim. I set up a simple "walkForward" animation, and setup mecanim parameters to get it called when the player moved forward all that works. The animation is called at the right times. However, during play, as soon as any animation is started on the avatar, the model disappears, and a flood of error messages appear in the console, stating Quaternion to Matrix conversion failed because input Quaternion is invalid 1. IND00, 1. IND00, 1. IND00, 1. IND00 1 IND00 I'm not altering the animation with any scripts of my own, it's all mecanim. Is there a setting i'm missing? I'm using Unity 4.3.0.0f4, building exporting my mesh with Blender (latest).
0
Is Unreal engine or Unity better for high graphics low file size mobile games? My objective of learning game development is to make a 3d relatively high graphics mobile game but that should be in 150 mb. I don't know should I start with unity or unreal engine. I found that people say unreal engine is better for 3d games and unity is better for mobile game development. As I have no experience, can anyone suggest me an engine with some reasons?
0
Unity Editor stops updating ScriptableObjects if I click away from them in editor I'm trying to be better about structuring my code, and I think I'm doing it right. The issue I've got right now is I need to get joystick inputs, scale those values appropriately, and then use that scaled data on any number of MonoBehaviour scripts. I'm trying to split the input conditioning from the end user, and I'd like to do that by using a ScriptableObject to hold the conditioned data. I was thinking that a MonoBehaviour script would run, get the joystick data, scale it, and then push that data to variables in the ScaledJoystickData ScriptableObject. Later, a second MonoBehaviour script would access the variables in the ScaledJoystickData and use those to move the things in the game. I'm understanding the benefits of structuring the code this way, especially in that I can access the ScriptableObject from the editor and manipulate those values I don't actually need to have a joystick connected, and I'm free to test either end of the input handling independently. The problem is that, if I am looking at the ScriptableObject instance in the editor, it stops updating as soon as I click away from it (to the consuming GameObject). If I click back to the ScriptableObejct instance, none of the values update. Nothing on the GameObject's script updates unless I start the game with that GO selected in editor, and again THAT fails to update if I click off and click back. The GameObject script is currently using the values from the ScriptableObject instance and piping them to public variables, and the public variables aren't updating. Is there some bug with ScriptableObjects, or am I doing this wrong? EDIT Here's an example. Make a script called "ExampleSO" and replace the contents with using System.Collections using System.Collections.Generic using UnityEngine CreateAssetMenu public class ExampleSO ScriptableObject public float stashedVar 0f Make a script called "ExampleWriter" and replace the contents with using System.Collections using System.Collections.Generic using UnityEngine public class ExampleWriter MonoBehaviour public float scaling 2f public float scaledInput 0f public ExampleSO exampleSO null Update is called once per frame void Update() if(exampleSO! null) scaledInput scaling (Input.GetKey(KeyCode.LeftArrow) ? 1f 0f) exampleSO.stashedVar scaledInput Make a script called "ExampleReader" and replace the contents with using System.Collections using System.Collections.Generic using UnityEngine public class ExampleReader MonoBehaviour public float display 0f public ExampleSO exampleSO null void Update() if(exampleSO! null) display exampleSO.stashedVar Create an instance of the ExampleSO, add the ExampleWriter to a game object, and put the ExampleSO instance into the ExampleWriter slot. Highlight the game object holding ExampleWriter and run it. Push the left arrow key and see the value toggle 0 2. Click the ExampleSO instance. Nothing is happening there now. Click back on the game object, and now it doesn't update either. If you have the ExampleReader on the same game object then it won't work at all. ExampleReader will read fine, if you have it on a separate GameObject, but again if you click off and click back then it stops responding.
0
GetComponentsInChildren() raises error I have a gameobject to which a script is attached. In this script I have the following code foreach (GameObject g in this.GetComponentsInChildren lt GameObject gt ()) BagItem nBagItemScript g.GetComponent lt BagItem gt () if (nBagItemScript ! null) Bounds nBounds Helpers.BoundsFromGO(g) Vector3 nPos new Vector3((nBounds.size.x 2) nBounds.center.x, mapHeight (nBounds.size.y 2) nBounds.center.y, 0.01f) g.transform.localPosition nPos I thought this code was fail safe, but Unity outputs the following error message ArgumentException GetComponent requires that the requested component 'GameObject' derives from MonoBehaviour or Component or is an interface. UnityEngine.GameObject.GetComponentsInChildren GameObject (Boolean includeInactive) (at C buildslave unity build Runtime Export GameObject.bindings.cs 133) UnityEngine.Component.GetComponentsInChildren GameObject (Boolean includeInactive) (at C buildslave unity build Runtime Export Component.bindings.cs 88) UnityEngine.Component.GetComponentsInChildren GameObject () (at C buildslave unity build Runtime Export Component.bindings.cs 98) Bag.pUpdatePositions () (at Assets Bag.cs 173) Bag.Update () (at Assets Bag.cs 107) Can somebody tell me which error Unity C is choking on here? Is the error really in this line foreach (GameObject g in this.GetComponentsInChildren lt GameObject gt ()) ... or perhaps somewhere else? Thank you very much!
0
Keeping an object constrained to a 2d radius based off of the camera A few weeks back I posted a question about keeping an object on the screen. What I would like to do now is clamping an object around a 2d radius based on the camera. I'm need this for a reticule for this on rail shooter I've been making. (like that of starfox) Here is the current code I am using Vector3 movementx transform.TransformDirection(Vector3.right Input.GetAxis("Mouse X") aimSpeed) Vector3 newPosx transform.position movementx Vector3 offsetx newPosx centerPt.position transform.position centerPt.position Vector3.ClampMagnitude(offsetx, radius) the same for the y axis The problem with this set up is that I'm restricting it around 3 dimensional objects base off their locations in the world. (this is restricting the players movement towards the edges not letting the player to move the reticule to the side) So this is what I've tried Vector3 screenPosition Camera.main.WorldToScreenPoint(transform.position) Vector3 shipOnScreen Camera.main.WorldToScreenPoint(Ship.position) Vector3 movementx transform.TransformDirection(Vector3.right Input.GetAxis("Mouse X") aimSpeed) Vector3 newPosx screenPosition movementx Vector3 offsetx newPosx shipOnScreen transform.position shipOnScreen Vector3.ClampMagnitude(offsetx, radius) the same for the y axis This just seems to send the empty (which the ship is pointing at) off some where else in the world I cant even tell if I'm moving it or if its just moving with the parent object. (I've tried different variations with this moving the screenPosition swapping it with the transforms position in world space to no avail) My guess is that its not converting 2d space to 3d space when I try to clamp a 3d object within that radius. I would like to keep my reticule at an empty point on the screen and not replace it with the cursor. Edit Okay i have now thought up a new system that still needs some work. Having an empty object next to the reticule. With this I cut out the need for a 2d radius but I need this object object follow the ship on on the screen with taking in account the perception of the camera. I have taken a measure of the height and width of the camera. Its not too exact but it should do. So i guess I would like to know how the coordinate system on the camera is set up. like where is (0, 0) update Okay I've found a way to do this but it took a quite a bit of math on my part and a bit of estimation on my behalf. The way I've set it up is that I moving the pivot the same way I'm moving the ship only I'm multiplying it times the proportion of distance the ship can move side to side vs the distance the pivot can move side to side. I still have not built in an equation that will allow me to move the point farther back with more accuracy but this is a good temporary fix and if i really have to move it I'll i do the math again. but I would still like to have the equation of the rate of change. I'm not that brilliant at related rates. If you want to see my math I noted it down. but if i can have an equation out of this it would work perfectly while changing ship distance (constant) (61.6209, 27.5131) first measure distance 100 point A distance (320.5, 143.1) 5.20115872075484 y multiplier 5.200473802917458 x multiplier so the multiplier at 100 5.2 distance 50 point B distance (192.0436, 85.74551) 3.11633 y multiplier 3.11633 x multiplier so the multiplier at 100 3.11633 Rate of change (5.2 3.1165) (100 50) ROC ROC 0.04166934 mt 0.042 y No idea x distances from ship 0.042 Oh in case your wondering how i got my measurements I measured the distance manually with points.
0
Recursively calculate possible pathway on a grid depending on max walk distance I have a character that is placed on a grid. It has a variable maximum walking distance. Grid fields can be walkable or not walkable. As the character may has to walk around certain not walkable fields to reach his destination his maximum walking distance isn't allways represented by a circle. See these examples Without obstacles, walking distance 7 With obstacles, walking distance 7 Note how the obstacles affect the players maximum walking distance To calculate this i've written this recursive function static Vector2Int GetWalkableFields (Vector2Int position, int steps) List lt Vector2Int gt walkableFields new List lt Vector2Int gt () if (steps gt 0) foreach (Vector2Int v in GetNearbyFileds(position)) if (m mc.IsInBounds(v) amp amp m mc.IsWalkable(v.x, v.y)) walkableFields.Add(v) walkableFields.AddRange(GetWalkableFields(v, steps 1)) return walkableFields.ToArray() else Vector2Int v position return v And this function, that returns all four neighbour fields of a field public static Vector2Int GetNearbyFileds(Vector2Int position) Vector2Int neighbors new Vector2Int 4 neighbors 0 new Vector2Int(position.x, position.y 1) neighbors 1 new Vector2Int(position.x, position.y 1) neighbors 2 new Vector2Int(position.x 1, position.y) neighbors 3 new Vector2Int(position.x 1, position.y) return neighbors The function is called with the players position and maximum walking distance (steps) and get's the four neighbour fields and unless the steps are zero calls itselve for every neighbour field with the maximum walking distance decremented. As you can see in the screenshots, this works absolutely fine. The problem is, as the calculation not only goes away from the player but, in some recursion paths, goes back and fourht between tiles until stepcount zero is reached without even having traveled one field, that this way of calculating the path is really resource heavy. For a walking distance of 7 there are 27646 possible walkways that all are getting calculated. If a player is able to walk 11 fields the calculation takes a few seconds, if he can walk 12 fields Unity crashes while calculating. Is there a way to calculate this more efficient? Thank you in advance.
0
Chess engine stock fish process for mobile I am making the chess interface I designed for a game. I am using the process to get answers from a stock fish binary stockfish new Process StartInfo new ProcessStartInfo FileName System.IO.Directory.GetCurrentDirectory () " Assets Scripts Stockfish stockfish.exe", Arguments "", UseShellExecute false, RedirectStandardOutput true, RedirectStandardInput true, RedirectStandardError true, CreateNoWindow true The problem I face is it worked for my Windows build but for mobile package build it won't work with the executable. Is there a way around it?
0
Offscreen arrow indicator appears only when the user go near to the object I have placed four gameobject at different place.And I have a player and have applied movement to it through keyboard control.I have added script for arrow indication towords this gameobject.But the problem is that,the arrow appeaar only when the user go near to the gameoobject.I need the arrows to appear on the screen so that the user initially know where the gameobject is placed on the scene. Here is the code for onscreen arrow.I have attached this script to each gameobject public Texture2D icon The icon. Preferably an arrow pointing upwards. public float iconSize 50f HideInInspector public GUIStyle arrow GUIStyle to make the box around the icon invisible. Public so that everything has the default stats. Vector2 indRange float scaleRes Screen.width 200 The width of the screen divided by 500. Will make the GUI automatically scale with varying resolutions. Camera cam public bool visible false Whether or not the object is visible in the camera. void Start () visible GetComponent lt SpriteRenderer gt ().isVisible cam Camera.main Don't use Camera.main in a looping method, its very slow, as Camera.main actually does a GameObject.Find for an object tagged with MainCamera. indRange.x Screen.width (Screen.width 6) indRange.y Screen.height (Screen.height 7) indRange 2f arrow.normal.textColor new Vector4 (0, 0, 0, 0) Makes the box around the icon invisible. void OnGUI () if (visible) Vector3 dir transform.position cam.transform.position dir Vector3.Normalize (dir) dir.y 1f Vector2 indPos new Vector2 (indRange.x dir.x, indRange.y dir.y) indPos new Vector2 ((Screen.width 2) indPos.x, (Screen.height 2) indPos.y) Vector3 pdir transform.position cam.ScreenToWorldPoint(new Vector3(indPos.x, indPos.y, transform.position.z)) pdir Vector3.Normalize(pdir) float angle Mathf.Atan2(pdir.x, pdir.y) Mathf.Rad2Deg GUIUtility.RotateAroundPivot(angle, indPos) Rotates the GUI. Only rotates GUI drawn after the rotate is called, not before. GUI.Box (new Rect (indPos.x, indPos.y, scaleRes iconSize, scaleRes iconSize), icon,arrow) GUIUtility.RotateAroundPivot(0, indPos) Rotates GUI back to the default so that GUI drawn after is not rotated. public void OnBecameInvisible() visible false Turns off the indicator if object is onscreen. public void OnBecameVisible() visible true How can I make the arrows to appear on the edges of the screen
0
How can I keep the drawn lines instead deleting them? using System.Collections using System.Collections.Generic using UnityEngine public class DrawLines MonoBehaviour private Transform startMarker, endMarker public GameObject waypoints private float speed 2f private float startTime 0f private float journeyLength 1f private int currentStartPoint 0 private LineRenderer lineRenderer public void StartInit() currentStartPoint 0 SetPoints() lineRenderer GetComponent lt LineRenderer gt () lineRenderer.startWidth 0.2f lineRenderer.endWidth 0.2f void SetPoints() startMarker waypoints currentStartPoint .transform endMarker waypoints currentStartPoint 1 .transform startTime Time.time journeyLength Vector3.Distance(startMarker.position, endMarker.position) void Update() if (waypoints.Length gt 0) float distCovered (Time.time startTime) speed float fracJourney distCovered journeyLength Vector3 startPosition startMarker.position Vector3 endPosition Vector3.Lerp(startMarker.position, endMarker.position, fracJourney) lineRenderer.SetPosition(0, startPosition) lineRenderer.SetPosition(1, endPosition) if (fracJourney gt 1f) if (currentStartPoint 2 lt waypoints.Length) currentStartPoint SetPoints() else if finished, disable lineRenderer and this script lineRenderer.enabled false this.enabled false Each time it's drawing a line between two waypoints but then the line is deleted and then it's drawing a new line between the next two waypoints. Instead I want it to draw one line between all the waypoints. And to keep the line in the end not to delete it.
0
Are there still favored of using bluetooth devices today in modern games for multiplayer gameplay? I was wondering. Most multiplayer gameplay always favored by Wi fi during team up or to compete each other. I know that when in comes in huge groups (say 100 to 500 players or more online) in online games whether it's cooperation or battle, most players relying on Wi fi to play in very huge group. What if some persons wants to play in small groups and can be played offline (like in racing games or fighting games for example) using smartphones via bluetooth? The question is that are there most game apps for multiplayer gameplay still favored or popular of using bluetooth when playing in a very few no. of players (let's say only two players) on a certain game? Also, is it possible to create a game app for iPhone or any smartphones that run on Android that features bluetooth for multiplayer via Unity 3D game development software?
0
Physics.CheckSphere() appears not to work in Unity My scene is simple, I have a single GameObject with the following script attached usings ... public class GalaxyManager MonoBehaviour public int numberOfStars 300 public int maximumRadius 100 public float minDistBetweenStars 2f void Start() for (int i 0 i lt numberOfStars i ) float distance UnityEngine.Random.Range(0, maximumRadius) float angle UnityEngine.Random.Range(0, 2 Mathf.PI) Vector3 cartPosition new Vector3(distance Mathf.Cos(angle), 0, distance Mathf.Sin(angle)) if (!Physics.CheckSphere(cartPosition, minDistBetweenStars)) GameObject star GameObject.CreatePrimitive(PrimitiveType.Sphere) star.transform.position cartPosition else i Update is called once per frame void Update() What this is supposed to do is generate 300 quot stars quot within the maximumRadius of 100 that are separated by at least minDistBetweenStars. I haven't been able to figure out what's actually happening sometimes the check finds a collider and sometimes it doesn't. It's almost as if the CheckSphere() check is happening before the stars get placed via the star.transform.position cartPosition. I'm very new to Unity and appreciate the help. Anyone have any idea what's going on? edit Some more information, I've tried the script in both 2020.1.12f1 and 2019.4.14f1 to no avail. I'm also aware that this will lead to an infinite loop if it can't find a placement.
0
Unity how to switch between ratios in a Scene View? I'm complately new to Unity, but I know what's going on, I've made some games with LibGDX earlier. In GDX, to handle all resolutions perfectly I always create 5 different sets of backgrounds (cause they have to be perfectly sized) and I place UI widgets on percentage for each ratio independantly (hardcoded values). I was just checking what's the ratio on runtime. As we know, there are only 5 possible aspect ratios for mobile devices (I target mobile only). Now, when I started using Unity, the first thing I looked up was how devs handle ratios. I found some scripts in the web, which add pillarboxes which in my case is unacceptable. So I thought ok, let's do it my way, and make it for all aspect ratios. And my question is Is there any option in Unity, which will allow me to 'switch' in the Unity Editor between ratios and the 'Scene View' will understand this and resize? What I want to do is to create a 16 9 with the editor, then switch to 5 3, adjust elements for it, and remaining ratios too. To be clear, I don't mean the 'preview', when you check the desired device and it shows how the game will look like. Any help and tips are appreciated! )
0
Is it possible to interpolate different sprites? I can interpolate different animations based on position, rotation, and scale. I want to do the same for different sprites, automatically. For example, lets say I have a soda can being crushed. I have 2 sprites One is the soda can uncrushed, and one is the soda can fully crushed. I want to only use those 2 sprites, and have Unity automatically transition from the normal can to the crushes can. How can I do this without making a bunch of key frames in between?
0
Rotate on one axis, but visibly keep the other axes stable and editable It's been a long two weeks. Quaternions are freaking complicated. I've managed to make a few baby steps towards finishing my project, but I've hit a brick wall and could use a few of your beautiful minds to help me past it. I'm making an asset for Unity that will automatically rotate shift objects to make them appear 2.5D. What I'm having trouble with is the rotation part. I go through a trigonometric process to get a calculation of how much, between 0 and 180 degrees (typically), that the object should rotate on its x axis. The rotation of this object should be locked between 0 and 180 degrees. Think of it this way my trigonometric calculation is telling me whether the object should be flipped right side up or upside down So, we've got the angle it should rotate. Just plop it in a Quaternion.Euler(MyNewXValue, prevEulerY, prevEulerZ) and we should be good, right? WRONG. There are a number of things wrong with this. The previous eulers can come back a bit wonky since they can correspond to multiple values in the 360 to 360 degree range, so we have to "normalize" them a bit. Due to the rotation order, it ends up "swirling" in 3D space and altering the other two rotations instead of maintaining a stable x axis rotation change. With that said, here is my code C if (current euler.z lt 180f) rot Quaternion.Euler(rotation angle.x, current euler.y, current euler.z) else rot Quaternion.Euler(rotation angle.x, current euler.y 180, current euler.z 180) Ignore the (if lt 180). That's just so I can get this test running and working. I'll find a proper way to normalize it later. Anyway, this snippet works, but has one problem It twirls in 3D space and doesn't remain locked on its x axis. I've tried numerous other solutions, but they either spin out of control or... they all spun out of control. My question Is there a way to set the rotation by rotating on one axis, while allowing the other rotations to change at the user's command without it "swirling" in 3D space? EDIT SOLUTION For my use case I was able to use transform.localScale and modify it's Y scale as a solution to my issue. It has the exact effect as I was looking for, and is definitely more stable. I accepted Lunin's answer, however, as it seems to be another possible solution, and is written on this forum ). To clarify, my wish was to rotate a 2D object on its x axis, which would cause it to rotate vertically. At the same time, I wanted to allow the other axes to be editable at any given time. I can mimic a vertical rotation by changing the y scale of the 2D object. 1 y scale is normal, 1 y scale is flipped upside down. Since I only needed that one axis to change, this workaround worked perfectly.
0
In Unity shaders, how is IN.worldRefl calculated? I want to know how the world reflection vector in shaders is calculated so that I can manipulate it, but there is no documentation on what it does or how Unity calculates it. How is the reflection vector calculated and exactly what does it do?
0
Real Time Speech Verbal Communication with a Mecanim Character What would be the simplest method of integrating real time verbal communication within a mecanim character that is already being used in a Unity app project? Something like an SDK or toolkit? I have such a character that is animated by a motion capture device, so the user puts on the suit and the Unity character is driven by receiving live motion data. This is the non verbal part for research in Social Sciences amp Psychology. I tried integrating the Virtual Human Toolkit into my Unity app to use its real time speech amp lip sync amp facial gestures, but their character is set up in a complicated way, so I still cannot animate it by using my motion capture device. So, now I am thinking what is the next best thing to do with a Unity mecanim character to make it say something, etc...?
0
How could I make the player's movement more responsive? I am working on an Air Hockey game I tried making the movement physics based, by doing this using UnityEngine public class Player MonoBehaviour private Rigidbody m Rigidbody private float HorizontalInput private float VerticalInput public float Speed 1.0f private void Start() m Rigidbody GetComponent lt Rigidbody gt () private void Update() HorizontalInput Input.GetAxisRaw( quot Horizontal quot ) VerticalInput Input.GetAxisRaw( quot Vertical quot ) private void FixedUpdate() m Rigidbody.AddForce(new Vector3(VerticalInput Speed, 0.0f, HorizontalInput Speed),ForceMode.VelocityChange) and by adding a PhysicsMaterial to the MeshCollider attached to my player The movement should be quick and responsive, but it feels rather sloppy and unresponsive I also tried using Input.GetAxisRaw(...), but the controls become quite clunky. How can I improve on this? Is there a go to way to do this type of movement in Unity? (I would like the final version of the game to be played on controllers)
0
Prefab can't accept script created material I am doing mod support for my game. I want users to be able to change materials of any prefab in the game. In order to achieve that, I create a new material from the imported data and then apply it to an existing prefab. However, it does not work. It works if I try to assign the newly created material to an object on the scene (not a prefab) and it works if I try to assign an existing material to a prefab. However, assigning a new material to a prefab results in this I am fairly certain that is exactly the issue since it can be reproduced as easily as with this snippet of code GameObject prefab Resources.Load( quot Prefabs Cubes IceCube quot ) as GameObject prefab.GetComponent lt MeshRenderer gt ().sharedMaterial new Material(Shader.Find( quot Standard quot )) What am I doing wrong? How can that be worked around?
0
Why is the player not showing up on UI when connecting to server? I want to create a playerList, that whenever a player joins server, his her name will show up on a list in UI. But currently the names are only showing up on the Client host side. Below is my NewtworkManager code. lobbyPlayerList is just a UI element with VerticalLayoutGroup. lobbyCharacter is just UI textElement with a networkBehavior script that sets the text field value and also has newtworkIdentity and networkTransformation. public struct PlayerInfo NetworkMessage public string name public class LobbyManager NetworkManager public GameObject lobbyCharacter public GameObject lobbyPlayerList Start is called before the first frame update public override void OnStartServer() base.OnStartServer() NetworkServer.RegisterHandler lt PlayerInfo gt (CreateLobbyCharacter) public override void OnClientConnect(NetworkConnection conn) base.OnClientConnect(conn) PlayerInfo info new PlayerInfo name quot Test quot conn.Send(info) private void CreateLobbyCharacter(NetworkConnection conn, PlayerInfo info) GameObject gameobject Instantiate(lobbyCharacter, lobbyPlayerList.transform) gameobject.GetComponent lt LobbyCharacter gt ().SetText(info.name) NetworkServer.AddPlayerForConnection(conn, gameobject)
0
Controlling a balance wheel using a Unity script I am working on a small demonstration project with Unity like this (screenshot from footage below). I don't want to use Unity physics, which is too heavy. I plan to create a rotation function with ratio params for gears. But I am not sure how to control the balance wheel rotation like that video, I tried animation tools which is hard to make the acceleration like real physics.
0
How can I get game objects and prefabs to recognize modifications in enum values from scripts in the scene window I have made a script with several properties and enums that I attached to an empty game object. I am making changes to the values within the inspector, since they a public. How can I get the scene window to recognize these changes as they occur?
0
Moving Object Interception Projectile Collision I am using Unity to attempt to have missile A launch at incoming missile B and blow it up. However in order to do this accurately, A must be able to take into account B's current velocity, direction and distance in order to calculate where it needs to aim in order to succesfully hit it. How do we go about this using the below as an example?
0
OnMouseDown() and Collision not working for game object created within another game objects script I have created a game object (Brick) and added a script (BrickScript) to it. Within this script I create a Window game object if a certain condition is satisfied. Please see code below if (hasWindow) if (window null) var size gameObject.GetComponent lt SpriteRenderer gt ().bounds.size window (GameObject)Instantiate (Resources.Load ("Prefabs OtherPrefabs Window"), new Vector3 (transform.position.x 0.5 size.x, transform.position.y 0.5f size.y, transform.position.z), Quaternion.Identity)) window.name gameObject.name "Window" nbsp The Brick and window game objects actually overlap a bit. I realized that when hasWindow true (the window is created) the condition in the code below is not satisfied and other game objects don't collide with the Brick. But when hasWindow false (the window is not created), everything seems to work well. How can I solve this? void OnMouseDown () if (Input.GetMouseButtonDown(0)) Debug.Log ("touch down") hasBeenTouched true
0
How do I ensure consistent behaviour when using Unity's Collider2Ds for triggers and collisions? I am experiencing inconsistent behavior using Unity's 2D Physics engine and their Collider2Ds to detect collisions and triggers on my projectiles. I will classify it into two problems. The first is that occasionally the projectile will pass through walls objects it should collide with. The second is that occasionally the projectile will pass through enemies that it should hit without triggering. I will try to elaborate in detail below. A projectile is organized into a container Projectile GO and two children GO a PhysicsColliders GO and a HitBoxColliders GO. The PhysicsCollidersGO job is to hold the colliders that define the solid regions of the projectile using Collider2D components. It's GO is on a Projectile layer which is set to collide with other solid layers such as the ones my walls are on. Walls are static colliders. The HitBoxCollidersGO job is to define the a HitBox area. It's GO is on a HitBox layer and also uses Collider2D components that are set to be triggers. A HitScript on the GO listens for OnEnterTrigger. Projectiles are set in motion by setting the velocity of the RigidBody once upon firing. Here is a visual of the structure ProjectileGO PhysicsCollidersGO HitBoxCollidersGO Here are descriptions of the GameObjects and their components ProjectileGO RigidBody2D Component (collisionDetectionMode is set to Continious) PhysicsCollidersGO (Layer is set to Projectile) BoxCollider2D Component HitBoxCollidersGO (Layer is set to HitBox) BoxCollider2D Component (IsTrigger is set) HitScript Component Problem 1. Projectiles will sometimes not collide with walls solid objects etc... Problem 2. Projectiles will sometimes not trigger a hit. What could be causing these inconsistencies? How can ensure that collisions and triggers will consistently behave correctly?
0
Null Reference to camera when loading new scene I am getting the error MissingReferenceException The object of type 'Camera' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. The camera in my game contains a persistent object script, which prevents the camera from being destroyed when loading a new scene. private void Awake() DontDestroyOnLoad(transform.gameObject) The scene is switched via a method in the GameManager public void loadScene(UnityEngine.Object arena) operation SceneManager.LoadSceneAsync(arena.name) state GameState.LOADING and finally the camera contains another script which adds a distortion effect void OnRenderImage(RenderTexture source, RenderTexture destination) distortCam.CopyFrom(mainCam) Error occurs here distortCam.backgroundColor Color.grey ...Some more code ... The error occurs in this last method, but the camera still exists in the editor. mainCam is a Camera object that is assigned onAwake via mainCam GetComponent lt Camera gt () Also if I switch the loadScene method to public void loadScene(UnityEngine.Object arena) operation SceneManager.LoadSceneAsync(arena.name, LoadSceneMode.Additive) state GameState.LOADING it works perfectly, but it is inconvenient to always have to loadScenes additive. Why is the reference to the mainCam being lost? I have tried to check if it's null and reassigning it before using it, but so far I still have the problem. Any ideas?
0
Sprite button not triggering "On Click()" event Unity Hi have created some buttons from sprite and I added image and button components on it. I am just using sprites because In my game the camera can be moved on x and y. But I don't want my button to move and since UI buttons move with camera that is why I am not using them. Here is the GIF to explain the scene
0
How to automatically destroy a gameobject after a method or block of code In Unity I frequently find myself doing this in C GameObject myObject new GameObject() try do something with that object finally Destroy(myObject) A good example is creating a temporary pivot point for another object. I create the object, parent whatever object I want to rotate, do the rotation, then destroy the object. It's in a finally block so in case anything goes wrong it still destroys the object. Does Unity have any elegant way to do this? Writing this all the time is tedious, and it's easy to forget the Destroy method at the end.
0
Using Unity Post Processing v2, how can I apply processing effects to just the UI? I am using Unity 2018.3 with HDRP 4.9, and Post Processing 2.1.3. I would like to apply post processing effects (i.e bloom) to the UI only. I tried the 2 camera approach, but still can't get it working correctly. I have a post processing volume that is global, and also one that is global but for the UI. Not sure if this is correct. Basically I don't want the first processing volume to apply to the UI. I can apply post processing if I ignore all this second camera stuff and set the canvas to screen space camera. I then get the effects like bloom applied to the UI. However, I want to have different post processing for the UI, the global bloom is too much. First image is the UI Camera. Second image is the main camera. Third image is the Canvas for the UI.
0
SerializeField vs GetComponent Efficiency As far as I know, there are two built in ways to get an instance of a component in Unity. 1 Serialize the field and drag in the component manually in the editor SerializeField private MyScript script 2 Using MonoBehaviour's GetComponent method script GetComponent lt MyScript gt () I would think that it is more efficient to drag the component in the editor lest making the engine illiterate through every component in the GameObject to find the component. Is it more or less efficient to drag the component in the editor compared to using GetComponent? Or does Unity find components in a different way or dragging components in the editor is handled in a different way such that it would be more efficient to use GetComponent? Would using one over the other have any impact on performance in the real world? A similar question would also be raised regarding GameObject.FindGameObjectWithTag() vs dragging in the editor. As far as optimization go, should you use one method over another?
0
When creating an FPS style game, how should the iron sights be setup? I am working on creating an FPS style game for learning purposes. I previously was using self created animations for aiming down the iron sights of a gun. The animation would play when you zoom to iron sights and it would hold it there as long as you have the mouse held down. However, talking to a high rated designer, he told me usually it is done with a second camera that sits perfectly aligned with the guns iron sights. I would imagine you would still have to have an animation that then transitions you into that iron sight camera though. Now my animation works fine but I feel I may run into a problem later down the road if I am approaching it the wrong way from the start. Can someone verify the right way to do this and explain why it is?
0
Synchronize running code over the network Unity I want my code to run perform the same on different Unity clients. I don't know if this is hard to achieve. Here hare my problems The enemies movement I have a pathfinding that should always give the same results on server and on clients. Because I use the same pathfinding algorithm on server and client, and the position the algorithm chooses is synchronized with a network transform. But it does not give the same results on client and on server. Bullets make enemies die over all clients I have a script with OnTriggerEnter2D(Collider2D collision) that never gets called at the same moment on clients and server. The clients might miss touching a bullet on an enemy on server but not on a client. So in server enemies died and on client they have not. How to synchronize OnTriggerEnter2D() ? I will update the question to improve it with more examples when I find them.
0
unity2D Top Dow Mobile rigibody2D im using this code for my 2D TopDown mobile player movement.but when i move player With UI Image buttons player keep moving.it didnt stop.and also player starting of move he is very slow. the he accelerate his speed.how can i fix this. i add BoxCollider 2D and Rigibody2D my sprite.the set Gravity to 0. this is my code. public class PlayerScript MonoBehaviour public float speed 150f float hInput void FixedUpdate() Move (hInput) public void Move(float horizontalInput) if (horizontalInput.Equals(1)) rigidbody2D.AddForce (Vector2.right) if (horizontalInput.Equals(2)) rigidbody2D.AddForce ( Vector2.right) if(horizontalInput.Equals(3)) rigidbody2D.AddForce (Vector2.up) if(horizontalInput.Equals(4)) rigidbody2D.AddForce ( Vector2.up) public void StartMoving(float horizontalInput) hInput horizontalInput
0
Should my terrain be one big mesh or several medium ones? While creating a subterranean level with probuilder (irregularly shaped rooms and corridors), I was wondering if I should merge all "terrain" meshes into one or keep them as separate meshes? What are the good practices ? I'm creating each room as I go and its not hard to create openings and align doors vertices (with progrids) but once I start moving them around (like with polybrush) I'm sure it will soon be a nightmare. I can see pros and cons for both. Separate meshes would be easier to edit, duplicate or replace, probably better performances but at the risk of overlaps or holes because it would get hard to keep connected cleanly. I guess with one mesh you take the risk of having it eat memory and computation time, or having it too big to edit easily. I settled on each mesh consisting of a room and all half corridors going out of it, to hide the stitching and keep it simple. Still I wonder if there's a consensus.
0
How do I get the InputManager to recognize a certain axis Vector2D with a Vive motion controller? Right. So basically I want to map the Vive motion controller touchpads (certain locations) to the certain inputs in Unity's InputManager. How do I do this? Like I want a certain area on the touchpad to equate to forwards backwards in the InputManager. How would I do this? I am not seeing a way to do it natively. Long story short I'm wondering if I can use the Vive with the InputManager or not.
0
Problem connecting to Steamworks via Facepunch.Steamworks I'm using Facepunch.Steamworks (https github.com Facepunch Facepunch.Steamworks) to connect my Unity game to Steam. The login seems to work fine. The board object is an FP class, and AddScore is a call to the library to send the score to Steam. I have the boards set up on Steam, and they come out with IsValid true. Here are the output and the code. The boards currently have no data in them, so I don't think it's because the score isn't beating an existing one. xxxxxxxx Standard Normal True Fail public void SubmitScore(Globals.ApplicationMode mode, Globals.SkillLevels skillLevel, int score) int index GetLeaderboardIndex(mode, skillLevel) if(index 1 !IsSteamPlatform()) return Leaderboard board m leaderboards index Debug.Log("xxxxxxxx") Debug.Log(board.Name) Debug.Log(board.IsValid) board.AddScore(true, score, null, AddScoreSuccessCallback, AddScoreFailureCallback) private void AddScoreSuccessCallback(Leaderboard.AddScoreResult result) Debug.Log(result.Score) private void AddScoreFailureCallback(Facepunch.Steamworks.Callbacks.Result result) Debug.Log(result.ToString()) Here's a shot of the leaderboards on the Steam control panel. They seem in order their "Writes" attributes are false so that the client can submit to them directly.
0
How to make a class diagram and data model of a Unity3D game? I'm developing a 3D platformer video game on Unity3D and I've been asked to present its UML class diagram and data model. If I'm not mistaken Unity uses an entity component system, which necessarily doesn't use heritage. How would a class diagram from a Unity game look like, in that case? Also, I've been taught that usually data model refers to entity relationship models that represent a database. In the case my game doesn't use a database, how could I diagram the way the player's data is store on the game? I'm storing the player progress on a file in the user's computer.
0
Unity Smooth player input direction when changing camera Preface I'm very new to Unity. I'm working on an exercise using fixed cameras like how they work in the PSX final fantasy games. I have the camera scripts working fine but it's an aspect of the character control that I'm struggling with. My character moves relative to the cameras facing position, but when the camera suddenly changes to another angle, my running direction instantly and abruptly changes too. In the final fantasy games it sort of keeps going roughly in the same direction you were briefly. input new Vector2(Input.GetAxis( quot Horizontal quot ), Input.GetAxis( quot Vertical quot )) input Vector2.ClampMagnitude(input, 1) get camera direction need to add something here for in between camera switches! camF Camera.main.transform.forward camR Camera.main.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized transform.position (camF input.y camR input.x) Time.deltaTime 8 I saw someone with a similar game comment on an article with his solution, but I don't quite know how to put it into code. The quote quot Player just gets a rotation based on where the camera is looking and multiplies the character s motor force by that .forward and .right. I only update that rotation after a big delta in input so you can smoothly move between shots. quot This is his small (online) game which he's talking about, I'm trying to mimic the movement basically https ocias.com games foggy shore Can anyone give me some pointers? Updated It doesn't quite play how it does in the demo game, but it's getting there. input new Vector2(Input.GetAxis( quot Horizontal quot ), Input.GetAxis( quot Vertical quot )) input Vector2.ClampMagnitude(input, 1) if (!cameraChanged) lastCameraInput input camF Camera.main.transform.forward camR Camera.main.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized else if (Vector3.Dot(input, lastCameraInput) lt 0f) cameraChanged false transform.position (camF input.y camR input.x) Time.deltaTime 8
0
Prediction of collision place and time in Unity I have two moving objects. I have chosen trajectories for objects that they would definitely collide if they don't change speed or trajectory. Is there easy way to check at which point and time the objects will collide with given parameters (current object positions, their velocity vectors and speeds or any other parameter accessible from Unity)?
0
Gameobject not destroyed OnCollisionEnter I have this GameObject with the tag coin I am trying to destroy when the player collides with it using this code located in a player script attached to the player public void OnCollisionEnter(Collision col) var hit col.gameObject if(hit.tag "Coin") Destroy(hit.gameObject) However upon collision nothing is happening
0
All sides shadow outline in Unity NGUI How can I make such exactly the same shadow using NGUI?
0
Switch UNet From LocalHost to IP I have set my game up so that I can run one instance as host and one instance as client and I see two people in the room. How do I get from that setup to another computer (as client) connecting to mine (as host) without matchmaking. I understand I will need a static IP, and have set my router up for port forwarding (I tested it with an FTP server application I made). I am specifically asking for what options you select in the Unity NetworkManager to do this. Here is my current NetworkManager (I erased the last number in my IP so I dont get DDos)
0
Unity animation transition with 0 Exit Time doesn't transition immediately Question Why doesn't an animation transition with an Exit Time of 0 immediately transition to the next state? Minimal example Using Unity 2018.3, I set up an AnimatorController with two states Initial and Next. I wanted Initial to transition to Next immediately, so I tried setting an Exit Time of 0. However, this doesn't transition immediately As shown above, Initial state still runs instead of transitioning immediately to the Next state. (There is no Motion attached to the AnimationState, so perhaps it's using a default duration.) Below are screenshots of my animation transition settings. Strange behaviour with small non zero ExitTime I also tried using an Exit Time of 0.01 (i.e. transition after 1 of the animation has played), and it transitions almost immediately as I expect most of the time. However, occasionally it will still play the Initial state In this case, even though it transitions to Next immediately most of the time, it still occasionally waits for the Initial state to complete. (It happens much less frequently than the image above suggests, but the issue becomes more frequent if I set the ExitTime even lower, e.g. 0.003). Workaround From searching online, the recommended solution for immediate animation transitions seems to be to turn off Exit Time and use a condition (e.g. bool or trigger) to transition immediately instead. (Edit in my case, I've defined an animator bool parameter called ImmediateTransition and set it to true by default instead of using Exit Time 0.) This seems to work, but I would like to better understand how Exit Time works and why it's not working the way I expect.
0
How should the physics be on an halfpipe like in a skate game in Unity? I am making a inline skating game. My player is skating based on the normals of the surface of the ground. But when I skate up a halfpipe it flies in the Air but doesnt comes down like it should be, it changes position in the Air and my player falls horizontally on the ground I cant get up anymore like this when he is lying on the Ground. I want it to be physically jump up and come down again the player should align on the ramp again not just fly in the air and drop down on the ground? What infos should you need to answer this question properly I will edit the question then?
0
Collision not smooth in unity3d I am working on a project(Racing car). When it hit an object the object should be destroyed. The Object is being destroyed when it is hit, but the car stops for a moment after hitting like an obstacle. How can I make this smooth, like the object is there and it is destroyed on collision but the car moves with the same speed? Script attached to the object void OnCollisionEnter(Collision col) Destroy (gameObject) Nothing needs to stop or slow down. It doesn't need to exert any physical force. Thanks.
0
Does Unity for PC use Direct3D or OpenGL? I am a mac developer using Unity and I hardly use a PC. When you build a Unity game for Windows, does it use Direct3D or OpenGL? P.S. I'm not sure if it's called Direct3D or DirectX
0
How to scale our multiplayer support, similar to Among Us We are a small team with the goal of creating our first multiplayer game, and we want to support multiplayer that can rapidly scale up as Among Us has successfully done. We don't have a huge budget and we are struggling to find an appropriate way to implement multiplayer, including peer to peer (although it would be exhausting to combat cheating and make a smooth experience). Our game has no more, no less than 50 players in a very tight space. As an example, we're looking at the indie game Among Us. They went from such a small game with barely any players, to maintaining well over 3 million CCU (concurrent users). How can we achieve similar scalability?
0
Exporting WebGL For Mobile Browsers I was asked by a client to create a pretty simple 3D game that will be embedded on a website, a plain landing page that will contain the game and will be played on mobile devices. The game itself has no complexity whatsoever, not in the functional aspect and not in the lighting shaders aspect the basic functionality is a simple finger swipe in order to quot throw quot a ball. I have checked and concluded that opening a webGL game on mobile devices might cause issues and only high end devices can run the game smoothly. My question is Is there a go to solution or any solution in which I can develop the game on Unity and build it for webGL in a way that it will be compatible with mobile devices? Or my only option is to develop the game using plain JS?
0
Procedural planet to sphere texture I'm making a 4x space game. I have a procedurally generated galaxy with planets in 3D space. The view is above the planet plane at 45 dec y up i.e 45 deg isometric. I procedurally generate the planet surfaces on a hex grid which can be viewed 2D 2.5D when clicking on the planets, ala GalCiv etc by placing meshes for mountains, seas, forest and so on on the hex grid. For realism, I'd like the textures of the planets when viewed from space to (at least roughly) mirror the view you get in the surface view. I'm struggling to think how this might be achieved in Unity. I figure I could create a render texture after generating the planet's surface and store it on the users HD. This has a few problems though taking up HD space and not mapping well to a sphere (unless I always make the poles a uniform colour, which doesn't look good as the rest of the surface is quite highly detailed). Another idea would be to create many generic textures for the space view of roughly each type of planet generated (blue green large continent archipelago etc) and select a texture which most closely fits the procedurally generated map at run time. As long as the same texture isn't used for planets close to each other and the user doesn't compare the 3D view with the 2D view to closely then hopefully they won't notice! So, any other ideas of how this might be achieved? I'm not looking for code, just a brainstorm of how I might get a procedural 2D map to be represented on a 3D sphere, or at least create a convincing illusion.
0
How can i set OnClick equal to UnityEvent The Problem I'm making a dialogue system for a small 2d rpg. I Have a Dialogue class with two lists for pages and responses. The response class has a UnityEvent so i can use the ui in the inspector to set methods like a button. Then in a DialogueManager class i have a Show() method which makes a button for every response in the list from Dialogue. The problem is when i try to set the created button's OnClick() event to the UnityEvent in the response. The Question So the question is how can i set the button's OnClick() to the methods in the UnityEvent from the response?
0
Unity Visual Effect Play() has no effect I am making my first visual effects, and I make effect, when my ship is flying. So I am want to play it only when the ship is actually moving. I would suppose it's easy, you call Play(), it will play. You play Stop() it will stop. But when I call play, nothing happens. public void Update() ship.Rotate(Input.GetAxis( quot Horizontal quot )) var move Input.GetAxis( quot Vertical quot ) ship.Move(move) if (move gt 0) FlyEffect.Play() FlyEffect.SetVector3( quot Velocity quot , new Vector3(0, ship.Speed move, 0)) else FlyEffect.Stop() When I let in Initial Event Name OnPlay, it is playing as it should be. But nothing from the script... What I am missing here?
0
Prefab instantiate or create gameobject at runtime? I'm developing a skill system for a client server game, all available player's skills server send to it, then client load it and put it to a spellbook. So I stuck in loading stage, how for performance and or memory will be better Save all spells in a bunch of prefabs and then just instantiate them Create JSON binary etc file, parse them and create a gameobject at runtime From the side of editing, both methods are equal.
0
Restrict render in Blender is not working I click "Restrict renderability", so that everything except the item I want to export is grayed out. However, it still exports lights and everything when I import it into Unity. How can I fix this?
0
How do I get the networkId of an object? My clients have a way of spawning "defense" barriers and I would like to limit the number of defense barriers per client to 1 A way of doing this is to destroy the old defense (if any) and then spawn the new one. Since this defenses are spawned by the server, how can I tell the server to destroy only the defense that was created by that client? I guess that by storing the networkID of the spawned defense I can later tell the server to destroy it and repeat. Am I attacking this right? Having this Command void CmdDefenseSpawned(string playerID, string PlaceToDefenseName, Vector3 toDefense, Quaternion defenseRotation) Debug.Log("Player " playerID " placed a defense on " PlaceToDefenseName " Position " toDefense) GameObject defenseInstance Instantiate(defense, toDefense, defenseRotation) NetworkServer.Spawn(defenseInstance) I would like something like this NetworkInstanceId defenseInstanceNetId defenseInstance.NetworkIdentity.netID So I can later delete the object whenever the client wants to spawn it again.
0
Understanding pixel art in Unity 2d I am struggling to understand the basics behind pixel art in Unity. I understand what a unit is, and that if I draw my sprite with 16x16 pixels, I should set PPU to 16. Take stardew valley for example, in the image below you can clearly see that the player is not square. The creator of the game said he made everything in 16x16, but then how is there so much detail in the characters? Surely you do not patch several 16x16 squares together to make a character (as you would with a tilemap)? What is the "common" way of dealing with things that are not square, like the characters in the image. Do you just make 16x32 sprite and set PPU to 16? Wont that make it look a bit weird next to 16x16 sprites? Do you generally pick one size (i.e 16, 32, 64) And then stick to that for everything in the game? The visual Issue I've seen is this, where a 32x32 sprite looks very out of place (too sharp) next to a 16x16 sprite. So I am wondering, how do you mix sizes wihout getting this effect where one image looks much sharper than the other. If I for example wanted a character to be 16x32, or any non square value, when my tiles are 16x16
0
Unity keepy uppies game Hello guys I'm tryting to make a game in unity of keepy uppies but I can't make the ball bounce to different directions like keft and right only staright up. using System.Collections using System.Collections.Generic using UnityEngine public class physics MonoBehaviour public Rigidbody rb public float force 10 void Start() rb.velocity new Vector3(0, 0, force) void Update() if (Input.GetMouseButtonDown(0)) RaycastHit hit Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit, 100.0f)) if (hit.transform ! null) PrintName(hit.transform.gameObject) if (rb hit.transform.GetComponent lt Rigidbody gt ()) LaunchIntoAir(rb) private void PrintName(GameObject go) print(go.name) private void LaunchIntoAir(Rigidbody rb) rb.velocity new Vector2(rb.velocity.x, 3) This is what I have done until now.
0
Hierarchical state machines I have a rather simple state machine to control my Unity character and as the actions the character can perform increase, so does the complexity of state management, I have been reading about hierarchical state machines, they seem like the answer to my problems but I cannot 'connect' the theory to actual implementation, take for example the below Movement State public class Player Movement BaseState public Player Movement(PlayerController playerController, EntityStateMachine Comp entityStateMachineComponent) base(playerController, entityStateMachineComponent) public override void OnEnter() playerController.GetComponent lt Animator gt ().SetBool( quot IsMoving quot , true) playerController.GetComponent lt Cast Component gt ().OnCastReady.AddListener(() gt stateMachineController.ChangeToState(new Player Movement Casting( playerController, stateMachineController)) ) public override void OnExit() playerController.GetComponent lt Animator gt ().SetBool( quot IsMoving quot , false) public override void OnFixedUpdate(StateMachineContext context) If movement input is zero if ( playerController.PlayerInput.inputData.Movement.Input Vector3.zero) stateMachineController.ChangeToState(new Player Idle State( playerController, stateMachineController)) else playerController.motor.MoveAndRotateTowards( playerController.PlayerInput.inputData.Movement.Input CameraRelative) public override void OnUpdate(StateMachineContext context) if (Input.GetKey(KeyCode.LeftShift)) playerController.motor.IsSprinting true playerController.motor.Speed playerController.motor.walkSpeed playerController.motor.sprintSpreedModifier else playerController.motor.IsSprinting false playerController.motor.Speed playerController.motor.walkSpeed if (! playerController.motor.IsGrounded amp amp playerController.Rigidbody.velocity.y lt 0) stateMachineController.ChangeToState(new Player Locomotion Falling State( playerController, stateMachineController)) if (Input.GetKeyDown(KeyCode.Space) amp amp playerController.motor.IsGrounded) stateMachineController.ChangeToState(new Player Locomotion Jump State( playerController, stateMachineController)) My current goal is to have this become my super state for my movement state machine, I would like to add a sub state to this (Cast Movement) that simply calls playerController.motor.Move instead of playerController.motor.MoveAndRotateTowards as I would like to have a different style of movement while aiming a spell, but how would I write this substate so that it only handles how the character moves and falls back on the super state for everything else? I have the feeling I have to re write how my state machine works but I have no idea where to start except I probably need to seperate transitions out of the states themselves? perhaps? haha
0
Efficient way to load chunks of a 2d level to prevent game from loading stutters I am building a 2D sidescroller game in Unity3D. It's tile based. To get better performance I divided the level into chunks. I activate these chunks when the player enters 2D Triggers and deactivate it again when he exits the 2d trigger. So I normally only have a max of 2 chunks loaded. This works good BUT I do have some loading stutters of a few frames when I load a new chunk. How can I prevent that from happening? Thank you!
0
Why does a UI button that is child to a canvas not appear in game view? I am trying to place a button onto a canvas background using C script. I want the button specific to the canvas (i.e., if I move the camera to look at another canvas, I do not want the button visible). My C script is below. I have attached it to an empty game object. When I run the game, the Heirarchy panel of Unity shows that the canvas and button are created OK, and that the button is a child of the canvas. The canvas appears in game view at the right size (200 x 200). But in game view, there is no button! The button is definitely present clicking on its name the Heirarchy panel shows me a location and size in the scene view that are exactly as specified in my C script. But nothing happens when I click the region in game view where the button is supposedly present. Unity's Inspector panel shows that a "Button (Script)" has been attached to my button object, with Rect Transform parameters as specified in my C code. I tried messing with the colors, but still no button. The "On Click()" window contains nothing except the message "List is Empty". How do I make the button appear in game view? How do I make the button work (i.e., generate the Console message "button pressed")? using UnityEngine using System.Collections.Generic using UnityEngine.UI using UnityEngine.EventSystems public class TestScript MonoBehaviour private GameObject myGO private Vector2 buttonSize private Vector3 buttonPosition void Start () setup a canvas myGO new GameObject () Canvas myCanvas myGO.GetComponent lt Canvas gt () myCanvas.renderMode RenderMode.WorldSpace RectTransform parentRectTransform myGO.GetComponent lt RectTransform gt () parentRectTransform.sizeDelta new Vector2 (200, 200) set size of parent rectangle create and place the button Vector2 buttonSize new Vector2 (10, 10) Vector3 buttonPosition new Vector3 (150, 70, 1) CreateButton (myGO.transform, buttonPosition, buttonSize) end Start() public void CreateButton(Transform panel ,Vector3 position, Vector2 size) GameObject button new GameObject() button.name "Button" button.transform.parent panel button.AddComponent lt RectTransform gt () button.AddComponent lt Button gt ().onClick.AddListener (handleButton) button.transform.position position void handleButton() Debug.Log("Button pressed!") end class TestScript
0
How are Roguelike Bullet Hell mechanics stored in Unity? I'm going to be creating a roguelike bullet hell game wherein the play will be a bullet hell game, but you will be traveling between "rooms" wherein the action takes place. The "rooms" will be randomly generated like in roguelikes such as The Binding of Isaac, but with bullet hell play similar to Touhou or Batsugun, with a possible twist. It will be similar to Enter the Gungeon, but there will be some differences. I'd like to know how Unity will deal with storing possibly thousands of different "rooms" and generating these each time, along with the enemies and bullets these enemies will begin to shoot after you enter the room. Only one room will be visible at a time. How would Unity deal with mapping possibly thousands of rooms, and will it be able to store this while generating bullet patterns? I know that in classic bullet hell arcade games, when there were many bullets on the screen, the game tended to slow down because of hardware limitations.
0
movement control with the 2D driving game I am working on a 2D driving game.I have a button(forward).I need to move the vehicle by pressing on the button. When the button is pressed the vehicle should accelerate upto its maximum speed and when the button is release the vehicle should gradually slow down. float rotateSpeed 0.1f float speedForce 15f float torqueForce 200f float driftFactorSticky 0.9f float driftFactorSlippy 1 float maxStickyVelocity 2.5f float minSlippyVelocity 1.5f bool moveForward false bool moveBackward false bool turnLeft false bool turnRight false Vector3 myRot void FixedUpdate () Rigidbody2D rb GetComponent lt Rigidbody2D gt () float driftFactor driftFactorSticky if(RightVelocity().magnitude gt maxStickyVelocity) driftFactor driftFactorSlippy rb.velocity ForwardVelocity() RightVelocity() driftFactor Move rover forward and backward if(Input.GetKey(KeyCode.UpArrow) moveForward true Input.GetButton("Accelerate") ) Debug.Log ("Uparrow....................................................") rb.AddForce( transform.up 0.3f) if(Input.GetKey(KeyCode.DownArrow) moveBackward true Input.GetButton("Brakes") ) Debug.Log ("break....................................................") rb.AddForce( transform.up speedForce 30f ) float tf Mathf.Lerp (0, torqueForce, rb.velocity.magnitude 2) rb.angularVelocity Input.GetAxis ("Horizontal") tf if (Input.GetKey (KeyCode.RightArrow) turnRight true) transform.Rotate(0,0, 0.5f) if (Input.GetKey (KeyCode.LeftArrow) turnLeft true) transform.Rotate(0,0,0.5f) Vector2 ForwardVelocity() return transform.up Vector2.Dot( GetComponent lt Rigidbody2D gt ().velocity, transform.up ) Vector2 RightVelocity() return transform.right Vector2.Dot( GetComponent lt Rigidbody2D gt ().velocity, transform.right ) this is working fine but the problem is that when I release the forward button the speed of vehicle is not getting slow down. Can anybody help me please
0
Complex Machine handling through VR controller I have a very Complex Machine which I want to operate through my VR controller (HTC Vive Controller). As you can see its short animated video here. I want to pull the machine cover through VR controller which is easy to do but i want to scale and pull some of the other related objects of the machine too (like spring, piston etc, you can see in the video) as i pull its cover through VR controller. The problem is that i am unable to do this using Joints and Animation play. I almost tried anything but nothing worked for me. My question how can i imitate animation all work through code or through physics. Like if i pull an object the rest related object should be stretched like chain. And piston should open or closed according to force.
0
Could not establish connection with local server process when opening or making Unity project Whenever i try to either create or open a Unity project, I get faced with this error. Does Unity need a proxy server, because I dont have one. (If so, how do I get one?) And apparently I need to add some environment variables, (HTTP PROXY, HTTPS PROXY and UNITY NOPROXY localhost,127.0.0.1) what values do i add to these? Unity Package Manager Diagnostics (v0.1.5) Ran 7 checks 1 succeeded 6 failed UPM registry reachable (FAIL) Make an HTTP request to the UPM package registry Connection error. This could be because a proxy is misconfigured. Ping UPM registry (FAIL) Measure the latency of the UPM package registry API No successful pings could be made in 0.062 seconds (30 failed) Ping UPM download (FAIL) Measure the latency of the UPM package download endpoint No successful pings could be made in 0.039 seconds (30 failed) UPM registry download speed (FAIL) Test the Internet connection using the UPM package registry Connection error. This could be because a proxy is misconfigured. Speedtest.net (FAIL) Test the Internet connection using Speedtest.net Connection error. This could be because a proxy is misconfigured. HTTP proxy environment variables (PASS) Detect whether proxy related environment variables are set (HTTP PROXY, HTTPS PROXY, ALL PROXY, NO PROXY, UNITY PROXYSERVER, UNITY NOPROXY) Proxy support has been configured through the following environment variables HTTPS PROXY C Program Files Unity Hub Unity Hub.exe HTTP PROXY C Program Files Unity Hub Unity Hub.exe UNITY NOPROXY C Program Files Unity Hub Unity Hub.exe UPM health check (FAIL) Start the UPM process and call its health endpoint Server started but did not respond to health requests Error Invalid protocol c How do I fix this?
0
Setup sub platforms inside Unity I want to automate some of my Unity build process. I know that setting up automatic builds for platforms is relatively easy, just start Unity headless and tell it to build platform X! This is fine for most things however I have some platform specific things for a given platform. For example I have achievements for Steam, GoG and my own thing if you are running truly standalone. I can easy switch between them by setting define STEAM BUILD to make a build with steam features enabled. This is setup for each platform that I support. At the moment I have to change the script manually and re build every time. I want to make a build server do this all for me but how do I tell Unity to build my PC version with a certain define X set?
0
Animating object, setting isKinematic false, and then letting physics take over I'm trying to create a "tree felling" effect, where the tree trunk falls over after being cut down by the player. I've used one prefab which contains my tree stump and tree trunk as children. In its default state, my tree trunk as a rigidbody with isKinematic true. When the player cuts down the tree, I begin an animation on the trunk which "tips it over". On the last frame, it sets isKinematic false at this point it should "fall over" because physicals gravity is in control and the center of mass is definitely over its base. However, the animation seems to be preventing it, like it's still "controlling" the transform. Adding a transition from the "fell" state to an "exit" state just resets the position rotation. Setting the animator to "animate physics" kind of works, but the tree just flies away, probably colliding with the stump or something. Disabling the animator after the animation kind of works, but this also causes the tree to go flying with some crazy physics. When left alone, OnCollisionEnter is called on the tree for colliding with my ground, yet the gameobject appears to still be stuck at 45 degrees and never touched the ground. It seems like the rigibody collider is not where the mesh transform is? Animating the object and then turning off isKinematic should work, it's been recommended to me on reddit and is the accepted answer on this question, so I'm not sure what could be wrong. Edit I can ease the physics problems by telling the trunk to ignore it's own stump (Physics.IgnoreCollision(Trunk.transform, Stump.transform) ), but the base of the tree still "jumps" away from the stump, rather than "continue tipping over". I'm not sure what else could be at play.
0
Unity2D How to save volume of audio source when game is restarted? How do I save volume of my audio source (clicking the mute button) when game is restarted. You see I have one scene in my game and once the player dies there is a button the user can click on that resets the game, however it also resets the audio source, so when I play the game and click my mute button, the audio source volume is at 0 but when I die and click the reply button (the restart reset button) the music is restarted as well, instead of staying muted (save the current volume). I tried using DontDestroyOnLoad(this) but my muted script is attached to my game over panel animation (the panel comes down when player dies) making the my game over panel animation not being destroyed when you restart the game. I tried other methods like putting my mute button script on a parent empty object and putting the object that has the audio source on under it as a child but it did the same thing. Anyway this is my mute button script private bool mute public void Muted () mute !mute if (mute) gameObject.GetComponent lt AudioSource gt ().volume 0 else gameObject.GetComponent lt AudioSource gt ().volume 1 And this is my restart level when button is pressed (p.s. I used the OnClick method activating methods) public void NavigateTo(int scene) Application.LoadLevel ("Game Level") Thank you in advance )
0
Unity scaling and animations In my Unity project I have a script that programmatically changes the scaling of an object during the game. Recently I wanted to add a spawning animation clip to my object, which modifies the object's scaling (but only during a short delay). So I added an animation controller to the object, containing the spawning animation clip. I can now successfully run the spawning animation but the in game programmatic scaling changes don't work anymore, even when my animation is not running. Any idea?
0
Mixamo Models not Importing Correctly in Unity Mixamo (now Adobe Mixamo) allows us to choose character and then animations from its website from free samples. I have done one simple animation and added the model to Unity. The animation works fine but the model is very changed once being imported, have a look here. I am using following import settings, Format Fbx for Unity Skin With Skin FPS 30 Keyframe Reduction Uniform I tried "Fbx" format only too, but no luck.I also applied "humanoid" in rigging, but I think it is not relevant here. Since I am not good with modeling that is why I am using this service, and I have no idea how to tackle this. Once it did worked well, but unfortunately I could not remember how, so I am stuck again.
0
Control convention for circular movement? I'm currently doing a kind of training project in Unity (still a beginner). It's supposed to be somewhat like Breakout, but instead of just going left and right I want the paddle to circle around the center point. This is all fine and dandy, but the problem I have is how do you control this with a keyboard or gamepad? For touch and mouse control I could work around the problem by letting the paddle follow the cursor finger, but with the other control methods I'm a bit stumped. With a keyboard for example, I could either make it so that the Left arrow always moves the paddle clockwise (it starts at the bottom of the circle), or I could link it to the actual direction meaning that if the paddle is at the bottom, it goes left and up along the circle or, if it's in the upper hemisphere, it moves left and down, both times toward the outer left point of the circle. Both feel kind of weird. With the first one, it can be counter intuitive to press Left to move the paddle right when it's in the upper area, while in the second method you'd need to constantly switch buttons to keep moving. So, long story short is there any kind of existing standard, convention or accepted example for this type of movement and the corresponding controls? I didn't really know what to google for (control conventions for circular movement was one of the searches I tried, but it didn't give me much), and I also didn't really find anything about this on here. If there is a Question that I simply didn't see, please excuse the duplicate.
0
canvas not found in game view with unity I am working on a GearVR app with Unity3D.I have an environement and I have placed a canvas in the scene.I have set the canvas Render mode to "World Space".But when I runned my project,the canvas is getting displayed on the scene view,but in the game view the canvas is not getting on the scene.But whereas in the camera view its showing the canvas.What will be the issue?. When I set me canvas Rendere mode to Screen Space Overlay the canvas is getting displayed in the scene but as the lookup change,the canvas is also moving along with the camera Can anybody please help me out.
0
How does Speed in Animator Window in Unity work? If speed 1 is considered normal playback, is it by a second? So animation play once in a second? If I have my animator speed set as 100, would it make the speed become 0.06 then ?
0
Unity UI Button not working on PC build but working on Android mobile build I am using Unity to build a game that is going to be used on PC and Android mobile devices. The problem I have is that when I use a UI Button, it works perfectly on mobile, but on PC and in the editor, is not working. Why could this be happening?
0
How to use Left Shift to run Unity? So, I need to use LShift to run, but I can't exactly figure out how to do so.... I don't know what to use.... Here my code using UnityEngine using System.Collections This script moves the character controller forward and sideways based on the arrow keys. It also jumps when pressing space. Make sure to attach a character controller to the same game object. It is recommended that you make only one call to Move or SimpleMove per frame. public class Move MonoBehaviour CharacterController characterController public float speed 6.0f public float jumpSpeed 8.0f public float gravity 20.0f public Transform charBody private Vector3 moveDirection Vector3.zero public float mouseSense 11f public float runSpeed 12f public bool isRunning false void Start() characterController GetComponent lt CharacterController gt () void Update() if (characterController.isGrounded) We are grounded, so recalculate move direction directly from axes moveDirection transform.forward Input.GetAxis( quot Horizontal quot ) transform.right Input.GetAxis( quot Vertical quot ) moveDirection speed moveDirection transform.right Input.GetAxis( quot Horizontal quot ) transform.right Input.GetAxis( quot Vertical quot ) moveDirection speed if (Input.GetButton( quot Jump quot )) moveDirection.y jumpSpeed Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below when the moveDirection is multiplied by deltaTime). This is because gravity should be applied as an acceleration (ms 2) moveDirection.y gravity Time.deltaTime Move the controller characterController.Move(moveDirection Time.deltaTime) float MOUSEY Input.GetAxis( quot Mouse Y quot ) mouseSense Time.deltaTime float MOUSEX Input.GetAxis( quot Mouse X quot ) mouseSense Time.deltaTime charBody.Rotate(Vector3.up MOUSEX) So, when left shift is clicked I want the speed to change to runSpeed... Can I please have some help doing so? Thanks
0
Move camera from wherever camera is to pinned point So, I need to switch move animate camera from point X (not point A,as I don't know where the camera is at that momemnt) to point B (place where you want your camera to move). This is for cinematics...like when you press a button in game which does something (opens doors maybe) but you can't see where nor what did you activate, so you show the player with the camera where and what happened. I tried to animate camera to position, camera just goes crazy. Then I tried to make an empty object placed at the position where the camera should be and move camera with code to that objects position. I tried enabling Camera 2 and disabeling Camera 1 but it just doesn't work. Enable Disable Code public var door DoorAnim public var triggered boolean false function OnTriggerEnter() triggered true function OnTriggerExit() triggered false function Update() if (triggered amp amp Input.GetKeyDown(KeyCode.JoystickButton1)) Debug.Log("Door 1 built") camera1 GameObject.Find("Camera1") camera1.enable false camera2 GameObject.Find("Camera2") camera2.enable true door GameObject.Find("door1") door.animation.Play()
0
How to animate a bezier curve over a given duration I have created a bezier curve by adding the following script to an empty game object in the inspector. This draws to complete curve at once when I run the code. How can I animate it over a given period of time, say 2 or 3 seconds? public class BCurve MonoBehaviour LineRenderer lineRenderer public Vector3 point0, point1, point2 int numPoints 50 Vector3 positions new Vector3 50 Use this for initialization void Start () lineRenderer gameObject.AddComponent lt LineRenderer gt () lineRenderer.material new Material (Shader.Find ("Sprites Default")) lineRenderer.startColor lineRenderer.endColor Color.white lineRenderer.startWidth lineRenderer.endWidth 0.1f lineRenderer.positionCount numPoints DrawQuadraticCurve () void DrawQuadraticCurve () for (int i 1 i lt numPoints 1 i ) float t i (float)numPoints positions i 1 CalculateLinearBeziearPoint (t, point0, point1, point2) lineRenderer.SetPositions(positions) Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1, Vector3 p2) float u 1 t float tt t t float uu u u Vector3 p uu p0 2 u t p1 tt p2 return p
0
Is it possible to use a string somehow converted to match name of a bool? I have a Json file holding data for my LineData type i created. Serializable public class LineData public string lineID public string lineDialog public float lineDuration public string condition Note the last one, 'condition', that is what I hope to use to hold a name of a specific bool in my code, so that the line can only be spoken when that bool is true. Is this a decent way to achieve this? Or is it even possible? I've read about making 'custom markup' on my Json things like (!!) and ( ) built in the text to mean stuff in my code, but I don't know where to start with it and cannot find any tutorials (I've only seen it on some Youtube GDC lecture style videos from professional game developers working for companies) But failing the custom markup thing, if I can somehow use the string of the name of the bool, and use that to check the state of it's corresponding bool in the code, that would be enough for me so far. Any ideas or help is fantastic and very welcome. Many thanks!!! (PS. The json looks like this (Im sure you don't need it, but just in case)) "lineDatas" "lineID" "BEDROOM DAVE 0001", "lineDialog" "Yaawwn, up i get for another fun packed day.", "lineDuration" 3, "condition" "" , "lineID" "BEDROOM DAVE 0002", "lineDialog" "Well I think I need a cigarette before I get to work!", "lineDuration" 3, "condition1" "notSmokedCig"