_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
How to scroll Select objects in the hierarchy tab? So I am creating breakable objects in unity and I have to select around 200 objects in the hierarchy tab so that I can apply some components to each the pieces. My problem is that once I select more than 100 objects in the hierarchy tab, it starts to bug out and it becomes incredible difficult to select objects. So I was wondering if there was a way to a scroll select or something like the box select like you can use on windows to easily select multiple items, or maybe some other way I didn't mention. It would really help me if someone could tell me a quick way to select multiple things in unity, in the hierarchy tab. Thanks, Nova
|
0 |
Animation imported from Maya has interpolation issues I have imported animation from Maya (.fbx) and the curves for the animation in Unity are very different than in Maya. I can clearly notice a flicker for few seconds when I am scaling the object (0 to 1) in loop. The curve for scaling is shown below. The rest in the animation work fine except for the scale. The problem is that Unity adds interpolation automatically to these curves which is why it creates an issue. I have selected the keys in the curves for the scale attribute and quot Both Tangets gt Constant quot , but it did not have any effect. How can I fix this?
|
0 |
(Unity) what happens if i get a transform.position of a nested object Okay so here is the example You have a plane at position 0,0,0 with a scale 15,1,15 (for demonstration) Now you have a parent object for the sake of simplicity lets call it parentObject this parent object has the following position 7,25,26 The parent DOES NOT have a mesh and is thereby an empty gameobject The parent has a child gameobject Here the issue starts the child has a transform position at 5, 25,30 however this objects transform.position is relative to the parent last take our agent i know set him to go to childObject.transform.position will he then move correctly to the object or will he, in fact, move to the position that is relative to the parent object? I know this might seem a bit messy but the general question is if i tell an agent to go to a gameobject that is a child of another object using transform.position will he go to the place we would expect?
|
0 |
Making a surface transparent from blackness of texture I am making a "halo" shader in unity using GLSL. And I've come to a roadblock. What I need to do is take a texture, like the following, and make it transparent according to the darkness of it. And I don't want a cutout, because that cuts it off at a hard edge. This line of code doesn't seem to work. gl FragColor texture2D( vec4( MainTex.r, MainTex.g, MainTex.b, MainTex.a), vec2(textureCoordinates))
|
0 |
unity2D swipe control's bool for animator doesn't work i was trying to make a control where the animation plays upon swiping one direction. each time i've make a tap swipe control, it just keeps popping messages like this. the tap animation works fine, but the animation for swipe controls just doesn't work well, the bool for them has assigned but did not make it 'true' when i swipe a direction, but the bool for the tap works, which is weird.(ignore the miss bool in the animator) it says that i need to assign the anim variable of the Swipe script in the inspector. but there is nothing left for me to assign, which doesn't make much sense for me. (refer to Region Animation) i've tried to make some adjustment with the script, but the results is the same, and it has no problems when build. which is why i need help for the animation stuff. using System.Collections using System.Collections.Generic using UnityEngine public class Swipe MonoBehaviour public Animator anim public bool tap, swipeUp, swipeDown, swipeLeft, swipeRight public bool isDragging false public Vector2 startTouch, swipeDelta private void Update() tap swipeUp swipeDown swipeLeft swipeRight false region Standalone Input if (Input.GetMouseButtonDown(0)) tap true isDragging true startTouch Input.mousePosition Debug.Log("Tapped") else if (Input.GetMouseButtonUp(0)) isDragging false Reset() endregion region Mobile Inputs if (Input.touches.Length gt 1) if (Input.touches 0 .phase TouchPhase.Began) tap true isDragging true startTouch Input.touches 0 .position else if (Input.touches 0 .phase TouchPhase.Ended Input.touches 0 .phase TouchPhase.Canceled) isDragging false Reset() endregion region Animation if (Tap) anim.SetBool("Tap", true) if (SwipeDown) anim.SetBool("Down", true) if (SwipeUp) anim.SetBool("Up", true) if (SwipeLeft) anim.SetBool("Left", true) if (SwipeRight) anim.SetBool("Right", true) endregion calculating the distance swipeDelta Vector2.zero if(startTouch ! Vector2.zero) if (isDragging) if (Input.touches.Length gt 0) swipeDelta Input.touches 0 .position startTouch else if (Input.GetMouseButton(0)) swipeDelta (Vector2)Input.mousePosition startTouch did we cross the deadzone? if (swipeDelta.magnitude gt 125) which direction? float x swipeDelta.x float y swipeDelta.y if (Mathf.Abs(x) gt Mathf.Abs(y)) left or right if (x lt 0) swipeLeft true else swipeRight true else Up or down? if (y lt 0) swipeDown true else swipeUp true public void Reset() startTouch swipeDelta Vector2.zero isDragging false anim.SetBool("Tap", false) anim.SetBool("Down", false) anim.SetBool("Up", false) anim.SetBool("Left", false) anim.SetBool("Right", false) public Vector2 SwipeDelta get return swipeDelta public bool Tap get return tap public bool SwipeUp get return swipeUp public bool SwipeDown get return swipeDown public bool SwipeLeft get return swipeLeft public bool SwipeRight get return swipeRight
|
0 |
Blender assets management and workflow for Unity project I'm trying to decide how to manage my 3D assets, and even how I should construct a world for my game. I should maybe explain, my game is basically a single explorable world set in a school. It's quite large. Every room and building enterable (possibly transitionless), and a large outdoor area (sports field, playground, etc.) I plan to make much of it modular (walls, floors, etc.) The world is somewhat tiled. I've create several different blocks for walls (Straight, cornered, T shaped, cross shaped, door, etc.) which I can place sequentially to create rooms and buildings. I have some blocks lined up in a row in Blender. Now I'm wondering what to do with these pieces... Issue 1) Should I use Unity to place my assets to create my world, or do I create another blender file with all my assets linked? I'm tending towards the latter because I feel I can do a lot more within Blender, but it doesn't appear very easy. However in order for the game to function I'd imagine I'd have to cut up my world into pieces. Problematically I'd also like to use Unity's terrain tool, so if I'm creating a single world object in Blender I'm not sure how I'd do this. Issue 2) I'm not very experienced in 3D game development, I've mainly worked with Flash up until recently. In Flash, you can create movieclips which nest other movieclips. Preferablly I'd like a system as close to this as possible within Blender or Unity. So for instance, I'd like to have a 3D asset of a table. Without affecting the original asset, I want to place objects on the table like books and whatnot, and then control this as a single instance called 'Table with books', maybe duplicate it elsewhere, if I change the position of the books on one it should update all other instances. In Blender, I use alt D to duplicate an object and link it to the original, however it's very easy to duplicate an object without selecting it's children and creating a variety of differently childrened duplicates, which in a vast world which is hard to keep track of, would become a massive headache to deal with. I can just imagine spending hours upon hours correcting a single silly mistake I produced and repeated without noticing for several days. Within Blender I've tried making each wall object it's own group, however they're all in one file and have different xyz positions. I don't want to separate them into dfferent files, in order to create seamless walls I need to have them all in one place. When I create a group instance with shift A, the origin is of the original group object's xyz position I know there's an offset option in the groups panel where I could set it to 2,4,0 to counteract this but I don't like this at all. If I move 10 original grouped objects I have to update each of their offsets! I suppose I could create an empty axis for each wall object, but this also seems an odd way of doing things. Issue 3) Walls are 2 sided objects, the design of one could be different on either side, one could be pink on one side with a skirting board, the other side could be exposed brick work. How would I do this? Lets say I use Unity to position all my assets (which I'm now assuming is probably the right way), ideally I'd like to select a load of walls faces and change their design with a combo box of styles and a color picker in the inspector (a script would be necessary obviously). Sorry, that's a lot of questions for a single post, I hope someone can point me in the right direction.
|
0 |
Road Intersection mesh generation For the last month I was learning about meshes and how procedurally generate them. For what I need it looks very straightforward. For my little app I planning to have a road tool (very simple), user draws lines and curves and road is generated with specific width (flat). So I can now create a drawing tool and generate simple mesh along the curve or line. Next step is to be able to construct intersections... I looked at lots of example but couldn't find any descriptions how it is done. Could you please advice what approach to take, how to identify intersection of two or multiple curves and generate mesh junction? Also could you please advice on bigger picture, should I have sort of underline system for city building app, like graph, to know where to place road intersections, buildings and so on? Thank you This is a quick prototype I did (not in code) https youtu.be 1TxxB ofLAo
|
0 |
Set Parent to Instantiated Objects in Unity i am having problem in attaching parent to the instantiated objects. I have attached the code below. please tell me where i am doing wrong. Thank you. public GameObject brick public Transform BrickHolder public GameObject Bricks void Start() for (float y 2.16f y lt 4.88f y 0.34f) for (float x 2.125f x lt 2.125f x 0.85f) GameObject Bricks Instantiate(brick, new Vector3(x, y, 0), Quaternion.identity) as GameObject if (Bricks ! null) Debug.Log("Hello") Bricks.transform.SetParent(BrickHolder)
|
0 |
Which GameObject should I put the animator on? I have a GameObject. One of its children is an empty GameObject, whose children are the body parts which need to be animated. Character (root) gt Body gt gt Body Parts Should I put the animator on the root GameObject ("Character")? Or on the empty child ("Body")? Does it matter? What benefits would one way offer over the other? Or is there another approach I should be taking? This is for 2D sprites animations. I am trying to figure this out before making all of the animations to avoid redoing them.
|
0 |
Unity Invert Movement Direction I am currently developing a 2,5D Sidescroller in Unity (just starting to get to know it). Right now I added a turn script to have my character face the appropriate direction of movement, though something with the movement itself is behaving oddly now. When I press the right arrow key, the character moves and faces towards the right. If I press the left arrow key, the character faces towards the left, but "moon walks" to the right. I allready had enough trouble getting the turning to work, so what I am trying is to find a simple solution, if possible without too much reworking of the rest of my project. I was thinking of just inverting the movement direction for a specific input key facing direction. So if anyone knows how to do something like that, I'd be thankful for the help. If it helps, the following is the current part of my "AnimationChooser" script to handle the turning Quaternion targetf Quaternion.Euler(0, 270, 0) Vector3 Direction when facing frontway Quaternion targetb Quaternion.Euler(0, 90, 0) Vector3 Direction when facing opposite way if (Input.GetAxisRaw ("Vertical") lt 0.0f) if input is lower than 0 turn to targetf transform.rotation Quaternion.Lerp(transform.rotation, targetf, Time.deltaTime smooth) if (Input.GetAxisRaw ("Vertical") gt 0.0f) if input is higher than 0 turn to targetb transform.rotation Quaternion.Lerp(transform.rotation, targetb, Time.deltaTime smooth) The Values (270 and 90) and Axis are because I had to turn my model itself in the very first place to face towards any of the movement directions.
|
0 |
XInputDotNet not working when building for UWP in Unity I am working on a game where a controller has to vibrate. I have found the XInputDotNet plugin which worked very well in the editor and a normal windows build, but if I build for UWP (both Xaml and D3D) the controller doesn't vibrate. When building in unity for UWP it also gave me an error saying this Plugin 'XInputInterface.dll' is used from several locations Assets Plugins x86 XInputInterface.dll would be copied to lt PluginPath gt XInputInterface.dll Assets Plugins XInputInterface.dll would be copied to lt PluginPath gt XInputInterface.dll Plugin 'XInputDotNetPure.dll' is used from several locations Assets Plugins x86 XInputDotNetPure.dll would be copied to lt PluginPath gt XInputDotNetPure.dll Assets Plugins x86 64 XInputDotNetPure.dll would be copied to lt PluginPath gt XInputDotNetPure.dll Please fix plugin settings and try again. UnityEditor.Modules.DefaultPluginImporterExtension CheckFileCollisions(String) UnityEditorInternal.PluginsHelper CheckFileCollisions(BuildTarget) (at C buildslave unity build Editor Mono Plugins PluginsHelper.cs 25) UnityEditor.HostView OnGUI() The only way I found to remedy this is by deleting one of the plugin folders. I tried manually copying the ddl's to the build folder, but this didn't help. I tried using the 32 bit dll's and the 64 bit dll's, I tried building for x86 and x64 and I tried all three modes in visual studio(Debug,Master,Release). I found some links to the Windows.Gaming.Input namespace, but I dont't know if it is possible to add this namespace to unity and if so how. Does anybody have an idea how to fix my problem?
|
0 |
how can i create a snake with a single piece look I want to create a 3d snake with a single piece look, i have tried separate head and body parts following each other with Vector3.SmoothDamp but some quaternion issues occurred (when y axis gt 90, pieces turning upside). What I want is exactly like in the video https youtu.be uWlMvHU2wfQ Could you tell me the unity components I need to know research? Are the snake models in the video rigged?
|
0 |
How to interpolate colors around the spectrum of hues? I wanted to generate a 7 segment display whose color brightness varies with time, this can be done by just using linear relationship. Color activeColour2 new Color(1, DateTime.Now.Millisecond 0.001f, DateTime.Now.Millisecond 0.001f) So in 1 complete second, it produce color in the range of (1,0,0) to (1,1,1) as in the code below using System using UnityEngine public class ClockDigit2 MonoBehaviour static readonly bool , SEGMENT IS ACTIVE new bool , true, true, true, true, true, true, false , 0 false, true, true, false, false, false, false , 1 true, true, false, true, true, false, true , 2 true, true, true, true, false, false, true , 3 false, true, true, false, false, true, true , 4 true, false, true, true, false, true, true , 5 true, false, true, true, true, true, true , 6 true, true, true, false, false, false, false , 7 true, true, true, true, true, true, true , 8 true, true, true, true, false, true, true 9 public Color32 inactiveColour Color.black public SpriteRenderer segments new SpriteRenderer 7 public void Display(int number) Color activeColour2 new Color(1, DateTime.Now.Millisecond 0.001f, DateTime.Now.Millisecond 0.001f) var digit number 10 if (digit lt 0) digit 1 for (int i 0 i lt 7 i ) if (SEGMENT IS ACTIVE digit, i ) segments i .color activeColour2 else segments i .color inactiveColour void Update() Display(DateTime.Now.Second) However, now I want to interpolate through all the colors in the circle above over 1 second. I don't know how to express this as a formula for R, G, and B. The RGB value is not linear relationship as you spin the selected color in the chart, you can notice the RGBA components vary together in a nonlinear form. I considered using Lagrangian interpolation. However, this will not be accurate or might fail greatly because if you take a reference point at the circle and assume in 1sec, it made a complete revolution, you will notice there is a certain period of time where the RGB value is constant along the path either 0 and 1. So is there any method to get a formula that perfectly fits the color chart with respect to time?
|
0 |
Why the Render texture is not working when trying to preview a camera on a object? In the editor in Assets right click Create Render Texture Then changed the Render Texture name to SecurityCameraTexture Dimension 2D size 480 x 256 Then created a new material Assets right click Create Material Then changed the material name to SecurityFootage Then changed the material shader from Standard to Mobile Diffuse Then dragged the render texture(SecurityCameraTexture) to the top right image place of the SecurityFootage(material) Next I have a tv object in the scene. In the tv screen I dragged the new material The SecurityCamera. On the SecurityCamera I attached the script that rotate the camera from side to side And the script using UnityEngine using System.Collections public class scr camera MonoBehaviour public float rotate amount Use this for initialization void Start () Update is called once per frame void Update () transform.rotation Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup) rotate amount) transform.eulerAngles.y, transform.eulerAngles.z) Last step I did was to drag the render texture(SecurityCameraTexture) to the camera Target Texture. When running the game and watching the tv I don't see the camera preview in the tv. It should the show the camera preview the camera moving from side to side and what the camera is showing. The camera preview was working fine before I started working with the render texture. But it's not showing the preview in the tv.
|
0 |
How do I add an "offset" to LookAt? I have created a Third Person Controller. The camera is behind the player I would like to make it so that the player aims at the mouse pointer position. To do that, I use the following code to rotate the chest towards the position var mousePos Input.mousePosition mousePos.z 10 Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) Chest.LookAt(aim) The hands do not perfectly straightly point forwards, so I need to add an quot offset quot to the LookAt. I tried this approach var mousePos Input.mousePosition mousePos.z 10 Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) aim new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0) Chest.LookAt(aim) Of course I do all rotation patching in LateUpdate(). In Update(), it would simply be erased by the animation itself. It does work, but when the model is rotated around the Y axis, something goes wrong The offset is quot wrong quot , it doesn't have the same effect. This surprises me because all I do is rotate the entire model. So I think this line is not correct aim new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0) Is this not the way to offset the LookAt results?
|
0 |
Rolling on collision I'm having a small issue where if I collide with another object (let's use a simple cube) with my player (this player is just a sphere), the ball will infinitely roll in the opposite direction and WILL NOT STOP. my code is as follows using UnityEngine public class PlayerController MonoBehaviour private Rigidbody rb private float moveHorizontal private float moveVertical public float moveSpeed Start is called before the first frame update private void Awake() rb GetComponent lt Rigidbody gt () Update is called once per frame void Update() moveHorizontal Input.GetAxis("Horizontal") moveVertical Input.GetAxis("Vertical") private void FixedUpdate() MovePlayer() private void MovePlayer() Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) rb.AddForce(movement moveSpeed) I even changed the ForceMode to ForceMode.Impulse so be able to see what it was doing a little easier, and it is in fact slowly rolling away infinitely with no way to stop it. Both objects have a Rigidbody for them to be able to react to being hit. This is my first time messing with 3d. I tried to do something like this to make it not roll away on impact private void OnCollisionExit(Collision collision) if (collision.collider.gameObject.layer ! LayerMask.NameToLayer("Ground")) rb.velocity Vector3.zero But then if I want to jump on the cube (lets say the cube is an enemy and I'm jumping on it to kill it), then it acts very wonky each time it touches the edge of the cube and I haven't made it on top (again, because the velocity is being set to zero). I am all out of ideas and would love some input here! EDIT I now realize that the ball will slowly roll forever even without collision and just simply moving. I am very lost !
|
0 |
How to represent a modular FSM for AI using ECS? I am considering to implement AI using ECS which actually contradicts working with naive FSMs. My current idea is to have multiple components which represent the particular state an Entity that has a AIControllerComponent is currently in. Let's say an enemy starts out with the mentioned AIControllerComponent as well as a EnemyIdleComponent. Now an EnemyIdleSystem would handle all those idle enemies and if it happens that a player comes too close it'd replace the EnemyIdleComponent with an EnemyChasePlayerComponent leaving the handling of this to EnemyChasePlayerSystem. This approach is rather generic and I would basically end up with a bunch of enemies that have the very same behaviour. I was curious to know how I should combine this approach with some more modular states. At first I thought about adding an enum variable to AIControllerComponent which holds the type of the enemy but I can't really think of a decent solution to call different implementations inside of the EnemyFooSystems based on that particular enum value. Do you have any suggestions? EDIT I am using pure ECS patterns and Jobs, as such MonoBehaviours and non blittable types inside of IComponentData are not usable.
|
0 |
How to apply code of certain script to another? I have a code in my "OnCollider" script to respawn whenever the player dies and has taken an object containing tag 'Respawn'. 1st script OnCollider using System.Collections using System.Collections.Generic using UnityEngine public class OnColllider MonoBehaviour public GameObject Doorfinder public GameObject Door2 public Transform Camera public Transform target public GameObject Coin public bool collided public GameObject Playee public GameObject currentRespawn void Start() Door2 GameObject.Find ("Door0.2") Playee GameObject.Find ("Player") public void OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.name "scroll") Destroy (collision.gameObject) Destroy (Doorfinder) if (collision.gameObject.tag "Fire" ) Playee.SetActive (false) if (collision.gameObject.name "PathFinder") Destroy (collision.gameObject) Destroy (Door2) if (collision.gameObject.tag "Coin") Destroy (collision.gameObject) if (collision.gameObject.tag "subVillains") Playee.SetActive (false) if (collision.gameObject.tag "Bramble") Playee.SetActive (false) Respawnable (collision) public void Respawnable (Collision2D collision) if (collision.gameObject.tag "Respawn") collided true collision.gameObject.SetActive (false) if (collided true amp amp Playee.activeInHierarchy false) transform.position currentRespawn.transform.position Playee.SetActive (true) collided false if (currentRespawn.activeInHierarchy false amp amp collision.gameObject.tag "Respawn") currentRespawn collision.gameObject 2nd Script Enemy using System.Collections using System.Collections.Generic using UnityEngine public class MaxyMory MonoBehaviour public Vector2 origin public float distance public int layerMask public float sider public Vector2 secondorigin public float bringer public float lesngther public GameObject destroy public Vector2 origination public float middle public float lengther Use this for initialization void Start () origin new Vector2 (transform.position.x bringer, transform.position.y sider) origination new Vector2 (transform.position.x bringer, transform.position.y middle) secondorigin new Vector2 (transform.position.x bringer, transform.position.y lengther) Update is called once per frame public void Update(GameObject Playee) Debug.DrawRay (origin, Vector2.right distance, Color.red) Debug.DrawRay (secondorigin, Vector2.right distance, Color.cyan) Debug.DrawRay (origination, Vector2.right (distance 30f), Color.gray) RaycastHit2D hit Physics2D.Raycast (origin, Vector2.right, distance) RaycastHit2D anotherhit Physics2D.Raycast (secondorigin, Vector2.right, distance) RaycastHit2D checker Physics2D.Raycast (origination, Vector2.right, distance 2f) if (hit.collider.tag "Player" anotherhit.collider.tag "Player") Playee.SetActive (false) OnCollider is attached to the player while the enemy script is attached to the enemy itself.
|
0 |
Positioning 2D (non UI system) game objects As an old Flash dev I'm slightly confused about how you position game objects on the screen in Unity since game objects have no width or height (only a scale). Let's say I have a container gameobject that has several child game objects with sprite renderers representing tiles on them. If I set the container to x0, y0, the whole tile layout will extend from the screen center upwards and to the right. What are the commonly used ways to position the game object so that it would be centered on the screen? I could calculate the width height of my container but that would still not be very useful because the x y coordinates work in a different scale than pixel (right?). E.g. my test screen is 640x1024 and to center my container (while running in the editor) I'd have to set x y to 4.5. How does that make any sense? Of course Unity's UI system would be a solution but I don't want to create the playfield with the UI system.
|
0 |
Clearing a gizmo list (OnDrawGizmos) I have a list of gizmos in a simple gizmo drawing manager. This list is updated from different parts of the codebase, usually from Update() methods. It goes something like this public class RenderGizmos Singleton lt RenderGizmos gt private List lt GizmoData gt gizmos new List lt GizmoData gt () public void AddNewGizmo(GizmoData gizmos) this.gizmos.AddRange(gizmos) public void AddNewGizmo(GizmoData gizmo) this.gizmos.Add(gizmo) void OnDrawGizmos() if (gizmos null) return for (var i 0 i lt gizmos.Count i ) draw gizmos Can you advise me on when to clear the gizmo list? Ideally I would like to clear it every frame. However Clearing it at the end of the OnDrawGizmos() method will render no gizmos (as I suspect this method might be called several times a frame). Clearing it in an LateUpdate() Update() method is dependent on execution order, sometimes it draws gizmos, sometimes it doesn't Clearing it in a Coroutine has rendered no gizmos (but it might just be dependent on the execution order as well) I would like not to be dependent on the execution order so I prefer not to use the Script Execution Order system.
|
0 |
Unity a ball bounce inside a sphere sometime will penetrate and drop outside i'have made a ball within a sphere (which imported from blender, with mesh collider), see the pic after the scene started, the ball bounce inside around 5 seconds, and then the ball will penetrate (see the arrow) the sphere and drop out of sphere, anyone knows the reasons?
|
0 |
Control the Transform component of an object while the animation is playing It seems the the animation controls the Transform component of the gameobject, hence making it not possible to control the transform properties while the animation is playing. Is there any way to control the Transform component of an object while the animation is playing, like rotating it for example?
|
0 |
Camera stacking for first person view weapon in Universal Render Pipeline I just added URP to my project then upgraded the materials to URP and now it's not rendering the environment anymore I found the problem is that I have 2 cameras which are stacking on each other one with a priority of 1 and the other 0 . The camera that has higher priority is blocking the lower priority camera. How can I fix that? I want to render the higher priority camera on top of the lower priority one.
|
0 |
Unity Logic for saving and loading objects with both static and dynamic data I need help to get some structure for my save and load. I am making a city builder, so I have Buildings thats need to be saved. Each building has a lot of static Data, for example name, description, etc. However it also has a lot of dynamic Data, for example worldPosition, id, etc. My current structure looks like this On each Building GameObject I keep a reference to a ScriptableObject that stores all the static data. I also store a reference to an Object that stores all the dynamic data. This means I need 2 classes for storing Building data, which I already don't like (BuildingStaticData amp BuildingDynamicData) When I Save Load my game I only need to store the Dynamic data, so for saving I just save the DynamicData. For Loading I load the DynamicData, and instantiate a Building GameObject that is associated with it, then the GameObject has the reference to the StaticData. While this works, I would prefer to have a structure where I only have a single class for BuildingData, but I also don't want to lose the power of a ScriptableObject where I can reference other Prefabs etc. I need some help with this logic.
|
0 |
Checkerboard like rendering does not save performance I have a simple scene in Unity with a camera and a quad facing the camera filling the whole viewrect. The quad has a material with the following shader Shader quot Skip quot SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot struct appdata float4 vertex POSITION struct v2f float4 vertex SV POSITION float4 screenPos TEXCOORD0 v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.screenPos ComputeScreenPos(o.vertex) return o fixed4 frag(v2f i) SV Target int2 screenUV (i.screenPos.xy i.screenPos.w) ScreenParams bool skip (screenUV.x screenUV.y) 2 0 if (skip) return fixed4(1,0,0,1) else fixed4 clr fixed4(0,0,1,1) for (int i 0 i lt 10000 i ) clr i 2 0.5 return clr ENDCG The shader returns simple color for an even pixel and runs an expensive computation for an odd pixel. There is no performance difference between running the expensive operation on all the pixels and running it on just half the pixels. bool skip (screenUV.x screenUV.y) 2 0 13fps bool skip true 2300fps bool skip false 13fps Why is there no improvement in performance?
|
0 |
Unity Game objects in scene load incrementally and not at the same time I am using Unity in my Android app. When the app opens, I show the user data in the Unity scene. User data contains texts and images. In order to load this data in the scene, I make a lot of UnityPlayer.UnitySendMessage(GameObject,Function,Params) calls to many C scripts in Unity from Android. Each of these calls performs a specific task like loading an image, creating a text, applying the text font etc. Problem is that the loading of this data right now looks incremental (if that's the right word). So the text is visible first and after a fraction of a second the image shows. Some text effects show later. This looks ugly. How can I make all the UI elements load at the same time even if it takes some time? Is there a way to freeze the scene before each game object is ready to be drawn?
|
0 |
How can I Implement spin in billiard game? I'm not sure that you played billiard or snooker before.if you played you should know about spin. but anyway if you don't know about it you can see it in this video I want to Implement spin like this game for example difference between Top spin and Back spin is Top spin Back spin Spin behaviour if you aim behind the ball you can shoot the ball in all direction if you aim closest to right you can just aim the right if you aim closest to left you can just aim the left I found a same Issue that used Torque in stackoverflow but I don't know why didn't work! Top Spin GetComponent lt Rigidbody gt ().AddTorque(Vector3.back cueStrength ) GetComponent lt Rigidbody gt ().AddForceAtPosition(cueStick.forward cueStrength,transform.position,ForceMode.Acceleration) Back Spin GetComponent lt Rigidbody gt ().AddTorque(Vector3.forward cueStrength ) GetComponent lt Rigidbody gt ().AddForceAtPosition(cueStick.forward cueStrength,transform.position,ForceMode.Acceleration) I noticed that flyordie's snooker didn't use AddTorque.so I don't need answer that Implemented with AddTorque. Update What I tried I add joystick to select spin angle then I apply spin force ( It seems my spin works but sometimes didn't work that I attached video in end of my question). this is my code using System.Collections using System.Collections.Generic using UnityEngine public class MainBall MonoBehaviour private Vector3 FirstPos store first position as reset position public Transform SpinRoator spin rotator cylinder that show spin angle private Rigidbody rigidbody public bool SpinUsed spin should use once private float v2 private void Start() rigidbody GetComponent lt Rigidbody gt () FirstPos transform.position After goal reset ball position public void ResetPos() rigidbody.velocity Vector3.zero rigidbody.angularVelocity Vector3.zero transform.position FirstPos void SpinForce() SpinUsed true float F ComebackForce() calculate comeback force StopBall() stop ball rigidbody.AddForce(SpinRoator.forward F) apply spin force calculating return force after hitting f m.a float ComebackForce() var m rigidbody.mass var v1 rigidbody.velocity.magnitude var a (v1 v2) Time.deltaTime var F m a v2 rigidbody.velocity.magnitude return F stop ball public void StopBall() rigidbody.velocity Vector3.zero rigidbody.angularVelocity Vector3.zero private void OnCollisionEnter(Collision other) if(other.collider.tag "Ball" other.collider.tag "ColorfulBall") if(!SpinUsed) SpinForce() but What is Problem?! It seems works correctly but My Problem is sometimes Spin don't work correctly you can see this video that demonstrate this problem.my ball goes wrong direction of spin!!! 1.Ball goes Wrong sometimes as you can see in above gif ball goes wrong direction!!! ball should go along yellow cylinder but I don't know what is problem of my code!!! 1.Ball goes slow sometimes another problem is comeback force is slow sometimes!!! I calculate comeback force F m.a but why is it slow?!
|
0 |
How to Implement Trap Damage Unity Currently, I have a 2D platformer game, and I want to implement a function that can make the player die and go back to the start or a checkpoint when he interacts with a weapon or trap. What I have in my scene is a sprite with a Rigidbody on it and a trap sprite with a BoxCollider2D on it which is set to trigger. How can I make my player go back to the start when he hits the trap?
|
0 |
Should I use a database to store 10 000 names in a sports game? I'm working on a single player sports game for a year or so and this doubt came up how should I treat store big amounts of data, like player names. Let's take an arbitrary number as example 10000 names, 5000 first names and 5000 surnames. These names would be equally divided between 100 countries, which give us 50 first names and 50 surnames per country. Should I have a local database with these names (or even these countries) considering this data will be needed to generate new players names during the course of the game? Would that introduce limitations, considering I want to make my game moddable by players, as much as possible? These doubts can be extended to other, more complex game entities, such as Players each one with their own face, attributes, team etc... Teams each one with its own crest, kit, squad etc... In my previous research about that, the SQLite popped up as a seemingly viable solution. It happens that I have almost no experience with DB's (specially in games) and would like to know if this is a good direction before start to study and try to implement it.
|
0 |
How can i use StartCoroutine to set the speed for each scaling step of the walls? using System.Collections using System.Collections.Generic using UnityEngine public class WallsTest MonoBehaviour using a GameObject rather than a transform public GameObject prefab public Vector3 wallsStartPosition public float width 0 public float height 1 public float length 2 public Camera wallsCamera void Start() wallsCamera.transform.position new Vector3(wallsStartPosition.x, wallsStartPosition.y 100, wallsStartPosition.z 235) StartCoroutine(BuildWalls()) IEnumerator BuildWalls() for (int i 2 i lt 2 i ) GameObject go Instantiate(prefab) go.transform.parent transform Vector3 scale Vector3.one Vector3 adjustedPosition wallsStartPosition float sign Mathf.Sign(i) if ((i sign) 2 0) adjustedPosition.x (length sign) 2 yield return new WaitForSeconds(0.1f) scale.x width scale.y height scale.z length width else adjustedPosition.z (length sign) 2 scale.x length width scale.y height scale.z width adjustedPosition.y height 2 go.transform.localScale scale go.transform.localPosition adjustedPosition What it does now it's creating two walls at once it's just waiting 0.1 millisecond before creating them. But instead i want it to show the scaling of the walls how they scaling and moving same for the else part for the adjustedPosition.z and not only the adjustedPosition.x The problem is it's just waiting until it's placing the walls at once. I want to see the walls being building step by step like it's placing cube after cube.
|
0 |
How can I make natural rain drops on screen? I'm trying to make rain effect drop with metaballs and trail on screen.I find a clue in shadertoy but I didn't understand how implemented https www.shadertoy.com view ltffzl unfortunately it have many math calculations and i can't use it in unity because it produces a lag.obviously I should use textures but how can I have trail effect?! my idea is using a texture and trail renderer for droping but how can I have metaballs effect? Update I could Implement Metaballs by This Article https github.com smkplus RainFX tree master but I haven't Idea about trail
|
0 |
"Failed to fetch the following dependencies com.google.games gpgs plugin support 0.9.50 " when force resolve GooglePlayGamesPlugin 0.9.50 Ive been stuck with this problem for the last few days and really need some assistance. Iv created an android app and im trying to set up google play services as i want to use the leader board etc.. I downloaded and imported the latest plugin "GooglePlayGamesPlugin 0.9.50 " no errors during the import. I then go to assests play service resolver android force resolve and run that. After running I end up with the following error Resolution failed Failed to fetch the following dependencies com.google.games gpgs plugin support 0.9.50 UnityEngine.Debug LogError(Object) Google.Logger Log(String, LogLevel) GooglePlayServices.PlayServicesResolver Log(String, LogLevel) GooglePlayServices.ResolverVer1 1 LogMissingDependenciesError(List 1) GooglePlayServices.c AnonStorey18 lt m 26(List 1) GooglePlayServices.c AnonStorey14 lt m 1F(Result) GooglePlayServices.c AnonStorey15 lt m 28() GooglePlayServices.PlayServicesResolver PumpUpdateQueue() UnityEditor.EditorApplication Internal CallUpdateFunctions() If i ignore the error and complie the app it works fine but does not connect to the google service. I can publish and use the app without crashes etc but i cant log on to google or view leaderboards. Can any one assist me as im really desperate to get this up and running. Im using unity 2017.1.1f1 personal 64bit Windows 10 64 bit jdk1.8.0 162
|
0 |
Changing text occurs error move initialization code to the Awake or Start function I have GameManager class that has Log method using UnityEngine using UnityEngine.UI public class GameManager MonoBehaviour public static GameManager Instance SerializeField private ScrollRect m GUIConsoleContainer SerializeField private UnityEngine.UI.Text m GUIConsole ... void Awake() Instance this ... public void Log(string message) m GUIConsole.text m GUIConsole.text message " n" GameManager class has static instance, so I can invoke Log method in anywhere like this GameManager.Instance.Log("Helloworld") However it works only first time. After invoke Log again, Unity gives me this error message get isActiveAndEnabled can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function. UnityEngine.UI.Text set text(String) I assigned reference of m GUIConsoleContainer and m GUIConsole in inspector, but I don't get it what this means and why it happens. Just using Debug.Log() or print() works without any error. How should I avoid this error message? Using Unity 2018.2.1f1. p.s. Error coming from here, another class called NetworkManager void OnReceivedBytes(IAsyncResult result) try if(m Socket null) return int resultLength m Socket.EndReceive(result) if(resultLength 0) Shutdown() return Log("Received " m RecvBuffer 0 ) lt lt Error coming from here ... ... And this is where it call OnReceivedBytes using UnityEngine using UnityEngine.UI using System using System.Collections using System.Net using System.Net.Sockets public class NetworkManager MonoBehaviour private Socket m Socket void Start() m Socket new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) m Socket.Connect("localhost", 1337) if(m Socket.Connected) Log("Connected.") m Socket.BeginReceive( m RecvBuffer, 0, m RecvBuffer.Length, SocketFlags.None, new System.AsyncCallback(OnReceivedBytes), null ) else Log("Failed to Connect.") ...
|
0 |
what is the simplest way to get player selection system like checkers in unity 3d c like lets say the board is a top down grid like if your were in front of an actual checkers board i want to figure out how i would be able to select deselect a piece then select deselect a space on the board so that the players piece will move to said place and if another piece is occupying that place already then the said player cant move there also im new to c and progrming in general...i have been only doing it for about five months and have been looking at tutorials and all that ... but if some one could paste an example code if possible something simple so that i can dissect it, learn from it, and change it as I see fit. and if you can explain how the code works that would be really appreciated. things i need some kind of grid checker board code player selection deselection i would prefer it in c and the code applicable strictly to unity3ds mono develop although I intend to learn visual studio in the future at the moment i just want something for unity. lastly please assume that i may be stupid when explaining writing your example code or answer.
|
0 |
Why should I use getcomponent? I have already referred the animator by using the statement, Animator anim But,What is the use of getcomponent in awake() function.What happens without it.
|
0 |
How to play Sound of a Destroyed Object So I have implemented grenades, and thats working fine. Now I want some explosion sound, but the problem is that the sound is still playing when the grenade is explode and I Destroy the grenade. Does someone have an idea how to circumvent this? I mean I could disable all Components on the nade so that it's invisible etc. and destroy it after the sound is done playing, but I feel like that's a bit weird.
|
0 |
Can you use a standard multi thread if only reading unity objects? First of all I know about coroutines and how to use them (they're awesome). A friend of mine was telling me about the way the he implemented his saving system in a game he was working on, after asking him what he was using I found out that he is using system.threading and not coroutines to save data. I know that Unity isn't thread safe but apparently he has had no issues with saving which leads me to wonder if it is ok to use normal threads as long as you're only reading data and no pre existing data is modified in the gameworld? would this affect the game at all (other than some moving objects being slightly ahead of where they should be because of the time it took to get to that object and save it)?
|
0 |
Footstepper with Vr Unity I have the Footstepper Complete Footstep Solution from the unity store, and i dont get it working with the Vr, I made the footstep material like official documentation said, Then i put the Footstepper Setup in the ovrPlayer object. The problem is that sometimes sound the default fallback, so i think that the colission is not detected as it suppose. Some idea ?
|
0 |
Unity splash is starting in progress after white screen When I export my Unity project (on Windows), there is a brief white screen before the Unity splash screen renders, already in progress. Discretely cutting to the already in progress splash screen looks pretty bad, so I'd like to fix this. Here is a video showing what I mean. After some googling, I did find other reports of a white screen, but only on Android. My project is very simple and I am not loading anything intensive on boot, so I'm not sure what is causing this white screen. Does anyone know what might be causing this issue or have ideas to troubleshoot it?
|
0 |
Reasonable amount of garbage collection for mobiles games? I'm making a 2D game for mobile and I noticed that my GC seemed to spike during attack. My normal GC is 40b but during attack it could spike to 2.2kb. I think this is really high specially when I saw a 3D game with only 8b GC. I would love to hear your thoughts about what's a reasonable amount of GC for mobile(e.g device with 512ram). I know I'm supposed to keep the GC as low as possible however I want to have a value I could compare to.
|
0 |
Understanding Torque in Unity This is (hopefully) a simple question that should avoid me asking a more complex question. This is in Unity (2D) but hopefully this is a general physics principle I am not getting. I am applying a torque to a 2D object. The object has a scale of 1, a RigidBody2D with a mass of 1 and no angular drag or undergoing gravity. It is a CircleCollider2D with a radius of 1. There is nothing else attached to the object. In the following code I apply a torque of Pi for one second. In linear motion (and from my understanding of torque) I would expect the angular velocity, after one second, to be Pi (or 180deg s). However, running this code and printing out the speed at t 1.0, the speed is 90deg s. void FixedUpdate() if (time lt 1.0f) rigidbody2D.AddTorque(Mathf.PI) This is consistent, applying a torque of 2Pi gives me a velocity of 1Pi after the time. Where is this factor of 2 coming from?
|
0 |
Unity How to set IK position of Left Hand with an offset? I have a character holding a stick with left hand. I am using IK to make the stick hit a target position. When I position left hand at target position, it works fine. But, I need to offset the hand such that the end of the stick hits the target position. For this, I have put an empty game object as a child at the end of the stick, and offset it like in the code below, but the hand just keeps jittering like crazy. I know it is quite possible to do, but somehow I seem to be missing something. Please help me! SerializeField private GameObject target private Vector3 leftHandPosition private Vector3 hitChildPosition private void OnAnimatorIK(int layerIndex) Vector3 t target.transform.position (hitChildPosition leftHandPosition) animator.SetIKPosition(AvatarIKGoal.LeftHand, t) animator.SetIKPositionWeight(AvatarIKGoal.LeftHand, 1) private void LateUpdate() hitChildPosition BatHit.transform.position leftHandPosition animator.GetBoneTransform(HumanBodyBones.LeftHand).position Here's an image to visualise what I'm trying to solve
|
0 |
How to "place" object in a 3d world without overlapping them ? I would like to place object in a 3d world "like minecraft player can do". What I'm trying to do is to allow the user to place objects, without overlapping them (like in minecraft you can do). So if the player try to place an object partially over another, my game automatically "move and place" the object in the allowed position. What can be the right approach ?
|
0 |
MouseLook Script "Pops" back to the last value when the script is enabled after being disabled or destroyed I am trying to get a problem with a MouseLook script that controls my camera and a LookatGameObject script that also controls my camera when I want to force the player to look in a certain direction under control, but still no luck. I have identified where the issue is Line 43, transform.localEulerAngles new Vector3( rotationY, rotationX, 0) is the the method that sets the X Axis, makes it "POP" back to the last value when the script is enabled (I have even destroyed the component and then added the component when needed but the same result) can anyone see a solution for this? The MouseLook Script using UnityEngine using System.Collections AddComponentMenu("Camera Control Mouse Look") public class MouseLook MonoBehaviour public enum RotationAxes MouseXAndY 0, MouseX 1, MouseY 2 public RotationAxes axes RotationAxes.MouseXAndY public float sensitivityX 15F public float sensitivityY 15F public float minimumX 360F public float maximumX 360F public float minimumY 60F public float maximumY 60F float rotationY 0F void Update() if (axes RotationAxes.MouseXAndY) float rotationX transform.localEulerAngles.y Input.GetAxis("Mouse X") sensitivityX rotationY Input.GetAxis("Mouse Y") sensitivityY rotationY Mathf.Clamp(rotationY, minimumY, maximumY) transform.localEulerAngles new Vector3( rotationY, rotationX, 0) else if (axes RotationAxes.MouseX) transform.Rotate(0, Input.GetAxis("Mouse X") sensitivityX, 0) else rotationY Input.GetAxis("Mouse Y") sensitivityY rotationY Mathf.Clamp(rotationY, minimumY, maximumY) transform.localEulerAngles new Vector3( rotationY, transform.localEulerAngles.y, 0) Here is my LookAtGameObjectScript using System.Collections using System.Collections.Generic using UnityEngine public class LookAtGameObject MonoBehaviour public Transform target public float speed 5f Update is called once per frame void Update() Vector3 direction target.position transform.position Quaternion rotation Quaternion.LookRotation(direction) transform.rotation Quaternion.Lerp(transform.rotation, rotation, speed Time.deltaTime) And And my method for turning off MouseLook and Turning on LookAtGameObject private IEnumerator LookAtGameObject() GameObject.FindWithTag("MainCamera").GetComponent lt MouseLook gt ().enabled false GameObject.FindWithTag("MainCamera").GetComponent lt LookAtGameObject gt ().enabled true yield return new WaitForSeconds(8f) GameObject.FindWithTag("MainCamera").GetComponent lt LookAtGameObject gt ().enabled false GameObject.FindWithTag("MainCamera").GetComponent lt MouseLook gt ().enabled true yield return null
|
0 |
How to destroy particles system after its work is over How can i stop particle system after player get destroyed
|
0 |
Show size dimensions of an object in Unity Inspector I want to see the size of the currently selected objects in the Unity Inspector, however I can't seem to find how to add it. Currently when I select a model in my scene, the Inspector panel shows info about its position, rotation and scale, but not the size of the object. What I want to achieve is to create a scene so that the objects in this scene have the correct proportions to each other, i.e. if a human has a size of 1.8 'units', an example car should be about 5 units long.
|
0 |
Should I use inheritance or interfaces for an inventory system? I'm about to start programmin an inventory, harvest and loot system. I will need enemies that drop items, harvestable environmentals that yield resources and an inventory system that takes items and resources. Should I solve this with interfaces, class inheritance or both? Why? Or is it just up to my programming style? I'm more familiar with inheritance, but if interfaces give an advantage I'd use them and get used to it.
|
0 |
How to increase the thickness (Size) of a plane in Unity I am making a small game where you have to roll around and not fall of a platform. I am using a plane to simulate the ground, but it is really thin. Is there a way to make it thicker by increasing a variable?
|
0 |
Are lightmaps also considered textures? I want my game to support phones with max texture size of 1024 so my texture atlases are 1024. My question is are lightmaps also considered textures and their max size must be 1024? Or they can have higher dimensions like 4096?
|
0 |
Voice Recorder in Unity I am using Unity for a user study and I am trying to integrate audio interview questions in the game itself. I need to record the user's input to an audio file. The closest thing I found was in this thread. https forum.unity.com threads save microphone recording to disk.378038 It works but it tries to save a 5 minutes clip at once. So, it takes a few seconds and the whole game is stuck for a few seconds. I want to create a thread that will continuously write the shorter clips to the file. I tried using a coroutine but I am having a hard time managing the header as it is dependent on the whole clip. Any suggestions or links to any threads I might have missed will be appreciated. Thanks!
|
0 |
How to rotate an object based on the movement and angles of Lifters I have Lifters that quot carry quot an object. I want the object to move and rotate based on how those Lifters move. Requirements include Supporting 1 4 Lifters at any side of the Object (e.g., both on one side, opposite, so on can't make any guarantees about their positions relative to the object) Supporting any orientation of the Object (e.g. the Object could be flipped on its side, sideways, or upside down can't make guarantees that Forward is always facing forward, etc) As such I implemented this by having the object move by setting its velocity to the average of the Lifters' velocity. Now, if not all of them move (or if there's a disparity in their velocities), I want the object to rotate, like so This is done by keeping track of how much an individual lifter has moved in a frame from the Object's position, and calculating the angle via m Angle Vector3.SignedAngle(lastPos transform.position, currentPos transform.position). This quot movement angle quot I add up for every Lifter and then at the end, Rotate the Object via Transform.Rotate(Vector3.up, m Angle). However, this approach has some problems Calculations are done along the Y axis and therefore does not angle the Object up or down if the Lifters have different vertical positions, m Angle actually overshoots, but I found simply dividing m Angle by the number of Lifters made it perfectly accurate. I do not know why this works. Because I want this to rotate the object in quot 3 dimensions quot , I have attempted to calculate the quot euler angles quot of each Lifters' movement via Vector3 oldDisplacement lastPos transform.position Vector3 newDisplacement currentPos transform.position Quaternion rotation Quaternion.FromToRotation(oldDisplacement, newDisplacement) m EulerAngles rotation.eulerAngles And then at the end, I rotate the Object based on these quot movement angles quot transform.Rotate(m EulerAngles, Space.World) This works in three dimensions, however it is off in the same way that m Angle was before I divided it. It rotates the object too far. On top of that it seems to produce rotations along axes that have no displacement. I want the object to only rotate exactly by the angle created by the Lifter's movement. This should keep it quot synced quot to Blue instead of rotating past as you see here. When I check how much rotation Blue is adding per frame, I get an output like so Blue is adding (0.000, 359.507, 0.066) on movement ( 0.015, 0.000, 0.000) Despite moving solely on the x axis, there is a z euler angle being created, and the y euler angle of 0.493 degrees is too much for 0.015f movement. I do not know why rotation.eulerAngles is inaccurate in my usage. The only issue I can perceive is that since the Object's position is also moved at the end, the angle calculation assumes it is not moving and generates a larger angle (e.g., perhaps newDisplacement should be something like currentPos (transform.position m Body.velocity Time.deltaTime) ). However, removing the Object's movement from the finalPosition of the Lifter seemingly has no effect. Or perhaps there is some finite precision in Quaternion.FromToRotation? Or my math is incorrect in some way? I'd love a sanity check on the code or approach or if I should approach this problem from a different perspective. EDIT Here's an example gif of the functionality with m EulerAngles code (so the rotation overshoots, but works in 3D also I recorded the gif at lower fps that's not the game's framerate)
|
0 |
GameObject scope over RPC call Debugging my code I faced some unexpected behavior. I called an RPC using uLink.NetworkView on the server passing some parameter including a GameObject tagged as Player. Inside that RPC I make a call to GameObject.FindObjectsWithTag("Player") What I refer to by saying "unexpected" is that that function returns all the gameobjects in hierarchy INCLUDING the gameobject passed as parameter to the RPC call. I noticed that inside the editor it appears in hierarchy the gameobject passed to the RPC but without all the components BUT the transform. My question is to know exactly how the scope is working, I seem to understand that the scope of the FindObjectsWithTags seems to include RPC parameters but without the most informations. Any clue about this?
|
0 |
Clearing a gizmo list (OnDrawGizmos) I have a list of gizmos in a simple gizmo drawing manager. This list is updated from different parts of the codebase, usually from Update() methods. It goes something like this public class RenderGizmos Singleton lt RenderGizmos gt private List lt GizmoData gt gizmos new List lt GizmoData gt () public void AddNewGizmo(GizmoData gizmos) this.gizmos.AddRange(gizmos) public void AddNewGizmo(GizmoData gizmo) this.gizmos.Add(gizmo) void OnDrawGizmos() if (gizmos null) return for (var i 0 i lt gizmos.Count i ) draw gizmos Can you advise me on when to clear the gizmo list? Ideally I would like to clear it every frame. However Clearing it at the end of the OnDrawGizmos() method will render no gizmos (as I suspect this method might be called several times a frame). Clearing it in an LateUpdate() Update() method is dependent on execution order, sometimes it draws gizmos, sometimes it doesn't Clearing it in a Coroutine has rendered no gizmos (but it might just be dependent on the execution order as well) I would like not to be dependent on the execution order so I prefer not to use the Script Execution Order system.
|
0 |
Smooth rotation for a bone? I'm trying to make my character bone "chest" rotate smoothly when face enemy and get back to his stand. Can anyone help me with this ? public Transform Target public Vector3 Offset Animator anim Transform chest public float rotation speed public bool aim at traget false void Start() anim GetComponent lt Animator gt () chest anim.GetBoneTransform(HumanBodyBones.Chest) void LateUpdate() if (aim at traget true) smooth rotation to face target chest.LookAt(Target.transform.position) chest.rotation chest.rotation Quaternion.Euler(Offset) else get back to you stand smoothly
|
0 |
Reducing mobile build size This is my second time making and game and I want to make sure that I fit under 50 mbs. So far my plan is to fit all the games artwork into two 2048x2048 sprite sheets. I tested a empty unity3d project and when the apk was made it was 19 035 KB of size. Where does this overhead come from and how can I reduce it? This is not a duplicate question of this one. I'm asking why building a completely empty project results in a apk with a size of 19 MB. Does this mean that I have limit my assets to 30 MB so that the complete app will be less than 50 or is there a way to strip some of those initial 19 MB.
|
0 |
Animate moving object I have a sphere shot out of a cannon which i need to get lined up with another sphere when and if the two spheres collide. Considering that both spheres are moving (one in X and the other is shot at the first one) how would i animate the cannon sphere to line up if the collision occurs? I can use a bool to check if collision but how do i animate the projectile in the animation tab so that the projectile takes into consideration the always changing position of the X moving sphere ?
|
0 |
How can I find the distance from bezier curve anchor points to control points for a circle approximation and their positions From the image below, I have represented a circle by a closed bezier curve made of two cubic bezier segments. I am aware that a bezier curve cannot represent a perfect circle. How can I calculate the distance from the anchor points to the control points based on the distance from both anchor points to give a close approximation of a circle? Also how can I use the calculated distance to find the positions for the control points?
|
0 |
How to create a forest game scene in unity3d? I am pretty new to game development. I have started using unity3d. I have created simple games for which I have used plane (3d gameObject). Now, I want to move a step forward I want to create a forest with mountain and trees. So, I went through few tutorials and concluded terrain (3d Object) will be best fit. Issue My player falls down from the terrain due to gravity and if i disable gravity then my player flies up in y axes when moved over mountains. What is the way i can create terrain with gravity and so that my player doesn't fall from the terrain. Can anyone throw light on how do overcome above mentioned issue.
|
0 |
When the motion button is pressed, the shape of the character changes and always goes to the left direction good day. When the motion button is pressed, the shape of the character changes and always goes to the left direction. Why is this happening and what is the solution? Pressing two buttons moves to the left and the shape changes. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerKontrol MonoBehaviour public float karakterHizi 8f, maxSurat 4f private Rigidbody2D myRigidbody private Animator myAnimator private bool solaGit, sagaGit void Awake () myRigidbody GetComponent lt Rigidbody2D gt () myAnimator GetComponent lt Animator gt () void FixedUpdate () if (solaGit) SolaGit () if (sagaGit) SagaGit () public void AyarlaSolaGit (bool solaGit) this.solaGit solaGit this.sagaGit !solaGit public void HareketiDurdur () solaGit sagaGit false myAnimator.SetBool ("run", false) void SolaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0)) void SagaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0))
|
0 |
Best practice child and parent script What is the best practice coming to where to place the code in this scenario. I have a gamobject called player. It has lots of child objects. One of them is sword. Like this Player Body Head Torso Sword So i have code that controls the player in player. It controls movement and triggers an attack animation which swings the sword. The code that checks if the sword is swinging and if it has hit something is at the moment inside the sword. My question is, what model is best practice? I can think of some All code in player. player checks if sword is colliding and handles what happens to the enemy that was hit. sword checks for collision but player handles it by polling sword and takes care of what happens with enemy and player after. sword checks for collision but player handles it by listening to an event that sword triggers and takes care of what happens with enemy and player after. sword handles everything by handling what happens to enemy and player communicating with parent through a reference.
|
0 |
Toggle Button click doesn't count when the Mouse Up happens outside of the button area I have a problem with my toggle buttons. When a user performs the Mouse Up of the toggle button outside the button area, the click is not counted. Mouse Down and Mouse Up on the button area works. Mouse Down on the button and Mouse Up outside, does not work.. Just to avoid confusion, the Mouse Down is when you click, the Mouse Up is when you lift the finger from the mouse button. Do you have any idea how to solve this? I'm using Unity. Thanks for your help!
|
0 |
Unity3d webplayer failed to download data file When testing my game web builds on localhost, I get the error "Failed to download data file". The game data file is correctly placed, and the page loads fine, it just wont download the plugin, or prompt me to do so. I tried the following things Add MIME Types to IIS 7.5 Open IIS Manager Double click "MIME Types" in the IIS section. Click Add on the right side "Actions" menu. File name extension .unity3d MIME type application unity3d click ok Restart the server (right side "Actions" menu) That didn't work for me specifically because it turned out I was using IIS Express, so I did the following If Windows 7, browse to 'C Users Documents IISExpress config ' and open the file ApplicationHost.config. Search for 'staticContent' and add the following before the closing tag However, again, it didn't work..
|
0 |
Unity get reference of GameObject under another GameObject I am trying to get reference of the object underneath my Player. I don't know if I am aproaching this correctly. Right now, I have a player simply put in the scene, like this Then I am trying to get reference of it like this (does not work) public void CheckTileUnder() Vector3 halfExtents new Vector3(0f, 1 2.0f, 0f) Collider colliders Physics.OverlapBox(transform.position, halfExtents) foreach (Collider item in colliders) Tile tile item.GetComponent lt Tile gt () if (tile ! null) RaycastHit hit if (Physics.Raycast(tile.transform.position, Vector3.down, out hit, 1)) currentTile tile Another aproach that I thought of would be to put the player under the Tile like this Then I guess I would have to change parents like suggested in one of the answers here? How should I select the Tile under the Player?
|
0 |
Game App deep linking is working in all android phone, but it is not working in tablets . Do i need to add any manifest code to work it in Android? This is my manifest, which is used for App indexing auto complete and deep linking.
|
0 |
Can you use a sprite with uneven dimensions in Unity 2D? I'm new to game development as a whole, so forgive me if this is an idiotic question in itself, but I want to use a sprite sheet where the entire sprite sheet's dimensions are 104x144, and the dimensions of an individual "pose" of the sprite is 26x36. If I can use this sprite, and I'm asking if I can, what Pixels Per Unit would I put? Again, I have absolutely no idea how this works, and I'm probably being a huge idiot about this entire thing.
|
0 |
Unity Mathf.Atan2 algorithm complexity using Unity5.5.1f using C So I have a circle (2D) divided equally by 16 directions, and I also have a direction V which is different from the other 16. In order to know which direction is the closest I thought of two apporaches Dot product between V and all the other directions and choose the max one Store atan for all the 16th directions then compute atan for V and see which angle is the closest to V's My questions are,does anyone know what is the complexity of Mathf.Atan2? Or of an Atan2 algorithm in general? I read it gets worse and worse as the angle becomes bigger, is it true?
|
0 |
How can I parse different types of objects from JSON? I'm trying to save the player's inventory as a JSON data but I'm having a problem. I have a class Sword which extends an abstract class Weapon which extends another abstract class called Item. This is what JSON file looks like with the Sword and Armor objects in it "category" "type" "Weapon", "subtype" "Sword" , "id" 0, "value" 1, "name" "Wooden Sword", "description" "Sword made out of wood", "slug" "wooden sword", "stats" "wear" 100, "damage" 5 , "category" "type" "Armor", "subtype" "Helmet" , "id" 1337, "value" 1, "name" "Steel Helmet", "description" "Whatever...", "slug" "steel helmet", "stats" "wear" 100, "defence" 5, "vitality" 3, "dexterity" 1 How can I parse these objects into their respective C objects, putting the first entry into a Sword object and the second one into a Helmet object. There will be other types of objects in there too, so it's not limited on these two.
|
0 |
NavMeshAgent.CalculatePath how to use properly? I seriously can't figure out how to use this function, and the documentation doesn't help at all. Here's the documentation code public class ExampleClass MonoBehaviour public Transform target private NavMeshAgent agent void Start() agent GetComponent lt NavMeshAgent gt () NavMeshPath path agent.CalculatePath(target.position, path) if (path.status NavMeshPathStatus.PathPartial) Here's my code public class Movement MonoBehaviour NavMeshAgent agent NavMeshPath path void Start () agent GetComponent lt NavMeshAgent gt () void MoveToTargetLocation() agent.SetDestination(targetLocation) lt being set somewhere else NavMeshPath path agent.CalculatePath (targetLocation, path) if (path.status ! NavMeshPathStatus.PathPartial) if (Vector3.Distance (curLocation, targetLocation) gt 0.55) animation.CrossFade (animationRun.name) moving true else animation.CrossFade (animationIdle.name) moving false The error I'm receiving is Assets Movement.cs(59,54) error CS0165 Use of unassigned local variable path' Am I supposed to be setting the path somewhere else?
|
0 |
Unity Instantiate an object respecting the prefab's default rotation Simple question, I hope. I've built a variety of prefabs for an isometric shooter game (hazards, enemies, health indicator bars, popup texts, shots, explosions). All of these prefabs were constructed with default rotations appropriate for the gameplay. My problem is that Instantiate() will overwrite the default rotation of the prefab with whatever is specified as the rotation parameter. So I'm left with hard coded rotations in my Instantiate() calls to get things oriented correctly in the X Z plane. (0,180,0) and (90,0,0) are common ones. I'd much prefer to Instantiate prefab gameObjects consistently with "no change to their default rotation," but I'm not sure how to accomplish this. Thanks for the help, Mike.
|
0 |
How can I fix the turret is facing the opposite direction of the target? This script is attached to the turret parent. The object that rotate on X and Y is the child Cube of the Cylinder. The target is the Sphere. using System.Collections using System.Collections.Generic using UnityEngine public class TurretAI MonoBehaviour SerializeField private float turnRateRadians 2 Mathf.PI SerializeField private Transform turretTop the gun part that rotates SerializeField private Transform bulletSpawnPoint SerializeField public GameObject target void Update() TargetEnemy() void TargetEnemy() if (target ! null) Vector3 targetDir target.transform.position transform.position Rotating in 2D Plane... targetDir.y 0.0f targetDir targetDir.normalized Vector3 currentDir turretTop.forward currentDir Vector3.RotateTowards(currentDir, targetDir, turnRateRadians Time.deltaTime, 1.0f) Quaternion qDir new Quaternion() qDir.SetLookRotation(currentDir, Vector3.up) turretTop.rotation qDir This is a screenshot of the parent turret that I set to be static so it will not rotate too and the script attached to it This is a screenshot of the Cube that rotate on X and Y and should be facing the target And the missels And last when running the game you can see the Sphere target position and the turret is facing the opposite direction. If I will drag and move the Sphere the turret will rotate to it but with the missels back instead with the missels front side
|
0 |
Emission for Mobile Shaders? I need to use Emission texture to my model, but I can't find any emission parameters in mobile shaders. I searched this on google, but there's nothing helpful to me. How do I add emission for mobile shaders, without writing own shader code? (I'm keep studying shader but still not good at)
|
0 |
Unity apk vs aab for the same scene I'm new to Unity , i use mac os catalina , unity 2019.4 and build for android mobile. I downloaded a unity project from internet. It's already in format of unity project. so i just copy it into my unity folder. THere's only 1 scene there. I can load , run and built with no problem. It created 160mb of .APK file. But now i need to bring this project into my other project (let's name it B project ). Basically i only need to bring that single scene (and all its linked assets) into that B project. What is the proper way to do this ? Last time, what i did was i export the whole things as package then imported it into my B project. When i open the scene , i can run and build with no problem. But it create .AAB rather than .APK and size is 300mb (2x of the previous APK). Is this big size become the reason it become AAB ? Can someone tell me what's wrong ? why the size is doubled when i just build the same scene. Does unity build includes unused asset ? because in B project there's already asset from my other scenes. What is the proper way to do this ?
|
0 |
Conservation of energy of a bouncy ball in Unity3d My problem is that in the project I have a ball with a physicMaterial where Dynamic Friction and Static Friction both are 0 Bounciness 1 Friction Combine is set to Multiply Bounce Combine is set to Maximum This ball has a rigid body attached in which mass 1 drag and angular drag both are 0 useGravity true There are some cubes which create a boundary for the ball to bounce inside. The ball bounces in a closed boundary. The problem is overtime its top velocity keeps on increasing and after sometime it gets out of the boundary. I want the velocity of this ball to NOT exceed a provided maxVelocity. Here i am sharing my project through google drive bounceProblem.unitypackage
|
0 |
World position into local position I want to understand how I can convert world position of an object into local position. Especially how to deal with a rotation of objects. I'm testing transform.InverseTransform(...) methods. When parent and child has 0 rotation, this methods easily convert world into local position. I don't know how to deal with a situation, when one of the objects has not zero rotation. In the example below my parent object has (0,0,10) position and (0,0,0) rotation. Child position (0,0,0) and rotation (90,0,0). Debug.Log (string.Format ( quot World position 0 nLocalPosition 1 nInverseTransformPoint 2 nInverseTransformVector 3 nInverseTransformDirection 4 nTransformPoint 5 nTransformVector 6 nTransformDirection 7 quot , transform.position.ToString (), transform.localPosition.ToString (), transform.InverseTransformPoint (transform.position).ToString (), transform.InverseTransformVector (transform.position).ToString (), transform.InverseTransformDirection (transform.position).ToString (), transform.TransformPoint (transform.localPosition).ToString (), transform.TransformVector (transform.localPosition).ToString (), transform.TransformDirection (transform.localPosition).ToString ())) The example debug result World position ( 1.0, 0.7, 10.0) LocalPosition ( 1.0, 0.7, 0.0) InverseTransformPoint (0.0, 0.0, 0.0) InverseTransformVector ( 1.0, 10.0, 0.7) InverseTransformDirection ( 1.0, 10.0, 0.7) TransformPoint ( 2.1, 0.7, 9.3) TransformVector ( 1.0, 0.0, 0.7) TransformDirection ( 1.0, 0.0, 0.7) What should I add to transform.InverseTransformPoint (transform.position) to get transform.localPosition?
|
0 |
How UV channels work in Unity? So this Graph Shader is using UV0 channel As far as I know, UV layout in a 3d model file (e.g. fbx) is stored inside the model itself, is that right? But the picture above implies that a model can contain multiple UV channels inside of itself. Is that true?
|
0 |
When using Prefab Mode only one game object is adjusted while the others need to be manually selected in hierarchy window for changes I created a bezier curve prefab using the code in the post How to create an illustrator photoshop like pentool for creating bezier curves in Unity. I added a few copies of the prefab to my scene. When I open the original prefab in prefab mode (I am using Unity 2019.1.0a8) and adjust any of the points it only affects one of the prefabs, the changes are not recognised in the scene view till I select the other objects manually. I added SceneView.RepaintAll() after calling path.MovePoint(i, newPos) in the Draw() method but it still doesn't update the others. Could it be that I haven't serialised by variables correctly? How can I get all of the objects created from the prefab to recognise changes immediately when the original prefab is altered?
|
0 |
Unity difference between accessing asset prefab from reference VS from Resources.Load? Question point Does putting prefab asset in inspector's reference and access its content inside in runtime VS. Load the same prefab asset from Resources.Load API, will both cause entire prefab to load and use same memory footprint? Backgroud In UNET or it's replacement lib, Mirror, you will have to register list of prefab on NetworkManager to spawn on server and clients. Under the hood, these prefab references will be sent to registration function ClientScene.RegisterPrefab which in turn access them as far as prefab.GetComponentsInChildren lt NetworkIdentity gt () (I suspect that this will make entire prefab loaded?) VS I put those prefab in Resource folder, then use API like Resources.Load LoadAll to send them to ClientScene.RegisterPrefab (which proved to work too) But many fellow dev warned me about how evil Resources API is and using these will load all data into memory, etc. Didn't this 2 way ultimately need to access inside of prefab and both need to load entire prefab in? Is there clear advantage for memory footprint for approach? Some prior research In official document about resource management, there is some explanation about how resource will load but it still does not clear up difference between these 2 appraoches. 2.7. Resource lifecycle To reduce loading times and manage an application's memory footprint, it's important to understand the resource lifecycle of UnityEngine.Objects. Objects are loaded into unloaded from memory at specific and defined times. An Object is loaded automatically when The Instance ID mapped to that Object is dereferenced ... Foot note Some clarification Why do you need to use Resources.Load? Take UNET example case here in my question, and notice that it needs to know every prefab that will be use in game, that's including monsters, items, bullet. Sure you can drag and drop these to inspector (like in screenshot) but will become tedious and unorganized very fast on magnitude of 50 prefabs. So instead I organize them to Resources folder like Assets Resources EnemyPrefab Stage1 . Assets Resources EnemyPrefab Stage2 . Assets Resources ItemPrefab . To get more organized load pattern. Resources.LoadAll lt GameObject gt ("EnemyPrefab Stage1") will do as it suggest. And skipping tedious inspector drag and drop work, let alone checking what did I missed to drag and drop. Can't you just profile it yourself? why asking here? I could, but if someone already done this work or has knowledge to confirm such behavior, this could be better, thus this question here. And hey, didn't this is how knowledge is shared and this site is for?
|
0 |
Why is my color on my obj not showing in Unity! I've been trying to import my full color obj files to unity for a while now, but I can't get them to be in color. All of the colors show up in Meshlab, but not in Unity. All of the youtube videos I have watched have said that I need some sort of texture file but my obj doesn't have one. It is just the obj and it somehow has color in Meshlab. Is there some sort of setting I need to change in Unity? If I need a texture file for it to work, is there a way I can extract the texture file(s) from the obj?
|
0 |
How to flick gameObject using Touch? I've been searching for a solution for my problem for a while on the web, but i didn't find anything that work properly What i want to do I have a bouncing ball and I want to let the user flick it with his finger (using a swipe gesture or whatever). The ball shouldn't start moving unless the player flick touch the ball. I don't want the ball to move if the player flicks anywhere on the screen, only if the flick touch the ball What i've done so far I've tried to write a script which would detect the touch starting position and the touch end position, and check if the end position is the same as the ball position to make sure that the flick touch the ball. Then the script calculate the direction vector by substrating the start position from the end position. After that i use the AddForce methode and give it the direction vector as a parameter. Here's my code, (it's better than 1000 words ) using UnityEngine using System.Collections public class Movement MonoBehaviour public Vector2 start public Vector2 end public Vector2 direction public Vector2 ballPos public float Flicktime void Start() void Update() ballPos new Vector2(transform.position.x,transform.position.y) if (Input.touchCount gt 0) Touch t Input.touches 0 if (t.phase TouchPhase.Began) start Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0)) if (t.phase TouchPhase.Ended t.phase TouchPhase.Canceled) end Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0)) direction end start if(t.position ballPos) rigidbody2D.velocity direction 2 What's the problem ? The problem is that the code doesn't work. When i launch the game in the Unity Remote 4 app in my android device and try to flick the ball it doesn't move, the inspector shows that the the scripte is calculating the start amp end positions and the direction vector, but the ball doesn't move, it stays in the same position even when the flick touch the ball. So what's the problem ? is there a better way to do it ? Since the ball have a circle collider how to make it detect collision with the player swipe ? Thank's and have a nice weekend !
|
0 |
How to Implement a Very Simple Game State Manager in Unity? I ve tried a bunch of different implementations, and trawled everything online I could get my hands on. Everything has downsides, nothing plays nicely with how Unity wants you to work. Let s keep it simple. You want to track in game time. You want this to be available as a ScriptableObject. You need a MonoBehaviour to keep the time updated. You want to ensure there s just one such GameState ScriptableObject and one such GameStateManager MonoBehaviour. You don t want to manually add the manager to all scenes. Is there a standard and sane way to achieve this without resorting to black magic? To keep this grounded, here s the boilerplate ScriptableObject CreateAssetMenu(fileName "GameState", menuName "ScriptableObjects GameState") public class GameState ScriptableObject lt summary gt The time passed in game, in game time, in seconds. lt summary gt public float TimePassed get private set 0.0f lt summary gt Moves the in game time and date forward. lt summary gt lt param name "addedGameTime" gt Time to add, in in game seconds. lt param gt public void MoveTimeForward(float addedGameTime) Move the time passed forward TimePassed addedGameTime And MonoBehaviour public class GameStateManager MonoBehaviour lt summary gt The state of the game. lt summary gt public GameState gameState Start is called before the first frame update void Start() If we use a Singleton, and not drag a reference using the editor gameState GameState.Instace Mark that this should not to be destroyed when loading new scenes DontDestroyOnLoad(gameObject) Update is called once per frame void Update() Update the in game time gameState.MoveTimeForward(Time.deltaTime)
|
0 |
Particles emit even though emission is disabled I have created a basic particle system which is a single burst around a sphere. I have a script that disables this emission upon Start. If I don't disable the emission, then the particles continuously emit in bursts. However when I disable the emission, it does not completely prevent particles from being emitted. There is still a single burst at the beginning. Here is how it looks with emission disabled Here is the script which is setting emission.enabled false. This is attached to the sphere and the particle system is a child of the sphere. using System.Collections using System.Collections.Generic using UnityEngine public class BalloonPop MonoBehaviour public new Renderer renderer public ParticleSystem emitter public float explosionTime 0.5f private ParticleSystem.EmissionModule emission void Start() if (!renderer) renderer GetComponentInChildren lt Renderer gt () if (!emitter) emitter GetComponentInChildren lt ParticleSystem gt () emission emitter.emission renderer.enabled true emission.enabled false lt this All I want to do right now is to make it not emit any particles at all.Then I'll add an event to re enable the emission, but that's not the issue I'm asking about here. I also tried emitter.enableEmission false, which is deprecated, and it didn't work. Here is the particle system in the inspector
|
0 |
Cannot find GameController script causing errors with logging and references I am learning the Unity engine and have been practicing with various tutorials, but there is a curious error I am experiencing with the space shooter tutorial. Collisions with the player ship do not destroy asteroids or the player, while collisions with bolts fired by the player will destroy the asteroids but not increase the score at all. The error being logged is "Cannot find GameController script" which makes me think there is a problem with my code below, specifically the void Start() function that checks if GameController ! null. Is there something about Unity 5 that differs from Unity 4 that I would need to change? Or have I made a mistake in this code attempting to reference the GameController script? using System.Collections using System.Collections.Generic using UnityEngine public class DestroyByContact MonoBehaviour public GameObject explosion public GameObject playerExplosion public int scoreValue private GameController gameController void Start() GameObject gameControllerObject GameObject.FindWithTag("GameController") if (gameController ! null) gameController gameControllerObject.GetComponent lt GameController gt () if (gameController null) Debug.Log("Cannot find 'GameController' script") void OnTriggerEnter(Collider other) if (other.tag "Boundary") return Instantiate(explosion, transform.position, transform.rotation) if (other.tag "Player") Instantiate(playerExplosion, other.transform.position, other.transform.rotation) gameController.GameOver() Debug.Log(other.name) Destroy(other.gameObject) Destroy(gameObject) gameController.AddScore(scoreValue)
|
0 |
Can I always assume that fixed time step in Unity is reliable? I was thinking about games on low end machines or phones where the CPU would be limited. If I were to move all of my game logic into FixedUpdate() can I assume that it will always be called with the same time delta? Or would it still be worth adding code to make it take the actual time delta into account?
|
0 |
Is there a way to organize colliders? I am using a tilemap to design levels for my game in Unity. So, naturally, I need some circle box colliders to interact with the objects in the game. I know that if I use a prefab for every tile, I can also attach a collider, and never have to worry to add or modift colliders. But this seems too impractical, and also if I want to modify a block of colliders, I have to do this for every single tile. I also tried using Tilemap Colldier 2D, but it generates colliders for the places I don't want colliders, such as grasses that stick out from the ground tiles. My question is, is there any neat way to organize colliders so that I can identify them by looking at their names, IDs, etc.? Currently, I am designing only one level and anxiety builds up on me as I take a look at the colliders in a single tilemap. How can I automate or organize the colliders for my tilemap?
|
0 |
On Click Add Listener not working on Game Object I have this code attached to a 3D cylinder game object. I plan to use it as an arrow and rotate it when clicked and dragged. I had no idea what do as I am a beginner so I started with adding an onClick listener to a Button component on the Cylinder, and wrote this script which I added as component to the cylinder.. But the Rotate() function isn't called when I click on it, as there is no message in the Log.. This is the code using UnityEngine using System.Collections using UnityEngine.UI public class MoveAim MonoBehaviour public bool isAiming private Button button void Start () isAiming true button GetComponent lt Button gt () button.onClick.AddListener (Rotate) Debug.Log ("Start!") void FixedUpdate () void Rotate() Debug.Log ("Click recorded") Any idea what to do? And how should I implement the rotation of the cylinder? Help would be appreciated! Thanks!
|
0 |
Reducing total file size of multiple Unity games Our product consists of many small stand alone games, some made in Unity and some made in other languages. These games can be launched from a hub. The file size of the Unity games is quite large, since each game is being build to work as a stand alone game. When looking inside the folders, I can see that many of the files, folders and dlls are the same, so I thought that it would be possible to re use these across all the games to reduce the file size of our installer. So far I have successfully moved the games' exe and Data folders into one folder so they can re use the MonoBleedingEdge and UnityPlayer.dll, but I was hoping to be able to share even more resources than this. All the games are built using Unity 2019.1 and all of them are using many of the same libraries and dlls. Does anyone have experience bundling many Unity games like this? Is there some configuration for Unity that will help with allowing shared resources?
|
0 |
Unity How to detect if a UI button is pressed down? I want a UI up arrow button to be able to detect if it is pressing down. It is a child of a canvas in a 3D scene. My target platform is webGL for both desktops and mobiles. I coded not only the control of the up arrow UI button but also the control of keyboard arrow button for desktops. The keyboard control worked fine in PC but the UI arrow button didn't work as expected both in desktop and mobile. I tried the OnPointerDown() function attaching to the UI up arrow button and the logged it. The log didn't even show up when the UI button is pressed down both in desktop and mobile. It seems the OnPointerDown() needs the image of the button to receive raycast so its image component Raycast target option is on. Isn't the onPointerDown() supposed to be used in detecting press down of UI component by both mouse in desktop and touch in mobile? How to get the UI button to be notified when it is pressed down? Any approach other than onPointerDown() which can do the same thing? My scripts are here the one attached to the car object to be controlled using UnityEngine public class CarPlayerControl MonoBehaviour public float speed 40 private bool touchCtrl false private float xInput 0f private float zInput 0f void Awake() if (Input.touchSupported amp amp Application.platform ! RuntimePlatform.WebGLPlayer) touchCtrl true void FixedUpdate() xInput 0f zInput 0f if (touchCtrl) else keyboard control in desktop xInput Input.GetAxis("Horizontal") zInput Input.GetAxis("Vertical") Move(xInput, zInput) public void Move(float xInput, float zInput) float xMove xInput speed Time.deltaTime float zMove zInput speed Time.deltaTime float x KeepXWithinRange(xMove) float y transform.position.y float z KeepZWithinRange(zMove) transform.position new Vector3(x, y, z) private float KeepXWithinRange(float xMove) float x transform.position.x xMove return Mathf.Clamp(x, 0, 900) private float KeepZWithinRange(float zMove) float z transform.position.z zMove return Mathf.Clamp(z, 470, 500) and the one attached to the UI Up arrow button using UnityEngine public class ButtonUpControl MonoBehaviour, IPointerDownHandler, IPointerUpHandler public GameObject car private CarPlayerControl carPlayerControl private bool mouseDown private float xInput void Awake() carPlayerControl car.GetComponent lt CarPlayerControl gt () mouseDown false void Start() void FixedUpdate() if (mouseDown) xInput 1.0f else xInput 0f carPlayerControl.Move(xInput, 0f) public void OnPointerDown(PointerEventData eventData) mouseDown true Debug.Log("on ptr down btn up ") public void OnPointerUp(PointerEventData eventData) mouseDown false Debug.Log("on ptr up btn up ")
|
0 |
Alternative for using game object prefabs for level generator I just finished the Unity Tutorial for creating a simple 2D roguelike Mobile Game. Now I wanted to make my level bigger finding or creating my own algorithm isn't the problem. My problem is that creating a game object or using a prefab for every single floor or wall tile is a bad idea. (Map 200x200 40000 objects). A comment under the tutorial said that and I'm incline to believe it. That much I can understand, but I can't find a alternative. What can I use besides object prefabs? Sidenote I have decent programming skills, but am beginner with Unity. The tutorial I followed https www.youtube.com playlist?list PLX2vGYjWbI0SKsNH5Rkpxvxr1dPE0Lw8F I want to make the maps there bigger, but then everything goes slow motion.
|
0 |
In Unity, how do I create a drag and drop object? I have a 2d scene. I want the player to be able to pick up an object, move it around the scene and drop it somewhere. I can't find any way to do this, and all of the resources for Unity are really daunting and I can't find anything relevant to what I'm doing. I've tried adding the drag rigidbody script to both my camera and the sprite I want to drag, to no effect. Where can I find relevant documentation for stuff like this? Basic things like how to implement a script or what objects I need to attach these scripts to the stuff on the unity website is a little too advanced.
|
0 |
Unity with move gameobject line renderer I create DrawLine class, I want my character to follow the line I draw. How do I move my character on draw line renderer ? Thanks! public class DrawLine MonoBehaviour public GameObject linePrefab public GameObject currentLine public LineRenderer lineRenderer public EdgeCollider2D edgeCollider public List lt Vector2 gt fingerPositions void Update() if (Input.GetMouseButtonDown(0)) CreateLine() if (Input.GetMouseButton(0)) Vector2 tempFingerPos Camera.main.ScreenToWorldPoint(Input.mousePosition) if (Vector2.Distance(tempFingerPos, fingerPositions fingerPositions.Count 1 ) gt .1f) UpdateLine(tempFingerPos) void CreateLine() currentLine Instantiate(linePrefab, Vector3.zero, Quaternion.identity) lineRenderer currentLine.GetComponent lt LineRenderer gt () edgeCollider currentLine.GetComponent lt EdgeCollider2D gt () fingerPositions.Clear() fingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition)) fingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition)) lineRenderer.SetPosition(0, fingerPositions 0 ) lineRenderer.SetPosition(1, fingerPositions 1 ) edgeCollider.points fingerPositions.ToArray() void UpdateLine(Vector2 newFingerPos) fingerPositions.Add(newFingerPos) lineRenderer.positionCount lineRenderer.SetPosition(lineRenderer.positionCount 1, newFingerPos) edgeCollider.points fingerPositions.ToArray()
|
0 |
In Unity, can I load a local ( Resources folder) website to safari on an ipad In Unity, can I load a local ( Resources folder) website to safari on an ipad? This works fine on a Mac, opening up a wepage from my Resources folder. string path "file " (Application.dataPath) " Resources testsite.html" void OnGUI() if(GUI.Button(new Rect(20, 20, 100, 100), "site")) Application.OpenURL(path) but when I try to load this on an iPhone or iPad, it doesn't seem to work. Am I accessing the address incorrectly for iOS using "file "? If this is not possible, is there an alternative way I can load a locally stored website on an iOS device?
|
0 |
How to disable gravity for a RigidBody moving on a slope? I created a script that handles movement for my player (moving around, going down and up slopes). However, since I'm using a RigidBody not a CharacterController when I go up slope and stop on the middle of it the gravity pulls me backward, which is fine, but the problem is when I move forward, the gravity force pulls me backward when I'm trying to go forward. This problem wouldn't have appeared if my character wasn't a sphere but my character is a sphere so it always roll down when gravity is applied to it. What I want is to somehow stop the gravity for a second or reset it to zero when I move my character, and when I'm going up a slope so it won't hold me back. I tried if(grounded) rb.velocity Vector3.zero but I don't think it's the right approach.
|
0 |
How to create a custom set of coordinates based on two points in Unity? As the title says, I am having problems finding a way to create a new set of local coordinates based on two points. Here is an example Consider that the two gameObjects are not one parent of another, therefore I cannot use something like transform.localPosition, furthermore I tried using transform.TransformPoint(), however the latter works only if if I want to create it with respect to a single point. I think it is a silly question, yet I am not finding a way to solve it, so any help is greatly appreciated!
|
0 |
How to change animation start end proprieties via script? Is there a way of changing the start end proprieties (Transform, Rect Transform, etc..) of an animation via script? Like, I have 5 objects that start at the same position but should end in different positions, so I would like to change the end positions of each one via script. As I haven't found a way to do this, I created 5 animations for this, but I'd like to just have one animation and change its proprieties in runtime.
|
0 |
Convert a string to a gameobject name I want to use a string to reference a gameobject that I already have in my code, but the console says that you can't convert a string to unityengine.object. I have a string that says aaaa and a gameobject that has the name aaaa. using System.Collections.Generic using UnityEngine public class WorldRenderer MonoBehaviour public Transform Tile string seed quot aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacaaabaaaaaaaa quot public int worldHeight public int worldWidth private int seedSub 0 public GameObject aaaa public GameObject aaab public GameObject aaac void Start() transform.position new Vector3(worldWidth 2 0.64f 0.32f, worldHeight 2 0.64f 0.32f) for (int height 0 height lt worldHeight height ) transform.position new Vector3(worldWidth 2 0.64f 0.32f, transform.position.y) transform.position transform.position new Vector3(0, 0.64f) for (int width 0 width lt worldWidth width ) seedSub seedSub 1 transform.position transform.position new Vector3(0.64f, 0) Here's the problem VVV GameObject tilepos Instantiate(seed.Substring(seedSub 4 3, 4)) as GameObject Here's the problem tilepos.transform.position new Vector2(transform.position.x, transform.position.y)
|
0 |
Unity Duck volume of audio source inside a boxed area I'm trying to lower the volume of an outside ambient wind sound while the player is inside a building or room. Is there any way in Unity to do this without scripting? Or would I have to script this to check whether the player is in a certain collider to duck (or lowpass filter) the sound? The room is seamlessly in the scene's outside environment. Any ideas on this?
|
0 |
GameObject scope over RPC call Debugging my code I faced some unexpected behavior. I called an RPC using uLink.NetworkView on the server passing some parameter including a GameObject tagged as Player. Inside that RPC I make a call to GameObject.FindObjectsWithTag("Player") What I refer to by saying "unexpected" is that that function returns all the gameobjects in hierarchy INCLUDING the gameobject passed as parameter to the RPC call. I noticed that inside the editor it appears in hierarchy the gameobject passed to the RPC but without all the components BUT the transform. My question is to know exactly how the scope is working, I seem to understand that the scope of the FindObjectsWithTags seems to include RPC parameters but without the most informations. Any clue about this?
|
0 |
Get mouse touch position for NGUI event Since I am using NGUI, to capture mouse events I use their methods such as void OnPress (bool isDown) How can I check the mouse touch position that corresponds to this particular OnPress event?
|
0 |
Preventing character's movement if it won't fit(Unity2D) I'm creating a pacman game copy and I set up my movement. But there's a problem. My character can try to go up whenever I press but in the original you cannot go if there's a wall above you or your character won't fit. For example in this situation you can still go up but you'll bounce off wall. So my question is how to prevent character from movement if there's a wall or it won't fit there.
|
0 |
How do you execute Trigger collider collision only in one gameobject? I'm trying to deal with units (generated from the same prefab) dealing damage to each other on collisions. Each Unit has both a Collider2D and a trigger on the front, that deals damage to other units that enter it. I drew a small image (with Paint, sorry) to better illustrate what I mean and want. The problem I am having is that when a collision occurs (one unit enters the trigger of the other), both units damage each other, meaning Unit 2 also deals damage to Unit 1. I have seen that you can create a separate gameObject as a child of the unit and attach the trigger to this gameObject. However, the number of units will be very high so if possible I don't want to double the number of gameObjects used by units. Also, the amount of damage dealt is calculated from many other parameters from many other scripts on the units and doubling all those references doesn't look like an elegant solution. Any Ideas? Thanks
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.