_id
int64
0
49
text
stringlengths
71
4.19k
0
Why is the Position Handle placed at certain distance away from vector3 unit in Unity? I have a vector3 value that I am setting in inspector and I am drawing a ray using OnDrawGizoms to draw that vector line. However, the position handle I made using Handles API to set the vector3 value is placed certain distance away from the vector unit. It's not placed exactly at the end point of the vector line that is drawn and I am not sure why. My goal is to just make a handle to position a vector3 value. EDIT For some reason, the handle is positioned correctly for y position alone but not for x and z positions. Here is my code In this script, it is the localTargetPosition vector3 value that I want to make my handle for. public class MovePlatform MonoBehaviour public Vector3 localTargetPosition new Vector3(5, 0, 0) public Vector3 m initialPosition get return initialPosition set initialPosition value private Vector3 initialPosition, targetPosition, targetPosDebug public float speed 3 public bool loop void Start() initialPosition transform.position SetTargetPosition(localTargetPosition) void Update() transform.position Vector3.MoveTowards(transform.position, targetPosition, speed Time.deltaTime) if (transform.position targetPosition) if (loop) SwitchDirection() public void SwitchDirection() if (transform.position initialPosition) SetTargetPosition(localTargetPosition) else targetPosition initialPosition private void SetTargetPosition(Vector3 localPosition) targetPosition initialPosition transform.TransformDirection(localPosition) targetPosDebug targetPosition void OnDrawGizmos() if (Application.isPlaying) Debug.DrawLine(initialPosition, targetPosDebug, Color.red) else Debug.DrawRay(transform.position, transform.TransformDirection(localTargetPosition), Color.red) This is the script used for making handle CustomEditor(typeof(MovePlatform)), CanEditMultipleObjects public class MovePlatformEditor Editor protected virtual void OnSceneGUI() MovePlatform movePlatform (MovePlatform)target Vector3 initialPosition movePlatform.transform.TransformPoint(movePlatform.m initialPosition) Vector3 targetPosition movePlatform.transform.TransformPoint(movePlatform.localTargetPosition) EditorGUI.BeginChangeCheck() Handles.Label(targetPosition, "Target", "button") targetPosition Handles.PositionHandle(targetPosition, movePlatform.transform.rotation) if (EditorGUI.EndChangeCheck()) Undo.RecordObject(movePlatform, "Move Handles") movePlatform.localTargetPosition movePlatform.transform.InverseTransformPoint(targetPosition) Handles.color Color.yellow Handles.DrawLine(initialPosition, targetPosition)
0
I already have a GameManager script, but need to have a 2nd one I'm making a Unity game, and I want to use the Unity Distribution Portal. My problem is that you have to make a script named GameManager for this, but I already have another script called GameManager, so every time I try to rename the first GameManager script, the game stops working. I don't want to rewrite every script I've used GameManager variables in. So the way I've been trying to rename this is by right clicking on the GameManager.cs file in the Unity project window and renaming it there, then typing a 2 in the name inside Visual Studio. If I call the script for UDP for example something like GameManager2, UDP doesn't seem to understand that this is the script it needs for Sandbox Testing. Can anyone help me with this? Here is the UDP script I want to add (which is currently called GameManager2, but needs to be called GameManager) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UDP public class InitListener MonoBehaviour, IInitListener public IInitListener listener public void Start() StoreService.Initialize(listener) public void OnInitialized(UserInfo userInfo) Debug.Log( quot Initialization succeeded quot ) public void OnInitializeFailed(string message) Debug.Log( quot Initialization failed quot message)
0
Unity3D Tag as a public variable in editor How do you incorporate Tag strings into a scripts editor found in the inspector? What it is I'm babbling about When you create a public GameObject fooObject in a script, it shows up as a box that can have Game Objects dragged onto in its editor. It also has a small clickable dot that shows every Game Object that could be selected. Now, say I have a public string fooString that would specifically be used for referencing the Tag strings of Game Objects (such as if (fooObject.tag fooTag) or another use). Is there a way to define that string so that in the script's editor it strictly allows tag names to be used with it? I'm assuming with a similar clickable dot or a drop down menu of every selectable tag. Although I could just manually type my string, a solution like the one above would have big object orientated advantages. For example, if I was to change the name of this tag, it would change the string variable accordingly, as if the variable was a reference to such tag. Note to the moderators I looked for an answer to this question for nearly 2 hours now to no avail. I understand that I may be missing some specific wrong word choice, in which case this question easily could have already been answered here. If this is closed as a duplicate, then, a quick comment explaining my mistake would be greatly appreciated.
0
How to implement the seek steering behavior in Unity3d? Following this tutorial Understanding Steering Behaviors Seek, I tried to add seek and steering behavior to my Unity prototype but it's not working this is my script. The cube does not steer it just follows the target. public GameObject target float maxForce 15 float maxSpeed 30 float maxVelocity 200 float mass 15 Vector3 velocity void Start() velocity Vector3.zero void Update() transform.LookAt(target.transform) var desiredVelocity target.transform.position transform.position desiredVelocity desiredVelocity.normalized maxVelocity Time.deltaTime var steering desiredVelocity velocity steering Vector3.ClampMagnitude(steering, maxForce) steering steering mass velocity Vector3.ClampMagnitude(velocity steering, maxSpeed) transform.position velocity Time.deltaTime What could be the problem??
0
Unity solution not compatible with Visual Studio Since updating to the most recent version of Unity 5.4.0f3 Personal Edition, whenever I double click on a script, it launches Visual Studio, but I get an error saying that this version of Visual Studio (Community Studio 2015) is unable to open my project. Please see the screenshots attached for the actual error message. Monodevelop also launches with it's own error message. I am still able to open the individual script manually using the menu in VS but it's a little frustrating that it doesn't open automatically, and more annoying is that the intellisense code completion features no longer work. Anyone know how to fix this? I have Visual Studio Tools for Unity installed and have tried running the installer to repair this tool also.
0
Multiple updates for Unity animation per one method call I'm trying to do some simulation where I move objects procedurally in a loop within one method call. So instead of using Update(), method I do for example void Simulate(float deltaTime) real logic look a lot different, this is just an example for(int i 0 i lt 1000 i) transform.position direction speed deltaTime ..... The reason I'm doing this is because I want consistent 'framerate' by passing that deltaTime parameter Which is for example 0.01f And each step of that loop I'm taking snapshots on multiple cameras with calling Render() method on them before taking a picture. The movement works fine and I see it on snapshots, but some objects has an animation which should also be updated procedurally. I've tried to do animator.speed 0 and then in the same loop, to test it for (int i 1 i lt 1000 i) ... animator.Play("WalkFWD", 0, i 1000f) for example But animation does not change over that loop. It only works with that Play method when I either make this Simulation() method a coroutine and pass one frame (yield return null), or if I use in Update(). So, my question is it possible to procedurally update redraw animation after normalized time of that animation is set. (without waiting for another frame)
0
Unity3D GameObject as a static function Newbie Unity3D C developer here. I've tried learning Unity3D during my May June college vacation and came across a problem Code 1 CameraObj returnVoid void Start () returnVoid GameObject.Find ("Main Camera").GetComponent lt CameraObj gt () returnVoid.ComponentType () Code 2 GameObject returnDirectLight void Start () returnDirectLight GameObject.Find ("Directional Light") Debug.Log (returnDirectLight.GetComponent lt DRLight gt ().directionString) CameraObj is my custom component. As far as I know, GetComponent is actually a public method. I understand the logic behind Code 2. What I fail to understand is Code 1. How does GetComponent become a static function here? Does it become abstract in my CameraObj class?
0
Initializing Consumable product to an amount on first use I am using Unity's In App Purchase plugin to implement an in game store. In my game every player has fuel. I'd like to use the plugin in order to keep track of the amount of fuel the player has so that just erasing the cache on the phone or something wouldn't effect the regeneration time of fuel (like it would if I use PlayerPrefs). Right now i have it setup so the fuel amount is saved in PlayerPrefs and when fuel is used, a timestamp is saved in PlayerPrefs. Then it checks every once in a while if enough time has passed since they used it in order to regenerate it. Instead of doingoing it this way I want to initialize the fuel amount in Unity's in app purchase plugin so that Googles servers will have the amount and then I can use the same idea for regeneration that I already have but nowe the amount will be more safe. Is there a way to initialize the amount of a consumable product a player has on their first launch of a game?
0
Adding some recoil to the Camera so that the crosshair is pushing to the sky (FPS game) I just want to add some recoil to the camera, but I can't find a working script. It's an fps, so I take my mouse axis to rotate the camera. And now I want a pushback to the top, so that the camera looks into the sky after shooting a whole clip. It should be pretty easy, just add some amount to the axis, but it isn't working for me. I've got something like this from another post, but it just does nothing for me... I got a feeling that my axis is locked in some way, I'm using the "MouseLook" from the standart assets. transform.Rotate( recoil Time.deltaTime, 0, 0 ) Update This Script is working partially, but I think I reactivate the MouseLook too fast after the Rotate, so that the Mouse just jumps back to the starting position. mouseLook.enabled false transform.Rotate ( 5, 0, 0) mouseLook.enabled true
0
Unity orthographic camera and shadow When using an Orthographic Camera, the shadows appear to be of poor quality. How can I display smooth shadows?
0
How do you freeze your cursor in Unity? In a typical MMORPG, when I hold down the right click button and drag, the cursor disappears and stays in the same position. How does one do that?
0
Unity change sprites to something that uses less memory I have a game that uses only silhuette textures, but they take up waay too much memory (360 MB overall and this is a mobile game) so I plan to avoid using sprites with alpha punchouts (1 bit alphas). From what I gathered, I could use an asset from Unity store like SVG importer, but I have no financial means to do so. So I plan to make low poly 3D (in fact 2D) planes that somewhat cover my textures. Now, I have a lot of sprites already. I saw that Unity can create a 2D mesh collider around my sprites. Can I use that to create my meshes and then apply a single colour unlit material to them? How would it roughly effect memory usage as opposed to my generally 500x600 sprites? If I'm going in the wrong direction, is there a way to create Shapes, just like in Photoshop or GIMP?
0
How to apply force towards direction using mouse drag and or touch input direction and input speed? I've to object. I can move object 1 (my Player) using mouse (or Touch for smartphone version). I want apply a force to object 2 when object 1 hit it. Force direction must be mouse vector direction or touch vector direction. For Mouse input i'm using event OnMouseDown and OnMouseDrag to determine mouse original position. But I think this is not the best approach. Behaviour is not what i am expecting void OnMouseDown() mouseDragStartPosition Input.mousePosition translate the cubes position from the world to Screen Point screenSpace Camera.main.WorldToScreenPoint(transform.position) calculate any difference between the cubes world position and the mouses Screen position converted to a world point offset transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z)) void OnMouseDrag() keep track of the mouse position var curScreenSpace new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z) convert the screen mouse position to world point and adjust with offset var curPosition Camera.main.ScreenToWorldPoint(curScreenSpace) offset transform.position new Vector3(curPosition.x, ClampY, curPosition.z) void OnCollisionEnter(Collision collision) Debug.Log("OnCollisionEnter") if (collision.collider.tag "Disc") ApplyForce() void ApplyForce() Vector3 direction mouseDragStartPosition Input.mousePosition direction new Vector3(direction.x, ClampY, direction.z) ClampY used to not allow Y DiscRb.AddForce(direction 1, ForceMode.Impulse)
0
How do I find the face of an object? I'm working on a build mode but the thing of it is the player is able to deform meshes. Part of my build system includes having "snap" points thus I need to be able to find the face and recenter the snap point on deformed meshes. So, how do I find the face of an object and the center of said face? Also how would I find the center? To clarify The end goal is to keep the snap point positioned properly with the face that has been deformed manipulated.
0
Camera position and angle different when running inside Unity and when running on Android On Windows, running Unity 4.6.1p5, my simple game with only a cube, camera and light looks like this but under Android (Gingerbread on a 5 inch Galaxy Player) the cube appears lower down, slightly different angle and smaller (relative to the screen size). Sorry couldn't get a screenshot with my screenshot app... Any ideas why please?
0
Unity control time interval when using getAxis() in bolt visual scripting i use bolt visual scripting. I add input.getAxis in Bolt and set the axis name to Vertical so to get response when i press w and s . When running the game and press the w key, the output data (acceleration) will increase from 0 to 1. The problem is the increasing time is too fast or too short. How to make it slower longer? Let say i want it to take 3 seconds to reach 1. Edit This is what i want to achieve (at time 6 10 to 6 25) https youtu.be m8rGyoStfgQ?t 370 And the code is at the same video at time 6 00 . That codes works perfectly fine. And this is all i want to achieve but i want to do it in Bolt (visual scripting) rather than manual scripting. So that line of code at 6 00 on that video Velocity time.Deltatime acceleration That code is controlling how fast or slow the acceleration can go from 0 to 1 when pressing w key. But in Bolt, i use getAxis and by using default sensitivity setting, if i press w it will take less than half a second for the acceleration to go from 0 to 1. I want to make it slower so i can go from 0 to 1 in 3 seconds or 5 seconds. In fact , this the same as setting up the sensitivity in input manager to low value, but i want to keep this setting as default and want to control it inside bolt. Pls check my video here getAxis
0
Tetris block kinematic rigidbodies pass through one another with Transform.Translate I am trying to build a Tetris 3D game in Unity but I am stuck at getting the different blocks to interact (to detect each other, to sit one on top of the other rather than going through each other). I have set the ground with a box collider and the spwaned blocks come in with rigidbodies and trigger colliders. This works for them to nicely settle on the ground but when I try to sit a block on top of another block they both have kinematic rigidbodies and the collision detection doesn't work and they end up overlapping. The problem is if I remove the rigidbody of the already settled block then it will go through the ground. Any idea how to get 2 spawned objects to detect each other? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UIElements public class moveBlock MonoBehaviour public static float speed 2 public GameObject blocks public static List lt GameObject gt blocksSpawned new List lt GameObject gt () public static List lt Rigidbody gt blocksRBSpawned new List lt Rigidbody gt () public static bool triggerPlatform true Rigidbody rb void Update() Vector3 input new Vector3(Input.GetAxisRaw( quot Horizontal quot ), 0, Input.GetAxisRaw( quot Vertical quot )) Vector3 direction input.normalized Vector3 velocity direction speed Vector3 moveAmount velocity Time.deltaTime if (triggerPlatform) blocksSpawned.Add((GameObject)Instantiate(blocks Random.Range(0, 7) , new Vector3(0, 6, 0), Quaternion.Euler(Vector3.right))) rb blocksSpawned blocksSpawned.Count 1 .GetComponent lt Rigidbody gt () blocksRBSpawned.Add(rb) triggerPlatform false if (!triggerPlatform) Destroy(blocksRBSpawned blocksRBSpawned.Count 1 ) if (blocksSpawned blocksSpawned.Count 1 ! null) blocksSpawned blocksSpawned.Count 1 .transform.Translate(Vector3.down Time.deltaTime speed, Space.World) blocksSpawned blocksSpawned.Count 1 .transform.Translate(moveAmount) using System.Collections using System.Collections.Generic using UnityEngine public class trigger MonoBehaviour private void OnTriggerEnter(Collider other) moveBlock.triggerPlatform true
0
LineRenderer not working using Vuforia in Unity So I'm trying to render a line that shows up when camera sees an image target and moves around with it. Very typical AR application. But my line renderer doesn't seem to show at all. Here's the code using UnityEngine using System.Collections public class myLine MonoBehaviour Creates a line renderer that follows a Sin() function and animates it. public Color c1 Color.yellow public Color c2 Color.red public int lengthOfLineRenderer 20 void Start() LineRenderer lineRenderer gameObject.AddComponent lt LineRenderer gt () lineRenderer.material new Material(Shader.Find("Particles Additive")) lineRenderer.widthMultiplier 0.2f lineRenderer.positionCount lengthOfLineRenderer A simple 2 color gradient with a fixed alpha of 1.0f. float alpha 1.0f Gradient gradient new Gradient() gradient.SetKeys( new GradientColorKey new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) , new GradientAlphaKey new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) ) lineRenderer.colorGradient gradient void Update() LineRenderer lineRenderer GetComponent lt LineRenderer gt () var t Time.time for (int i 0 i lt lengthOfLineRenderer i ) lineRenderer.SetPosition(i, new Vector3(i 0.5f, Mathf.Sin(i t), 0.0f)) and here's my set up I also tried attaching the script directly to the ImageTarget and nothing happened.
0
System.Runtime.Serialization.SerializationException while trying to deserialize List I'm trying to serialize deserialize a class that holds inventory items. The code is attached below. First I call AddOne() void a few times, then I call SaveFile(), then I call LoadFile(). In LoadFile() the following error occurs ex "System.Runtime.Serialization.SerializationException End of Stream encountered before parsing was completed. r n at System.Runtime.Serialization.Formatters.Binary. BinaryParser.Run () 0x00288 in lt 1f0c1ef1ad524c38bbc5536809c46b48 0 r n at System.Runt... Does anybody see my mistake? Thank you for the help! using System using System.Collections using System.Collections.Generic using System.IO using System.Runtime.Serialization.Formatters.Binary using UnityEngine public enum Type undefined 0, Pistol 1, Magnum 2, Grenade 3, BlendGrenade 4, FireGrenade 5, PistolAmmo 6, MagnumAmmo 7, Rifle, RifleAmmo, System.Serializable public class Inventory MonoBehaviour public class InventoryItem public int Amount 0 public int Row 0 public int Col 0 public int Rotation 0 public Type ItemType Type.undefined public List lt InventoryItem gt Items public void Start() Items new List lt InventoryItem gt () public void AddOne() InventoryItem n new InventoryItem() this.Items.Add(n) public void SaveFile() string destination Application.persistentDataPath " save3.dat" if (File.Exists(destination)) File.Delete(destination) using (Stream stream File.Open(destination, FileMode.Create)) BinaryFormatter bin new BinaryFormatter() bin.Serialize(stream, this.Items) public void LoadFile() string destination Application.persistentDataPath " save3.dat" using (Stream stream File.Open(destination, FileMode.Open)) BinaryFormatter bin new BinaryFormatter() try this.Items (List lt InventoryItem gt )bin.Deserialize(stream) catch (Exception ex) Debug.Log(ex.ToString())
0
Rigidbody2D moves on x axis without adding force I'm currently trying to learn some Physics2D in Unity. Now, I've created a Ball (sprite) and added a RigidBody2D and a CircleCollider2D on it. The RigidBody2D has the following settings Bodytype Dynamic Simulated true Use Auto Mass false Mass 1 Linear Drag 0 Angular Drag 0 Gravity Scale 25 Collision Detection Continous Sleeping Mode Start Awake Interpolate None Now, when I start the scene, the ball drops as expected. However, it's also moving on the x axis by 83 pixels, which I don't want. The movement on the x axis stops once it reached that 83 pixels point. If I freeze the x position in the Rigidbody2D Settings I get the intended behaviour (ball just dropping on y axis), but I feel like that would be a hack instead of fixing the actual problem. What could cause this? I expected the ball to just drop, if I have no drag, a certain mass and gravity enabled.
0
How can I send different contoller input to the different player avatars? My apologies in advance for the vague question, since I don't understand the problem well enough to ask in finer detail. I want to create a multi player Unity application using the Oculus SDK. Let's say there are two players in the scene, A and B. The problem is this When player A presses a button using his index finger, the hand avatar for player B also displays a moving index finger. In short, hand movements for one player are also observed for the other. Controller inputs are also read without any ability to distinguish whether they originate from player A or B. What are the possible approaches for eliminating this problem, if it is mandatory that I continue using Oculus SDK?
0
Adding an extra Pass to the Unity Standard Shader I'm experimenting with adding some procedural textures to the unity standard shader. I'd like to add an extra pass (with vert and frag functions), but am unsure about where in the sequence this should go, and how to properly integrate it with the other passes (I want to keep all the standard shader lighting features etc.). To keep things simple, I'd like to start with adding an extra pass which simply paints the mesh one color. Where should this go (in Standard.shader)? Note I've tried adding a pass between passes 1 ("FORWARD"), and 2 ("FORWARD DELTA"). This works, and casts shadows, but does not recieve shadows. Thank you!
0
Separating part of mesh facing upwards I really hope you can help me fix this code List lt Vector3 gt verticesToExport new List lt Vector3 gt () vertices of the triangles facing upwards. List lt int gt trianglesToExport new List lt int gt () new triangle facing upwards. meshToCut is the original mesh, then I just try to replace it with the new data. int triangles meshToCut.triangles Vector3 vertices meshToCut.vertices for (int i 0 i lt triangles.Length i 3) Vector3 corner vertices triangles i Vector3 a vertices triangles i 1 corner Vector3 b vertices triangles i 2 corner float projection Vector3.Dot(Vector3.Cross(b, a), Vector3.down) if (projection gt 0f) verticesToExport.Add(vertices triangles i ) verticesToExport.Add(vertices triangles i 1 ) verticesToExport.Add(vertices triangles i 2 ) trianglesToExport.Add(triangles i ) trianglesToExport.Add(triangles i 1 ) trianglesToExport.Add(triangles i 2 ) meshToCut.SetVertices(verticesToExport) meshToCut.SetTriangles(trianglesToExport, 0) probably I'm doing wrong here! It works great by retrieving the vertices facing up, and I guess the triangles too but when I put it into a mesh filter I believe the triangles are not in order... 1.The model I'm trying to separate the triangles facing upwards. 2. This is what happens if I just take the vertices and triangulate them again. It proves that vertices are alright! 3. The result I get from the code above
0
How can i keep the spawned cubes to be inside the given area? In this case the 4 walls and objects I spawn inside the 'wall area' are all cubes. This situation could change to where the walls will be spheres and the other objects can be cylinders or cubes (its not limited to cubes only). What I'm trying to do is to spawn the objects in random positions but within the 'wall area'. The problem is when some cubes (objects) are spawning too close to the walls, part of the cubes will inside the area and some will be outside. In the screenshot example on the right, a cube is going out of the wall area. In this case the walls area is sized according to the terrain (500x500) but it could be any size like 45x23 or 100x100. In the script below I'm getting the 4 walls objects in array. walls GameObject.FindGameObjectsWithTag("Wall") Now I wonder how can I use a ray cast to detect if each cube is spawning too close to one of the walls and if so then re position the cube randomly, over and over again until it's inside the walls area. I'm not sure if using ray cast is the best way but that's what I had in mind. using System using System.Collections using System.Collections.Generic using System.IO using UnityEngine public class SpawnObjects MonoBehaviour public int numberOfObjects public GameObject objectToPlace public Vector3 newObjectsSize public float spawnSpeed 0.1f private int wallsLengthX private int wallsLengthZ private int wallsPosX private int wallsPosZ private int currentObjects private GameObject walls private List lt GameObject gt objects new List lt GameObject gt () private GameObject spawnedObjects void Start() var wi GetComponent lt Walls gt () wallsLengthX (int)wi.lengthX wallsLengthZ (int)wi.lengthZ wallsPosX (int)wi.wallsStartPosition.x wallsPosZ (int)wi.wallsStartPosition.z walls GameObject.FindGameObjectsWithTag("Wall") spawnedObjects GameObject.Find("Spawned Objects") StartCoroutine(Spawn()) IEnumerator Spawn() for (int i 0 i lt numberOfObjects i ) GameObject newObject (GameObject)Instantiate(objectToPlace) newObject.transform.localScale GenerateRandomScale(newObject) newObject.transform.localPosition new Vector3(GenerateRandomPositions(newObject).x , GenerateRandomPositions(newObject).y newObject.transform.localScale.y 2.0f, GenerateRandomPositions(newObject).z) newObject.name "Spawned Object" newObject.tag "Spawned Object" newObject.transform.parent spawnedObjects.transform objects.Add(newObject) yield return new WaitForSeconds(spawnSpeed) currentObjects 1 var wp GetComponent lt WayPoints gt () wp.FindMyObjects() private Vector3 GenerateRandomScale(GameObject newObject) Vector3 newScale new Vector3(UnityEngine.Random.Range(5, 100), UnityEngine.Random.Range(5, 100), UnityEngine.Random.Range(5, 10)) return newScale private Vector3 GenerateRandomPositions(GameObject newObject) float paddingX Mathf.Clamp(newObject.transform.localScale.x, 0, wallsLengthX) 2f float paddingZ Mathf.Clamp(newObject.transform.localScale.z, 0, wallsLengthZ) 2f float originX wallsPosX paddingX wallsLengthX 2f float originZ wallsPosZ paddingZ wallsLengthZ 2f float posx UnityEngine.Random.Range(originX, originX wallsLengthX paddingX) float posz UnityEngine.Random.Range(originZ, originZ wallsLengthZ paddingZ) float posy Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz)) return new Vector3(posx, posy, posz)
0
Materials aren't loading correctly from SketchUp into Unity I imported a SketchUp COLLADA (.dae) file from 2017 SketchUp Make, and imported it into Unity. I then clicked quot Use External Materials quot and the colors began to load. But I noticed quickly that one of the wings of my imported B 29 was Dark Gray, while the other way a proper color. Random parts, such as the front engine housing piece, were also dark gray. Parts of my advanced dials were also dark gray, and I immediately decided that there is now ay that I am going to manually go in and fix every single dark gray material, but at the moment, I found no alternative. I began with the wing. I went to assign the material that I used for the other wing, which was white, to the dark gray wing, but I found out that the other wing already had that material in use. And when I went to assign a different white color, absolutely nothing changed, aside from the fact that the wing now claimed that it had that color in use. Is there a fix for this problem? I could try importing as a .SKP file, if the reason for the issue is something to do with the COLLADA (.dae) file. What I had was 2 wings. they were both components in SketchUp, so whatever I did to one applied to the other, Then I made them unique before importing to Unity. The Wing that won't work right is the one wing that had the USAF Insignia on it. But I doubt this is the problem, because all engines on that wing were also not colored correctly, whereas the other wing was fine. Those engines were also components, but were also made unique before the import. Each wing has 9 groups inside of it. The other wing is identical in this sense. I imported the file from file explorer by dragging the file from file explorer and dropping it into unity. This is what the plane looks like in Unity My apologies for the crude handwriting, it is difficult to draw with a touchpad. In the image, I numbered the incorrectly colored parts visible in the image (Right Left references are perspective to image) 1. Left Wing. Color Dark gray. Color intended White. 2. Propeller blade hub. This is the part that all propeller blades are connected to. Both hubs on the two propellers on the Left Wing are colored incorrectly. Color white. Color Intended Grey. 3. Pistons. All piston components, such as the pistons, securing poles, and piston heads are not colored correctly same on the other engine on the Left Wing. Color White. Color Intended Grey pistons, darkish grey piston heads, and copper orange securing poles. 4. Cowl Flaps. In the image, this appears to be a stripe in the engine. Same with the other cowl flaps on the other engine on the Left Wing. Color Dark gray. Color Intended White. 5. Propeller blades. All 4 propeller blades on both engines on the left wing are not colored correctly. Color White. Color Intended Black, with yellow tips. 6. Right Wing Pistons. Most piston components, such as the pistons heads and securing poles are not colored correctly. Same with the other engine on the Right Wing. Color White Piston Heads, Grey Pistons, Almost Black Gray in the lines on the pistons, white securing poles. Color Intended Grey pistons, darkish grey piston heads, and copper orange securing poles. 7. Front Engine Casing. The same error is in the other engine's front engine casing on the Right Wing. Color Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). Color Intended White. 8. Rear Engine Casing. The same error is in the other engine's rear engine casing on the Right Wing. Color Dark Gray, with an apparent shine coming from beneath the part, which shouldn't be happening (the directional light is above the engine part). Color Intended White.
0
Why is there a discrepancy between these two transform.up vectors? I was trying to implement a feature which required transform.up, the result didn't match the green axis gizmo displayed in the editor so I assumed it was being put off by the rotation of the object despite expecting the gizmo to adapt to that. I then modified the prefab such that everything was now child to an empty object and the secondary objects were child to that instead of the rotating model, and wrote a script that simply copies the transform so that it tracks. This still didn't show the values expected from what the gizmo in the editor showed. I then did a Debug.LogError in the track script and this time the result was as expected. Why is transform.up showing the value expected from the local y axis gizmo but when passing a reference to the original script and checking tracked.transform.up gives off results? To reproduce in a simpler environment I set up a simple test scene. Simple default cube with the hierarchy structure shown in the screenshot. The transform values are as follows parent zeroed x 0, y 90, z 0 for cube x 0, y 90, z 90 for TrackPoint Scripts are as follows test.cs attached to trackpoint private void Update() Debug.LogError(transform.up) Track.cs attached to tracker public Transform transformToTrack private void Update() transform.position transformToTrack.position transform.rotation transformToTrack.rotation Debug.LogError(transform.up) byref.cs attached to cube public GameObject refObj private void Update() Debug.LogError(refObj.transform.up) When run, if you clear the console then click pause you'll see that one of them differs from the others. I don't understand why. My project and this sample scene differ in which it is that is giving unexpected results but the results are inconsistent with what I would expect. But wouldn't they all give the same result?
0
Apparently, Unity decided to import a bunch of things I already had I am getting lots of errors ever since Unity decided to reimport plugins and Unity assemblies that were already present in my project. I am not sure what I can now do, what folders to delete to fix this issue, etc. Is there any simple solution to fixing all of these problems? I cannot even click play in the Unity Editor now.
0
Object Touch Drag Problem Object moving to next finger My Code is as follows foreach (Touch touch in Input.touches) switch (touch.phase) case TouchPhase.Began touchPosition Camera.main.ScreenToWorldPoint (Input.mousePosition) offset touchPosition GOCenter break case TouchPhase.Moved touchPosition Camera.main.ScreenToWorldPoint (Input.mousePosition) newGOCenter touchPosition offset newGOCenter.y 0.0f newGOCenter.z 0.0f gameObject.transform.position newGOCenter gameObject.transform.position new Vector3 ( Mathf.Clamp (gameObject.transform.position.x, boundary.xMinMax, boundary.xMinMax), 0.0f, 0.0f ) break default break What i am doing is i am moving the player left and right along x axis by dragging in the screen. When i drag move the player with one finger then it works as expected. But when i keep another finger in the screen and take out the first finger from the screen the player comes of the second finger. I want the player to be moved from the place where it was left instead of coming to the second finger. I have done disabled multiTouch but it does not worked. user fingerIndex
0
How can I properly display the distance with the unit in a string on the UI? I wrote a script for distance of car and I don t know how to make distance like this Distance 156Km. I wrote this code distanceText.text ((int)distance).ToString() "Km" It works only from 1 to 9 when it goes to 10 Km, it disappears but if I write it like this distanceText.text ((int)distance).ToString() " Km" It show like this from 1 to 9 "5 Km" and from 10 to 99 "99Km" but when it goes to 100 Km and above, it disappears. What code should I write for this to show always Km after the distance. And I have one more question. I have a gameover canvas and I'd like in gameover canvas to show the final distance I make with PlayerPrefs but it doesn't work. Here it shows how it does not work
0
How to integrate images into text lines in Unity? Here are two screenshots from Stellaris, where images are seamlessly integrated into the text. How can I achieve this in Unity?
0
Raycast not hitting a collider I have the following simple raycast from a capsule on a cube bool hit Physics.Raycast (transform.position, Vector3.down, jumpSettings.groundJumpDistanceCheck, jumpSettings.layerMask) print(hit) When my layerMask is 8 (terrain), I have set my layer on my cube and my groundJumpDistanceCheck is 2. Then my hit is false. When my groundJumpDistanceCheck is set to Infinity. Then my hit is still false. However when I remove the distance parameter bool hit Physics.Raycast (transform.position, Vector3.down, jumpSettings.groundJumpDistanceCheck, jumpSettings.layerMask) print(hit) Then hit returns true. This is odd for me, as far as I know when you exclude the distance parameter it's supposed to be Infinity by default. But when I explicitly give Infinity as the distance, it returns false. I have also used the following code in an attempt to debug my issue, using the desired distance 2f Debug.DrawRay(transform.position, Vector3.down jumpSettings.groundJumpDistanceCheck, Color.red, 60f) As you can see, the ray does intercept the cube. I need the reycast to return true with a distance of 2f.
0
Unity Shader Graph, set blackboard properties from code I have a Shader Graph shader with a blackboard property that I want to change from within my code. The property is called Highlight here are the things I have tried Color myColor new Color(1f,0,0,1f) material.Color myColor throws error (as I expected) material.SetVector("Highlight", myColor) Name in blackboard window material.SetVector("HighlightColour", myColor) Name in material property material.SetVector("Color 8C3A526", myColor) Name in the shader inspector None of these work. Here's the shader set up
0
SetIKHintPosition and SetIKHintPositionWeight seems to have no impact I have recently been exploring Unity's inverse kinematics, to further polish the interaction between our rigged avatars and props. I have made a sample project, using PuppetMaster's basic humanoid for the model, rig, and idle animation, but without Final IK meaning this is Unity's inverse kinematics. Inside our OnAnimatorIK method, we set the right elbow's SetIKHintPosition and SetIKHintPositionWeight like we did with the hand IK animator.SetIKHintPosition(avatarIKHint, hintPosition) animator.SetIKHintPositionWeight(avatarIKHint, hintBlendValue) animator.SetIKPosition(sourceIKGoal, targetPosition) animator.SetIKPositionWeight(sourceIKGoal, blendValue) You can see the left and right hand correctly move to where we set it. However, it seems like the right elbow is ignoring the hint position entirely. You can see the white debug line connecting the elbow to the hint position in the picture above. It seems like the elbow ONLY bends if it absolutely must for the hand to reach the target position, regardless of where the hint is set, and the weight value given. I have fiddled with this on and off for days and still haven't found a solution. Others have asked the same question here and on other sites, but no one has posted an answer.
0
Is it ok to commit to git while my Unity project is still open? I tend to have big commits and it is related to me being tool lazy to close Rider and Unity, commit changes and then start both programms back up to make changes and repeat. I just assumed that this is the correct way of doing it, but is this even the case? Thanks in advance!
0
Design pattern for world objects caching I'm developing in Unity a voxel generated terrain and I'm trying to find an extensible design pattern for voxels and more in general, world objects caching. E.g. storing in a 'ChunkCache' class only the nearest Chunks and updating it after a set amount of time As of now, I'm using a static World class with the following members in pseudocode static class World Player reference Enemies reference WorldCache reference etc. The WorldCache instance contains a list of objects all deriving from the same base class 'Cache'. The implementation so far calls worldCache.update() method with an enum indexing this list of 'Cache' objects WorldCache class List lt Cache gt differentTypesOfCache void update(Enum whichCache) differentTypesOfCache whichCache .update() The problem I'm facing with this design pattern is different types of derived Cache classes need different types of information (e.g. a ChunkCache class will judge wether a chunk needs to be removed from the cache depending on the player's distance from the center of the chunk, whereas other types of derived Caches may need differing information) and as of now the only way to gather this information is to directly query the static World class members. Also if a certain Cache object requires information from another Cache object, it starts to look spaghetti. Is there a completely different pattern better suited for this scenario, or a way to modify the existing one for the better?
0
Elegantly exposing properties in Unity inspector There are various game objects in my scene that share some common characteristics, so I created an interface, like so public interface IHasLimitedRangeOfMotionAlongZAxis float MinimumZ get float MaximumZ get For certain types that implement this interface, I would like MinimumZ and MaximumZ to be publicly assignable in the Unity inspector. Therefore, I would like to be able to expose these properties in Unity. I am aware that one approach is to write C scripts in the Editor folder to implement an ExposePropertyAttribute (see here). However, this approach is unsatisfactory for two reasons My solution is not co located with my Assets folder. I write my code in a separate solution, and then use pdb2mdb.exe to import my scripts into my Unity scenes. (The reason for doing this is to avail myself of C language features introduced beyond C 4.0, which nonetheless target .NET Framework 3.5.) I shall have to create a custom editor for every single type that implements the interface with publicly assignable properties. This leads to a lot of boilerplate code. Is there a more elegant approach than adding private backing fields with the SerializeField attribute for all of my public properties?
0
Is it a good idea and a logic to create adventure game with one scene? I mean instead messing with loading scenes and passing variables between the scenes to make one scene and using in the hierarchy empty game objects for each part in the game for example empty game object name main menu and all the childs of it will be main menu objects. Or instead making a new scene to make one empty gameobject and all it's childs will be like scenes.
0
How do I set up a dedicated server for my multiplayer Unity game? I've made a multiplayer game with Unity and Mirror networking, and it all works perfectly when just running it on my own computer. However, I am trying to host on a dedicated server so that I can put the project on my portfolio and not have to worry about whether players can log in and test play the game or not. I tried a AWS Free server and I see that the Tanks example from Mirror is working just fine (although laggy), but my own project doesn't. I think this has something to do with the RAM limit of the free server but I'm not sure. I can see the task manager going up to 95 memory usage. When I remove some particle effects and geometry and enemies, it works. I'm not sure if this is my code that is so cloggy or the server or both. In any case I would need a solution for this but I don't know what my options are. Would be great if anyone can point me in the right direction. Thanks!
0
Companion AI with NavMeshAgent causing jittery movement on the X Axis I'm trying to do a companion AI that follows around my player but with a certain distance. I first tried to self program the movement behavior. but realized quickly that a NavMeshAgent offers more simple solutions to what I'm trying to achieve. Now the problem is that my AI doesn't follow around smoothly. It's surely not because of the camera, since my player and my enemy AIs do not have these jittery movement. My script is as simple as it can get private Transform target private NavMeshAgent agent public Animator partnerAnim public GameObject player private void Start() set target to player transform target GameManager.GM.playerMachine.transform agent GetComponent lt NavMeshAgent gt () private void Update() Determining wether to play the walk animation or not partnerAnim.SetFloat( quot normalizedSpeed quot , Mathf.Clamp01(agent.velocity.magnitude)) agent.SetDestination(target.position) My stopping distance is at 2 and my speed is at 3.5. No matter how I change these values, the jittery movement won't change. I also have a rigidbody attached to my NavMeshAgent, and I made sure to turn on isKinematic, and I also removed it to check if that solves the problem, but it didn't. The weird thing is that it only seems to be a problem when moving along the X Axis. When I move on the Z Axis only, my partner is following my player smoothly (I'm guessing this is because I increase the speed of my player on the Z Axis, but I don't really see the connection with my problem here. If it would be a speed problem, then lowering the speed on my AI would've fixed this, but it didn't.) Here are the full NavMeshAgent settings
0
Unity importing Blender models with different orientations All the models apart from 'Jungle Tree' are facing right which is not a problem, because they still seem to work with my game. But how can I change the 'Jungle Tree' to face right like the other models instead of left? I haven't made the Jungle Tree drastically different to the other models so I don't see why it is doing this
0
Unity, shader, vertexID I'm writing a shader and I just wanna ask if it's possible to get the ID of the vertex that is currently being manipulated. I read something about gl vertexID, but I couldn't find out if that is something I can use.
0
How to create an animation clip that changes whatever color a RawImage has to a certain destination color? I created an animation clip that turns a certain RawImage's color from white to red. I'd like to know how I could change that clip to turn any color that the RawImage might have into red with other words, I don't want to have a specific starting color. Instead the current color shall be used and faded to red.
0
Unity How to make grass details look good from top down I have an issue with the terrain details. Since it only draws a single plane per texture, it looks quite crappy with a angled top down camera, for example for an RTS camera. Is there some way around this, I know one solution people use is to angle the grass towards the camera a bit, but that isnt possible with the terrain details painter. The issue is circled in red If there is no solution to this, are there some techniques I can use to make some interesting looking grass for an RTS camera?
0
When an animation involves movement, where is the movement better to implement? For context, I am using Blender and Unity. Regarding the question, as an example, in some games, when you get hit, your character tucks a bit and gets knocked back a few distance. The tucking animation I want to implement in Blender but how about the knockback distance? Do you move your model in Blender (tuck and knockback), or do you do the tuck animation only (tuck in place) and then handle the knockback in Unity (basically triggering the tuck animation and then moving the model backwards a bit). My question basically is, what's commonly done and if there's any specific reason, why?
0
Shooting weapons Unity I'm trying to create a falling word game like z type (code here). Once the game starts a few words are displayed on the screen. When the user types a letter and if that matches with the first letter of any of the words displayed, an "activeWord" tag is added to the word. I have also created a laser script that checks if the tag is active and when that happens, it shoots the laser. What's happening right now is that the laser is shot only once i.e when the first letter matches but doesn't shoot a laser when the remaining words are typed. Can someone please have a look at the code and tell me where I'm making a mistake. this is the word display script where the active word is assigned public void RemoveLetter() remove the first letter if its correct and so on for the remaining letters. change the color of the word to red and add the "activeddWord" tag. text.text text.text.Remove(0, 1) text.color Color.red text.gameObject.tag "activeWord" public void RemoveWord() Destroy(gameObject) removes the word from display here is the input manager script public class WordInput MonoBehaviour public WordManager wordManager void Update () foreach (char letter in Input.inputString) wordManager.TypeLetter(letter) EDIT This is the player script where the laser is instantiated public class Player MonoBehaviour public GameObject laserPrefab void Start () transform.position new Vector3(0.0f, 3.92f, 0) player position void Update () Instantiate(laserPrefab, transform.position, Quaternion.identity) This is the updated laser script public class Laser MonoBehaviour public float speed 10.0f private Vector3 laserTarget private void Start() GameObject activeWord GameObject.FindGameObjectWithTag("activeWord") if (activeWord ! null amp amp activeWord.GetComponent lt Text gt ().text.Length gt 0) laserTarget activeWord.transform.position find position of word transform.Translate(laserTarget speed Time.deltaTime) for (int i 0 i lt Input.inputString.Length i ) Debug.Log("Character from input string " Input.inputString i " n" "Character from word displayed " activeWord.GetComponent lt Text gt ().text 0 ) if (Input.inputString i activeWord.GetComponent lt Text gt ().text 0 ) laserTarget activeWord.transform.position find position of word transform.Translate(laserTarget speed Time.deltaTime) shoot the laser After I do this, there are two major errors that I get As soon as I hit play, the laser fires continuously without stopping. The laser still shoots only once after the word is typed...This is the message I get in the console (screenshot attached). There is a difference of one word between the input string and whats displayed on the screen...Can someone please tell me how to rectify these.....
0
There any way to insert images inside the code (just for comprehesion) in any IDE compatible with Game Engine Unity3D (Monodevelop for example)? My code has a lot of geometry codes, thinks that shouldn't be represented just by comments I don't know if it exists, but should be fine to insert images like png in the middle of codes explaning that math behind, just in case I forget what any classes method lines do in future. Thanks.
0
How do I calculate a line segment that is a certain number of degrees from another line segment? I have a line segment that is at an arbitrary angle in 3D space. I want to (in code) draw another line that shares an end point with the first line and has an angle of arbitrary degrees between them. The second line will partially overlap the first in the XZ plane.
0
How can I programmatically add a Controller to an Animator during runtime? I am trying to set the Controller of an Animator during runtime using a script. When I click on the dot in the inspector manually, I can choose one called quot Standard Walk quot , but have not found a way to automate it.
0
Can I export a model and texture from a terrain file built in Unity3D? I am mostly familiar with building my level maps within unity, and have become quite use to its inbuilt terrain creator, in both generating my terrain, and spraying a texture on to it. I am making a game using MonoGame XNA, and would like to use a terrain map I built with Unity. I would have to recover the file, however, and have not been able to find anything to support being able to, in the first place. Can I export my terrain file with its texture, in any way, to use in XNA MonoGame?
0
Allow player to restart animation after it plays fully I have this code that plays an animation when the player touches the screen. The animation lasts 3 seconds. public class canCDanim MonoBehaviour public Animator anim private void Start() anim GetComponent lt Animator gt () void Update() Touch touch Input.GetTouch(0) if (touch.phase TouchPhase.Began) anim.Play( quot CanReload quot ) The trouble is that if the player touches the screen again, the animation will not play again. How can I make it so that I can restart the animation, but only after it's finished playing?
0
Generate platforms and move them with same speed I'm building an infinite runner and have to generate pillars on which the player jumps. There's a minimum and maximum value for how much gap can exist between two pillars. In addition to this, i want the pillars to move to the left with increasing velocity. All pillars need to have same velocity. So, i made a pillarHolder object which would have velocity that increases with time. The instantiated pillars would be made children of this pillarHolder. Code is if ((Vector3.Distance (go.transform.position,transform.position) lt 25f)) t rand.Next(13,35) t t 10 Debug.Log(t) tempx t pos new Vector2(tempx, 2.22f) go Instantiate(pillar,pos,Quaternion.identity) as GameObject go.GetComponent lt Transform gt ().parent holder holder.GetComponent lt Rigidbody2D gt ().velocity new Vector2( 10f,0) The problem is, the pillarHolder keeps moving in the negative x direction and after a while, the pillars are not positioned properly. The gap between them exceeds the maxGap. I tried to solve the problem by resetting the pillarHolder's position once it went beyond position.x 20f. But when it's position resets, child objects are reset too. Any help please?
0
Load 3D model from external directory I am developing a desktop application that want to load the 3D model from desktop. Using file explorer user wants to choose the 3d model then it want to show in the application scene.I tried to find the object, the path is detecting but if i tried to Instantiate it on unity it showing this error. ArgumentException The Object you want to instantiate is null. here the code is used public class ReadData MonoBehaviour string path GameObject go public void OpenExplorer() path EditorUtility.OpenFilePanel("Overright with model", "", "dae") Debug.Log(path) GetObj() void GetObj() if(path! null) UpdateObject() void UpdateObject() WWW www new WWW("file " path) go GameObject.Find(path) Instantiate(go) Anybody please help me to do this. Thanks in Advance.
0
Update method from script doesn't called After experiments with Unity versions, I have reproduced Mandelbrot example from scratch and got C script doesn't called. If I set breakpoint, it says it is not reacheable I think I set up all links. As it seem from IDE hint, inheritance is correct. Simultaneously, shader is working, i.e. image is displayed, but not updated by controller.
0
What design pattern should be used when there are a lot of different possible jobs? Some background information on what I am trying to accomplish. I am creating the game in Unity using C . Basically, I am trying to create an RPG type of game where it really harps on the idea of a lot of different possible classes jobs(I will call them jobs so not to confuse anyone). Basically, every job will have its own unique set of skills and can only do certain tasks, not dissimilar to a lot of games out there. However, the way I see most of the advice given down this path is simple inheritance, mostly because the user is only trying to implement 2 or 3 unique jobs. I feel as though this is just the easy answer that ends up causing a lot more headaches in the long run when you have lots of different jobs to implement. So my main question is, what design patterns would someone use when there are a lot of different jobs that the programmer needs to implement?
0
Unity crossplatform native plugins I need to create a c native plugin for my game. If I want to support macOS and Windows, do I need to write my plugin twice one in XCode with a bundle project and another in VS for windows or is there a way to support both with one codebase?
0
Discoordinated Chromatic Aberration Effect The game Teleglitch heavily utilizes the CA effect with screen distortion. I am trying to achieve this effect. Issue 1. How to not apply the effect onto the floor? (solved) They render the screen then apply the CA effect. However, the floor is not rendered with the post processing effect. Issue 2. How to have discoordinated position for each rendered CA effect? Currently I have three offsets for each channel red, green, and blue. However, I cannot assign different offsets for the channels for certain areas only. What would be a way to have discoordinated positions?
0
How do I create a sphere by script? I want to add a sphere at runtime via script. I have the following code which compiles fine. At runtime however, no sphere is added to the scene. I have attached the debugger to the script, and I have set breakpoints at each line. After the line Material nMat new Material(Shader.Find("Lit")) I'm using the URP the debugger "blanks" out, it doesn't hit the next line. What am I doing wrong? Thank you! using System.Collections using System.Collections.Generic using UnityEngine public class SphereMaker MonoBehaviour private GameObject Sphere void Start() Sphere GameObject.CreatePrimitive(PrimitiveType.Sphere) Sphere.AddComponent lt MeshFilter gt () MeshRenderer nRenderer Sphere.AddComponent lt MeshRenderer gt () Material nMat new Material(Shader.Find("Lit")) I'm using the URP if (nMat null) Debug.LogError("no mat!! n") nMat.color Color.red nRenderer.material nMat Sphere.transform.localScale new Vector3(0.4f, 0.4f, 0.4f) Sphere.transform.position new Vector3(0, 0, 0)
0
How do I create a HUD that appears to occupy 3D space can animate? I'm working with a group to try and make a first person space platformer in Unity, and was wondering if there would be anyway to create a HUD that moves and reacts to player actions, specifically looking around similar to the way the HUD moves in Metroid Prime. I'd also like it appear projected onto the inside of a helmet. I'm not entirely sure what best practice would be in this situation. Should we just attach the GUI elements to transparent objects in 3D space, then parent them to the main camera, essentially building our HUD with actual objects or is there another way that would be more efficient? I'm still very new to game development, but this is something we'd really like to have in our game if at all possible.
0
Speed dependent arc question I'm currenlty working on an assignment and would appreciate any sort of help on the following implementation The question follows We are tasked to implement some heuristics but one of them is really confusing to me. The following are a set of heuristics widely used by game developers for the movement of human characters while trying to reach a target A. If the character is stationary or moving very slowly If it is a very small distance from its target, it will step there directly, even if this involves moving backward or sidestepping Else if the target is farther away, the character will first turn on the spot to face its target and then move forward to reach it. B. Else if the character is moving with some speed If the target is within a speed dependent arc (like a narrow perception zone, or a cone of perception) in front of it, then it will continue to move forward but add a rotational component to incrementally turn toward the target Else if the target is outside its arc, then it will stop moving and change direction on the spot before setting off once more. B2 I'm not entirely sure what a speed dependent arc is. I googled it and it bring it back to the textbook( Artificial Intelligence for video games). My question is what is a speed dependent arc?
0
How can I make Matrix Rain? I want to make 3d Matrix rain like this shader that you can rotate camera.I tried to convert this shader but It have many calculations that it's expensive inside game engine.then I tried to make this effect by trail Renderer but I couldn't make random letters inside trail renderer.finally I tried by Instantiating quads but It hadn't fade like trail. so my question is how can I make this effect In efficient way?
0
Wall checking not working correctly Basically I am working on side scrolling 2d game. For that I want to check whether player is collided with wall. I have written some code for it but can't able to decide where I have done stupid mistake. So please guide me in this. If you need any more details then I am always available. Code for detecting wall RaycastHit2D hit Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance) if (Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance)) Debug.Log ("collider name " hit.collider.name) isDead true Debug.DrawRay (wallCheck.position, Vector3.right wallCheckDistance, Color.red) Following image gives you all idea about situation. In that I have allocated player with groundCheck and wallCheck flag. At present in wallCheck section, I am detecting ground as collider response after execution of above code. Above code I have placed in Update method for continuous checking. For this game, I want to do game over if wallCheck object detect any object in collision. Why wallCheck object detecting collision of ground object (stage1a)? That is big question of mine.
0
Everything black except where there's a light I have a camera in my scene with a map created at runtime As you can see everything can be seen. Now I want the map to be invisible (black as the background) except where there are lights. How can this be achieved in Unity3D?
0
is there any method to simply ignore some files in unity build? as im trying to build my new app on unity android specially when i want to use gradle, there is always some conflict with manifest or libraries and ..... for debug and problem exploration i need to ignore some folders to check for those bugs instead of need to move them somewhere else. i just thought about git branching but it can cause lots of branches and maybe not efficient
0
Play animation state's clip from particular time or fram I have a controller where i have a animation state. I want to play that animation clip from specified frame to specifed end frame. is this possible? here is the snap shot of the controller currently i am simply switching tow application using bool. I want to transition to paritcualr state but want to play its particular frame or time duration as a clip. public Animator talkingAvatarAnimator public bool isPlayHandGesture void Update () talkingAvatarAnimator.SetBool("isPlayHandGesture", isPlayHandGesture)
0
using Playerprefs on Android Mobile Platform I have a question about playerprefs on my android mobile game not initializing properly. I have already pre set my playerprefs data on a variable with a value of 3. In my play mode on unity the value is showing 3 through the textmesh that I have it scripted on. But when I install and test it on my android mobile device it is 0. can someone help how to properly initialize my playerprefs data to the right value on android platform? public static Game GM int maxAntiBody public TextMeshProUGUI antibodyTexMesh void Start () if (GM null) GM this maxAntiBody PlayerPrefs.GetInt("MaxAntiBody") antibodyTexMesh.text maxAntibody.toString() void Update () debugging() I use this method for setting or resetting my desired value for the playerprefs data I'm working with. In this case I choose 3 as a value. void debugging() if (Input.GetKeyDown(KeyCode.M)) PlayerPrefs.SetInt("MaxAntiBody", plus ) Debug.Log("max anti body value is " PlayerPrefs.GetInt("MaxAntiBody")) else if (Input.GetKeyDown(KeyCode.R)) plus 0 PlayerPrefs.SetInt("MaxAntiBody", plus) Debug.Log("max anti body is now reseted to " PlayerPrefs.GetInt("MaxAntiBody"))
0
Need insight on item system I have made an item database that takes keyed values from a database script then assigns them to an item class, then stores that item class in a List variable. This works fine but I have come across something that I see as potentially troublesome. For every unique effect, I have to make another keyed value and apply it to all the existing collections in the database. I want to make it such that an item can hold only 6 special values(physical damage, magical damage, armor, heal, etc) but with this method, I don't know how to tell the script which value goes to which special effect. Below is a template item from the database file. I use GRFON for this. See how I have written down all the possible damage types but for special values, I made 7 only with 6 of them being generic. The damage types can easily be assigned but when it comes to the special values, I have a hard time assigning magnitudes to special effects. iD 0 name Template category Null type Null subtype Null values physical 0, magical 0, hot 0, cold 0, electric 0, dark 0 specialvals spMag1 0, spMag2 0, spMag3 0, spMag4 0, spMag5 0, spMag6 0, spDuration 0 special none . properties mass 0, durability 0, maxdurability 0, charge 0, maxcharge 0, accuracy 0, useRate 0, reloadRate 0, range 0 description This is a template item. equippable 0 usable 0 stackable 0 maxStacks 1 count 0 rarity 0 price 0 uID template
0
Unity random.range value not same as last value Quick one, Currently using Unity Random.Range to set a var with the value of an enum state. State has 4 possible values, up, down, left,right. I call it like currentState (StateType)Random.Range(0, 3) This gets set at certain conditions. My issue is though I don't want the new setting to be the same as the current one. I have taken a look at the random.range on the API but haven't found anything useful. Is there an easy way to basically say "randomize but not the same as the current state" EDIT Currently im using a while loop. while (currentState LastState) currentState (StateType)Random.Range(0, 3) Is there anything i can do to remove the while loop?
0
How to make local keyboard input move only the local player, not everyone in networked multiplayer? I am working on Unity Networking and following this Tanks Networking tutorial https www.youtube.com watch?v V6wEvT6G92M Problem is that the keyboard inputs move all the tanks in the scene. It is not detecting the local tank. And when I run the game all tanks shows the same movement but it is not giving any error. I have followed all steps in the tutorial and searched all solutions on the google. This step in Tutorial is at 11 48. Implemented Code is using System.Collections using System.Collections.Generic using UnityEngine using UnityStandardAssets.CrossPlatformInput using UnityEngine.Networking public class TankController NetworkBehaviour Use this for initialization Header("Movement Variables") SerializeField float movementSpeed 5.0f SerializeField float turnSpeed 45.0f Header("Camera Position Variables") SerializeField float cameraDistance 16f SerializeField float cameraHeight 16f Rigidbody localRigidBody Transform mainCamera Vector3 cameraOffset void Start () if (!isLocalPlayer) Destroy(this) return localRigidBody GetComponent lt Rigidbody gt () cameraOffset new Vector3(0f, cameraHeight, cameraDistance) mainCamera Camera.main.transform MoveCamera() Update is called once per frame void FixedUpdate () float turnAmount CrossPlatformInputManager.GetAxis("HorizontalUI") float moveAmount CrossPlatformInputManager.GetAxis("VerticalUI") Vector3 deltaTranslation transform.position transform.forward movementSpeed moveAmount Time.deltaTime localRigidBody.MovePosition(deltaTranslation) Quaternion deltaRotation Quaternion.Euler(turnSpeed new Vector3(0, turnAmount, 0) Time.deltaTime) localRigidBody.MoveRotation(localRigidBody.rotation deltaRotation) MoveCamera() void MoveCamera() mainCamera.position transform.position mainCamera.rotation transform.rotation mainCamera.Translate(cameraOffset) mainCamera.LookAt(transform) I have also checked the auto create player in the spawn info as suggested in some solutions.
0
Animated textures for models How to write a shader? Was watching some Rocket League and notice there was animated decals and wheels. . I would like to implement something similar to the effects in the image above. How would I go about writing a Unity Shader to do the wheel effect? I don't know much about Shaders, but can I edit the standard Unity Shader to do the animation effect?
0
Is it possible to tile box colliders without causing "false" collisions in Unity3D? This is in regards to something like a sidescroller where you have a tiled map where each tile uses a 2d box collider. If you use a 2d circular collider as an example for your character, as it rolls across a series of tiled 2d box colliders, it will occasionally collide with the seams between tiles rather than rolling smoothly across them. In my scenario here, the tiles are 1x1 units snapped directly adjacent to each other. When rolling a 2d circular collider across a row of tiles, it goes mostly smooth but the more force applied, the greater chance of the circle flying up into the air rather than it's y staying the same as it rolls across them. The obvious conclusion I had was to use edge colliders instead which works fine, but I'm hoping to find a way to completely eliminate this problem even with just 2d box colliders. Thanks, Tim
0
Unity3d wheelcollider falling through terrain I have created simple project with 3D car and terrain. I have added 4 Wheel Colliders on model wheels. But when I run project wheels falling through terrain. Before run After run I am sure that at start wheel colliders above the terrain and not intersect it. Configuration is In what problem is? I have tried a lot of different things but I can't find a solution.
0
Why are parts of this Unity scrollrect not being bound to the mask? I'm setting up a system for people to load up extra levels. Since I don't know how many levels are going to be loaded I have a UI prefab that gets added to the main Level Load UI. However, the Text components of the prefab are not being bound by the scrollrect mask. The panel, images and button all are, and they are all children of the panel getting added to the panel that is the scrollrect's content. Another related problem, each of the prefabs also has a button on it. I've given it some alpha because I find that once it's in the scrollrect only the top half is clickable. You can see below that it only highlights (as red) if your on the top half of the button. The exception is that the final button will work if your mouse is anywhere on the button. This isn't an issue for the buttons if they're just placed in the scene. It only happens inside the scrollrect. I have a smaller version of the project right here for download. The 'main' gameobject starts a script that instantiates the main 'Load Level Screen' prefab and populates it with the 'LoadLevel Single' prefabs. I've been banging my head against the wall for over a week now, so any help would be appreciated!
0
save a particular area of the scene as screenshot in unity I need to save a particular part of the scene as screenshot. I have done a sample to show the particular part of the scene. When I click on the rectangular area the selected area will being shown on the screen on a texture (marked in red rectangle) But when I save, the whole scene is getting saved but not the selected part Here is code Texture2D screencap Texture2D border bool shot false public string path void Start () screencap new Texture2D(300,200,TextureFormat.RGB24,false) border new Texture2D(2,2,TextureFormat.ARGB32,false) border.Apply() Update is called once per frame void Update () if(Input.GetKeyUp(KeyCode.Mouse0)) StartCoroutine("Capture") string fileName(int width, int height) return string.Format("screen 0 x 1 2 .png", width, height, System.DateTime.Now.ToString("yyyy MM dd HH mm ss")) void OnGUI() GUI.DrawTexture(new Rect(200,100,300,2),border,ScaleMode.StretchToFill) GUI.DrawTexture(new Rect(200,300,300,2),border,ScaleMode.StretchToFill) GUI.DrawTexture(new Rect(195,100,2,200),border,ScaleMode.StretchToFill) GUI.DrawTexture(new Rect(500,100,2,201),border,ScaleMode.StretchToFill) if(shot) GUI.DrawTexture(new Rect(50,10,60,40),screencap,ScaleMode.StretchToFill) Application.CaptureScreenshot(myFolderLocation myFilename) IEnumerator Capture() yield return new WaitForEndOfFrame() screencap.ReadPixels(new Rect(198,98,298,198),0,0) screencap.Apply() shot true byte bytes border.EncodeToPNG() string filename fileName(Convert.ToInt32(screencap.width), Convert.ToInt32(screencap.height)) Application.CaptureScreenshot("D " filename) How can I save only the particular part in unity,can anybody please help me out.
0
Building meshes conforming to terrain deformation I have an uneven terrain on which the player is supposed to build buildings. For most structures I can just fudge the foundations, have them extend through the terrain. For roads, pipes, tracks and such I do have however the problem how to make them line up. What techniques can I best use to make the meshes of adjacent pieces line up, making it conform to the terrain?
0
How to Enable canvas with Event during a animation clip I want to enable a canvas while an animation clip is playing, I used animation Event and call the following script to enable the canvas, but the editor does not recognize any game object. How a canvas can be enabled? public void SetActiveTrue(GameObject game object) game object.SetActive(true)
0
How make circle with multiples holes In Unity, how can I programmatically make a shape like The gaps in the shape will all be the same size but their number may vary.
0
How can I implement foot pedal of a car in unity? I trying to create 2 D car game in unity for mobile where player controls acceleration by sliding the pedal in touch screen.Mine idea of implementation is using UI slider. Is there any other good I can use? Please suggest me any other implementation if any available.I'm new to this field.
0
Speedup Dev process for bug fixing and debugging in Unity? We're using Unity 2017 for a big Indie game. at the moment We have some issues with our development speed In order to fix issues and bugs, We used the visual studio and attach the process to Unity and go through the code step by step. every time we change something (even just a line of code) we back to unity and wait for all scripts to recompile which takes up to 1 minutes sometimes. after that, we run the game and go to the place that bug happened which takes us about two minutes. I was wondering if there was a Best practice for fixing issues and debugging in Unity which brings us speedup on script compiles and also helps us to get to bug location faster.
0
How can I move an object over linerenderer lines positions? I have 4 cubes the first 3 cubes connected with two lines one of the lines is curved. The fourth cube I want to move over the lines. The lines is built using linerenderer and in the linerenderer there are 397 positions. I created a small script that move an object over the positions. I checked and I have in the array 397 positions and the loop get to 397 but the object (Cube (3)) never moving all the positions only some. Or maybe the positions I get are not the same in the linerenderer ? This screenshot show some of the positions in the linerenderer this is the positions I want the object to move on Why the object is not moving over all the positions , only on some ? And this is the script I created that should move it using System.Collections using System.Collections.Generic using UnityEngine public class MoveOnCurvedLine MonoBehaviour public LineRenderer lineRenderer public GameObject objectToMove public float speed private Vector3 positions new Vector3 397 private Vector3 pos private int index 0 Start is called before the first frame update void Start() pos GetLinePointsInWorldSpace() Vector3 GetLinePointsInWorldSpace() Get the positions which are shown in the inspector var numberOfPositions lineRenderer.GetPositions(positions) Iterate through all points, and transform them to world space for (var i 0 i lt numberOfPositions i 1) positions i transform.TransformPoint(positions i ) the points returned are in world space return positions Update is called once per frame void Update() if(index lt pos.Length 1) objectToMove.transform.position pos index Time.deltaTime speed index Now I checked using a breakpoint the first position in the linerender at index 0 is X 30.57, Y 6.467235, Z 4.98 But in my script in the pos array I see that in index 0 the position is X 30.6, Y 6.5, Z 5.0 And the result is that the object that move Cube(3) is moving only some of the way and also it's not exactly on the line Why the object is not moving over all the positions , only on some ? Something is wrong in my script with getting the right positions from the linerenderer and maybe also the loop and the move is wrong. I can't figure out ho to do it.
0
Unity2D wait for coroutine to finish to activate it again is there a way to start another coroutine once the last coroutine is finish. I have a button that activates a coroutine, the button can be pressed any time you want, when pressed you activate a coroutine. However I notice that when you press the button twice the coroutine happens twice, which is not want I want. Is there a way to make sure that once my Boomerangeffect(coroutine) is activate the coroutine can't start (if button is pressed) until the present coroutine is finished. public GameObject BoomerangOn, BoomerangOff public static int buttonCount 4 static int timesActivated 0 void Start() if (PlayerPrefs.HasKey ("boomerangbutton")) buttonCount PlayerPrefs.GetInt ("boomerangbutton") void Update() PlayerPrefs.SetInt("boomerangbutton", buttonCount) public void Activated () if(timesActivated lt buttonCount) timesActivated StartCoroutine(BoomerangEffect()) IEnumerator BoomerangEffect() BoomerangOn.SetActive (true) yield return null yield return new WaitForSeconds (10.0f) yield return null BoomerangOn.SetActive (false) yield return null BoomerangOff.SetActive (true) yield return null yield return new WaitForSeconds (1f) yield return null BoomerangOff.SetActive (false) yield return null
0
Why do I keep getting an exception about "an element with the same key already exists" in this code? I'm trying to follow this tutorial about object pooling in Unity I got to minute 17 22. But when I run the game I get this exception ArgumentException An element with the same key already exists in the dictionary. System.Collections.Generic.Dictionary 2 System.String,System.Collections.Generic.Queue 1 UnityEngine.GameObject .Add (System.String key, System.Collections.Generic.Queue 1 value) (at Users builduser buildslave mono build mcs class corlib System.Collections.Generic Dictionary.cs 404) ObjectPooler.Start () (at Assets Scripts ObjectPooler.cs 31) This script is attached to a new empty GameObject using System.Collections.Generic using UnityEngine public class ObjectPooler MonoBehaviour System.Serializable public class Pool public string tag public GameObject prefab public int size public List lt Pool gt pools public Dictionary lt string, Queue lt GameObject gt gt poolDictionary private void Start() poolDictionary new Dictionary lt string, Queue lt GameObject gt gt () foreach(Pool pool in pools) Queue lt GameObject gt objectPool new Queue lt GameObject gt () for (int i 0 i lt pool.size i ) GameObject obj Instantiate(pool.prefab) obj.SetActive(false) objectPool.Enqueue(obj) poolDictionary.Add(pool.tag, objectPool) Like in the tutorial I'm making size of 1 of the Pools in the Inspector then giving as tag name Cube then drag a cube prefab to the Prefab then set the size to 150. But I'm getting this exception when running the game.
0
Creating color texture from greyscale heightmap in shader I'm trying to create a shader that takes a grayscale map as input, and returns a colored albedo that I want to use as texture for my PCG planets, I think that the code below should work, but it only produces flatly white objects. I'm a total shader noob, so I'm terribly sorry if I'm missing something obvious here. Shader "Custom Planet" Properties height("HeightMap", 2D) "white" SubShader Tags "RenderType" "Opaque" LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard fullforwardshadows Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 struct Input float2 heightMap float minHeight 0 float maxHeight 1 float inverseLerp(float a, float b, float v) return saturate((v a) (b a)) UNITY INSTANCING CBUFFER START(Props) UNITY INSTANCING CBUFFER END void surf (Input IN, inout SurfaceOutputStandard o) float hv inverseLerp(minHeight, maxHeight, IN. heightMap) o.Albedo hv ENDCG FallBack "Diffuse"
0
Sprite always starts flipped Everytime I start the game, or I swap animator controllers in the inspector (in runtime), the character is flipped in X axis until I start moving him. How do I prevent this to happen? This happens to me everytime I start a new project and I grow tired of this. Update 8 animations which are all idle ones of just 1 frame Down DownRight Right UpRight Up The last 3 have the Sprite Renderer's flipX enabled within their animations UpLeft Left DownLeft In the middle of the transitions, sprite remains flipped until it reaches 1 or 1. I recorded recently a video to display the issue. https www.youtube.com watch?v dC09snKvHAM Same as above but in 1080p and showing entire Unity window. https www.youtube.com watch?v Ww3GkUvb7bc 2nd update PlayerControls.cs using UnityEngine using System.Collections public class PlayerControls MonoBehaviour Rigidbody2D rb PlayerStats pStats Animator anim void Awake () rb GetComponent lt Rigidbody2D gt () pStats GetComponent lt PlayerStats gt () anim GetComponent lt Animator gt () void Update () if (Input.GetAxisRaw("Vertical") gt 0) rb.velocity new Vector3(rb.velocity.x, pStats.pMoveSpeed, 0) if (Input.GetAxisRaw("Vertical") lt 0) rb.velocity new Vector3(rb.velocity.x, pStats.pMoveSpeed, 0) if (Input.GetAxisRaw("Horizontal") lt 0) rb.velocity new Vector3( pStats.pMoveSpeed, rb.velocity.y, 0) if (Input.GetAxisRaw("Horizontal") gt 0) rb.velocity new Vector3(pStats.pMoveSpeed, rb.velocity.y, 0) if (Input.GetButton("Vertical") Input.GetButton("Horizontal")) anim.SetFloat("OrientationY", Input.GetAxisRaw("Vertical")) anim.SetFloat("OrientationX", Input.GetAxisRaw("Horizontal")) PlayerStats.cs using UnityEngine using System.Collections public class PlayerStats MonoBehaviour public string pName public string pClass public int pLevel public float pExperience public float pBasicDamage public float pMoveSpeed public string pClassList Animator anim public RuntimeAnimatorController animCtrl void Awake() anim GetComponent lt Animator gt () void Update() pLevel 1 (int)pExperience 240 if (!CheckAssignedClass()) pClass "Warrior" Debug.LogWarning("Player class not found. Using 'Warrior' as default.") if (Input.GetKeyDown(KeyCode.J)) SetClass(pClass) bool CheckAssignedClass() bool found false var i 0 for (i 0 i lt pClassList.Length i ) if (pClassList i pClass) found true break else found false return found void SetClass(string className) switch (className) case "Warrior" anim.runtimeAnimatorController animCtrl 0 break case "Archer" anim.runtimeAnimatorController animCtrl 1 break case "Mage" anim.runtimeAnimatorController animCtrl 2 break default anim.runtimeAnimatorController animCtrl 0 break
0
How do I know the data has arrived at server without requesting every frame of the game? I have a game where I have to get data from the server but the problem is I don't know when the data will become available on server. So I decided to use co routine and hit server at after specific time or on every frame. But certainly this is not the right, scale able and efficient approach. Now my question is that how do I know that data has arrived at server so that I can use this data to run my game. Or how should I direct the back end team to design the server in an efficient way that it responds efficiently. Our back end team currently uses REST Web services with JSON with Python. And they want to push data to my unity player without my frequent requests.
0
How to create a normal map for my dice texture? I have this simple dice texture and would like to create a normal map for it where the black dots are are dents and the edges are trimmed(like on a actual dice) I'm using unity5. I need a explanation on how to create the normal map in PhotoShop CS5 or a code solution. Thanks in advance. Here is the dice texture I'm using.
0
C Script file is not showing in Onclick Event in Unity 5.0.4f1? I uploaded the levelLoader file to the gameobject. Still, when I drag the script file onClick Event, the no function is null. Why? Can anybody help me? C code using UnityEngine using System.Collections public class LevelLoader MonoBehaviour Use this for initialization void Start () Update is called once per frame public void LoadLevel(int a) Application.LoadLevel(a) public void Quit() Application.Quit() Correct me where I am wrong. I am following this racing car game tutorial. At 7 58 he added this event. Please help me!!!
0
Fade a texture effect as it nears the end of a cylinder mesh In my game I have a laser beam that travels for about 15m, but abruptly stops due to the mesh the texture is attached to. How can I setup my shader graph so that the end of the texture fades away? I can't find anything similar to this anywhere online, and have tried multiple things (gradient colors with lerp attached to alpha) but just can't figure it out as I'm too new to the whole shader graph thing. Anything helps, thank you. Note The texture is 'animated' and scrolls along the path of the beam using the shader graph
0
Good way to establish an inventory system? Fairly new to Unity as a whole, and while making a prototype game I came across the issue of setting up an inventory system. So far, I've been stuck on what sort of structure it should have, given Each quot Mob quot (player, enemy, NPC, etc.) has its own inventory Objects can have children attached, which should be saved (e.g. Gun gt Attachment Manager gt Magazine Rail etc.) Simpler items (ammunition, etc.) are stackable An inventory has quot pouches quot which are available only for certain objects (magazines, health items, etc.) and have a certain volume At first, I simply made a Mob gt Inventory Manager gt Pouch gt Item system where everything was a child of its respective parent, but obviously even with colliders sprites disabled that's possibly hundreds of transforms per mob being shifted around each update. Right now, I'm just parenting each mob's inventory system to a static quot Inventories quot object to get past the issue of that many transforms, but is there a better long term solution that takes into account saving loading and scene transitions? Right now, I'm considering Turning each item with children (guns with attachments) into a prefab and saving it (not ideal) Using an ID system to instantiate objects on load by loading the root object (gun), then the children (attachments) given certain parameters (but the variables, like the rounds loaded into a magazine, would be tricky to load) Having different prefabs for items depending on whether or not they're equipped, on the ground, or in an inventory, and switching between them as needed
0
How to force a translation to go through an exact point? I have a camera object with a script that will whether translate it with a set speed, or stop it. I also have 7 "checkpoints", where there are 7 different quads, who will stop the camera whenever the camera reaches them. The problem here is that in my code void Update() if (scoreholder.CheckScore() lt scoretimer) if the current score is less than set X score if (killcam.transform.position.y quadholder.y) and if the camera's position equals the position of the generic quad PROBLEM HERE killcam.GetComponent lt cameraUp gt ().SetCam (true) stop the cam while (scoreholder.CheckScore () lt scoretimer) do stuff offset mr.material.mainTextureOffset offset.y offsetSpeed 0.1f mr.material.mainTextureOffset offset break else once the score is not less than the desired X score, move the cam killcam.GetComponent lt cameraUp gt ().SetCam (false) So my problem here is that this line of code if (killcam.transform.position.y quadholder.y) never happens, the translation skips some values, and the camera doesn't hit the exact quad spot. I tried to use gt instead of , but I ran into another problem, is that after the 3rd quad, since my camera speed increases in time, the code apparently doesn't get processed fast enough, and my camera goes beyond the 4th,5th,6th, and 7th quad without stopping. I have already tried Vector3.Lerp, and it gives me almost the same result, if I lerp between the beginning and the end of the track, I have to do it with an extremely small fraction, and I can't have my camera move at that speed.
0
Process for converting unity asset to scenekit scene resource Has anyone successfully figured out a method for converting a unity3d asset to a 3d SceneKit model scene? I imagine it would require exporting the asset into some third party file type, and then importing into scene kit. If you have any knowledge that can help me, would you kindly explain the process? Unity3d has a fantastic asset store, and I want to import some of these things to a project that requires scenekit (unfortunately, "just use unity" is not really an answer to my problem set).
0
Unity Assigning a key to perform an action in the inspector I am trying to write a simple piece of code in JavaScript where a button toggles the activation of a shield, by dragging a prefab with Resources.load("ActivateShieldPreFab") and destroying it again (Haven't implemented that yet). I wish to assign this button through the inspector, so I have created a string variable which appears as intended in the inspector. Though it doesn't seem to register the inspector input, even though I changed the value through the inspector. It only provides the error "Input Key named is unknown" When the button name is assigned within the code, there is no issues. Code as follows var ShieldOn false var stringbutton String function Start() function Update () if(Input.GetKey(stringbutton) amp amp ShieldOn ! true) Instantiate(Resources.load("ActivateShieldPreFab"), Vector3 (0, 0, 0), Quaternion.identity) ShieldOn true
0
Can Cloud Functions be used for a multiplayer game server? I'm building a turn based online multiplayer game with Unity for both desktop and mobile. Traditionally, I would build a Java socket server, host it in Google Compute Engine or similar, and have players connect to it. Since this works with sockets I can easily notify players of relevant events, such as matchmaking, chat, enemy turn, etc. I've been curious about Serverless Functions for a while, such as Google Cloud or Amazon Lambda. However, at first glance it doesn't seem to me like that would work for my game because there ins't a constant connection (with sockets), I can't notify players of relevant events in realtime or can I? For mobile I realize I could probably use something akin to push notifications (so the serverless code may push messages to the relevant player's phone). But that doesn't seem as simple for desktop games. Well, what if the players poll for messages? Like every second, call a Cloud function and ask them if there's anything for them. I'd image that would work, but that seems rather overkill with as little as a couple thousand players, calling the same function every second for prolonged times (the game's matches are long) sounds like it would easily increase expenses. Is there something I am missing? A coding practice that would make serverless code feasible for a cross platform online multiplayer game? I want to make it work, but it would seem like a socket server is still my only option.
0
Resize from one side of the object in runtime Unity For now I managed to resize my object but it resizes always from the center. I have the same problem like this question here. I've been thinking like adjusting the position and stuff, but nothing works for my code. Here's my code if (isMouseDragging) tracking mouse position. Vector3 currentScreenSpace new Vector3(Input.mousePosition.x, Input.mousePosition.y, positionOfScreen.z) converting screen position to world position with offset changes. Vector3 currentPosition Camera.main.ScreenToWorldPoint(currentScreenSpace) offsetValue if(getTarget.CompareTag("LeftRightWall")) currentPosition.y getTarget.transform.position.y currentPosition.z getTarget.transform.position.z if(getTarget.CompareTag("FrontWall")) currentPosition.x getTarget.transform.position.x currentPosition.y getTarget.transform.position.y It will update target gameobject's current postion. Vector3 v3Scale getTarget.transform.localScale getTarget.transform.localScale new Vector3(v3Scale.x 0.1f , v3Scale.y , v3Scale.z) getTarget.transform.position new Vector3(mfX getTarget.transform.localScale.x 2.0f, 0 , 0) getTarget.transform.position currentPosition My idea is I want to make the gameobject tagged LeftRightWall will be resized whenever the FrontWall is dragged and vice versa, like adjsuting the room size but I want to know how to resize them first. Any ideas?
0
Unity editor, horizontal line in inspector How to draw a horizontal line in the inspector like on the reference image? Kind of separation line.
0
Detect collision with static collider only Is this possible to detect collision with static colliders only I check it is not working. I dont want to use rigidbody or character controller with my box collider.
0
Can I pause Unity Setup download and continue it whenever possible as per convenience(using Unity Hub)? Actually I get only 1.5GB data daily. So it's not possible for me to download the whole Unity setup in a day. So I wanted to know if I can pause and resume download process as per convenience. I am downloading using Unity Hub.
0
Unity How to make input field respond to only double taps in Android? I am using Unity in my Android project. There are input fields in my app. As soon as I click on the field the keyboard pops up. I want the keyboard to only show up when there is a double tap on the field. But I am not able to get it to work and I have tried several ways. Requirement 1 Single tap shouldn't open keyboard Requirement 2 Double tap should open keyboard I tried OnPointerClick method of IPointerClickHandler but this doesn't seem to work. I used this code in one of the scripts attached to input field with IPointerClickHandler. public void OnPointerClick(PointerEventData eventData) if (eventData.clickCount 2) Debug.Log("UNITY Double click") else if (eventData.clickCount 1) Debug.Log("UNITY Single click") Then there is also the question of how to hide the keyboard or prevent it from opening on single tap. This also I am not able to solve. I started with clicking the Hide Soft Keyboard in control setting of InputField in Unity editor. But surprisingly this starts opening a keyboard which has mobile input. Can someone help? I have been stuck on this for some time I can't seem to be getting anywhere.
0
Component based programming with child objects I am presently working on a game in Unity3d and have come to a cross road regarding scripting for repetitive child objects. Should these child objects handle its own scripting for best practice? For example, I have a parent game object, Game Board, that spawns repetitive child objects, Tiles, on the board. Right now, I let these child objects handle its own position on the board and its own animation when the tiles move. However, I can just as easily do this with the parent object's scripting class. The reason I chose to let the child object do so is because I believe that child objects should be as independent to the parent object as much as possible. But since these are repetitive child objects, I start to wonder if it is just as easy to do all the scripting in the parent object. This way I decrease the number of class instances in the child objects. According the component based programming, which method is recommended?
0
MissingComponentException There is no 'TextMesh' attached to the "Can" game object, but a script is trying to access it When I run my program I keep getting MissingComponentException There is no 'TextMesh' attached to the "Can" game object, but a script is trying to access it.Even though I have attached it as you can see In the script I am trying to edit the text of the Text Mesh like this private int count public TextMesh countText Use this for initialization void Start () count 0 counterText gameObject.GetComponent lt TextMesh gt () counterText.text "Count " count.ToString() What I want is to count the cans that have been shot, so what I do next is void OnCollisionEnter(Collider other) if (other.gameObject.CompareTag("Can")) other.gameObject.SetActive(false) count count 1 counterText.text "Count " count.ToString()
0
Best practice for 4x game management in Unity? I'm trying my hand at creating a turn based 4x game in Unity, with a galaxy map and 2D hexagon grid maps for each individual planet. The planet grid hexes would be gameobjects, with the overall grid being around 30x40 in size. The number of planets would be under 50. What would be the best way to set this up? I'm looking for a solid approach regarding performance here, but one that also caters to easier design programming would be a plus. Some approaches I've come up with Load all of the grids for the individual planets at the start into a single scene, with each being under a "planet gameobject", and then set those gameobjects to inactive. The galaxy map would be its own scene that is loaded additively when needed clicking on a planet to view it would set its associated gameobject to active and then unload the galaxy map scene. Instantiate the gameobjects for planets as they're called up the grid data for the planet is dynamically loaded as part of this. The planet gameobject is destroyed when no longer needed. Galaxy map would function the same as approach 1. Individual scenes for each planet, loaded unloaded additively when needed. A separate, single scene would be used for loading procedurally generated planets. Seems to have serious challenges for managing units resources across planets scenes. Approach 1 seems to be the most straightforward, as the core of the game would be managed in a single scene, but I am concerned about performance. I'm setting up some test projects to stress test the approaches, but it'd be great to get feedback from someone with more experience. Any help is appreciated!