_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Load Material from file path or parse .mat file to Material Unity Is it possible to load a material from a file path? Or, otherwise parse a .mat file saved on disk to a Material usable at runtime? I had naively thought it would be possible to assign the bytes from a .mat file, as read by File.ReadAllBytes to a Material object, but that does not seem to work. |
0 | How I start a over a new game using a ui button logic code? My Hierarchy have 3 main GameObjects Game Data where all the gameplay objects are stored as childs of the Game Data GameObject. Main Menu and all objects of the main menu stored as childs under the Main Menu GameObject. Game Manager GameObject that have a script that control the game like pausing the game or go to the main menu. By default the Game Data is disabled and all the gameplay objects childs disabled too. Then when starting the game with the main menu when clicking the button to start a new game I'm just activating the Game Data object This script is attached to the Main Menu using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class MainMenu MonoBehaviour public GameObject gameData public void StartNewGame() gameData.SetActive(true) public void ResumeGame() public void QuitGame() Application.Quit() This is working for first time starting a new game. And this script is attached to the Game Manager GameObject using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class GameController MonoBehaviour public static bool gamepaused false public GameObject gameData public GameObject mainMenu private void Update() if (Input.GetKeyDown(KeyCode.P)) gamepaused !gamepaused if (gamepaused) Time.timeScale 0f else Time.timeScale 1f if (Input.GetKeyDown(KeyCode.Escape)) gameData.SetActive(false) mainMenu.SetActive(true) Time.timeScale 0f This script is working. When pressing the P button the game pause continue. When pressing the ESCAPE key the game also pause but also back to the main menu by switching the gameobjects disable enable. Now let's say I pressed the escape key while playing the game and I'm back to the main menu now I want to start a new complete game but clicking the StartNewGame ui button. The problem is that this time I don't want to just active the Game Data like I did before gameData.SetActive(true) This time at least in my logic I want to destroy the existing Game Data and instantiate a new Game Data using a prefab I already have of the Game Data. This is my logic but I'm not sure how to do it. Or something like that. The main goal is to be able to start over a new game each time clicking the StartNewGame ui button. |
0 | Display Rich Text in a TextMeshProUGUI component I am rading a text to be displayed in a Text UI from an asset using the standard commands Resources.Load lt TextAsset gt ("nameOfMyTextAsset") The text is a .txt. The text contains richtext tags to format the text in bold or italics. The richtext tags are displayed as such. I am using TextMesh Pro and insert the text via the following cmd public TextAsset MainText MainText Resources.Load lt TextAsset gt ("nameOfMyTextAsset") this.GetComponentInChildren lt TextMeshProUGUI gt ().text MainText.text The text is displayed like this How can I read text with richtext tags from a text asset? |
0 | Unity, Player isnt following along the waypoints I have a player with a Rigidbody, I want it to follow along the Waypoints, I have a script for it I tested it first on a Cube, everything worked fine, but on my character it just moves Towards the first waypoint then stays on the first waypoint instead of going ahead. Even if I comment out the LookAt Code section its not working. It could maybe cause the Y position of the waypoints that my player is stuttering, I changed it now. It is now moving along but stuttering much. Here is a picture of the problem Here is my code public GameObject waypoints public float grindSpeed public float turnSpeed public int currentWaypoint private Animator anim private Rigidbody rb public bool isGrinding false void Start() anim GetComponent lt Animator gt () rb GetComponent lt Rigidbody gt () void Update() MoveAlongWaypoints() if(isGrinding) anim.SetBool ("isOnGrinding", true) else if(!isGrinding) anim.SetBool("isOnGrinding", false) void MoveAlongWaypoints() if(isGrinding) TRANSLATE transform.position Vector3.MoveTowards(transform.position, waypoints currentWaypoint .transform.position, grindSpeed Time.deltaTime) ROTATE var rotation Quaternion.LookRotation(waypoints currentWaypoint .transform.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, rotation, turnSpeed Time.deltaTime) if(transform.position waypoints currentWaypoint .transform.position) currentWaypoint void OnTriggerEnter(Collider other) if(other.gameObject.tag "GrindWayPoint") Debug.Log ("Waypoint!!") isGrinding true |
0 | Is it possible to customize the Scriptableobject inspector for Simple level data, without the use of PropertyDrawers? I've invented an innovative, new game mechanic for Bricker Breaker Quest and want to create a quick prototype to recruit a game development team. After wasting a week researching the best way to easily represent the simple level data, I reluctantly started using Scriptableobjects. Each level is defined as a List lt Block gt , where public class Block MonoBehaviour, IComparer lt Block gt public int x public int y public int lives 0 private int pastLife 0 private SpriteRenderer spriteRenderer private TextMeshPro text private void OnCollisionEnter2D(Collision2D collision) lives if (lives gt 0) UpdateVisualState() else gameObject.SetActive(false) private void Awake()... public void AddLives(int life)... How do I properly serialize the Block object so that I can enter the X, Y, and Lives integers directly in the Inspector? As a quick hack, I created a List lt Vector3Int gt instead of the Block List and use the Z input field to enter the lives. Seems like overkill to create a PropertyDrawer just to relabel one field. Any other advice is appreciated. |
0 | Suggestions on how to achieve circular "hole" in environment I'm working on a 2D Sidescroller and I'm wanting to achieve a object that when activated it creates a port hole to the sprites underneath, giving the appearance of the object "cleansing" the area. Edited image showing the desired effect At this point I have no idea how to achieve this and am after suggestions, thanks! |
0 | How do I run code for a period of time and then return to normal behavior? i wanna run a code for my special power for five seconds only and then return to my normal working. when that power activates i am changing my player's material and i wanna return to my old material after those five secs are over. this is the code i tried void Start () transform.GetComponent lt Renderer gt ().material.mainTexture texts 0 void Update () if (condition) for (int t1 0 t1 lt 5 t1 (int)Time.deltaTime) transform.GetComponent lt Renderer gt ().material mats 0 transform.GetComponent lt Renderer gt ().material.mainTexture texts 0 this code breaks the game i think because unity is freezing when the condition is being met. |
0 | why contacts length could be 0 when collision2D happens in Unity3D? I made a ball with RigidBody2d and CircleCollider2D to collide with other balls with the same component, and I simply use the following snippet to check the contacts of the collision public void OnCollisionEnter2D(Collision2D collision) if(collision.contacts.Length 0) Debug.LogWarning(" collision contacts length is 0 ") return futher more code to deal with situation when contacts exists And I found sometimes the collision could happen without contacts I mean the contacts array could contain 0 points. Why does that happen? Cause it's very important for me to find the normal direction of the collision, but without a contact point, I could find that. |
0 | Unintended sliding blocks Unity (5) physics A game I'm working on right now relies on the Unity physics system for collisions, gravity etc. This all works well except for one strange thing. When an explosive is placed on a stone cube, it'll slide right off. A video displaying the sliding behavior https www.dropbox.com s lr6lhnn30x61tvf Unity 202015 02 19 2013 41 39 54.avi?dl 0 The stone gameobject settings http puu.sh g3BFn c15483b8ea.jpg The explosive has the same settings except for that the Mass is 1. What could cause this weird sliding and how can it be fixed? |
0 | ERROR Destroying assets is not permitted to avoid data loss I want my gameObject named lvl 01 to destroy when I click left or right arrow key but it's keep showing this error "Destroying assets is not permitted to avoid data loss" instead of destroying that gameObject, Can anybody please tell me what is going wrong around here. using UnityEngine using System.Collections public class Level 01Text MonoBehaviour public GameObject lvl 01 Use this for initialization void Start () Instantiate (lvl 01) Update is called once per frame void Update () if((Input.GetKey(KeyCode.RightArrow)) (Input.GetKey(KeyCode.LeftArrow))) Destroy (lvl 01) Debug.Log ("Something is seriously going wrong around here") |
0 | Why isn't my BoxCollider2D doing anything? I'm trying to make a speech bubble appear when you approach the tutorial board. The bubble is there and it has its animation states "Appear" and "Disappear" Appear is called OnTriggerEnter2D Disappear is called OnTriggerExit2D The collider is on the parent, tutorial board The animator and script are on the bubble itself. This is the script I have attached to the bubble, the conditions script. using System.Collections using System.Collections.Generic using UnityEngine public class Conditions MonoBehaviour private Animator bubblecondition private BoxCollider2D boxCollider Start is called before the first frame update private void Awake() bubblecondition this.GetComponent lt Animator gt () bubblecondition.Play("Disappear", 0, 1f) void Start() bubblecondition.SetBool("Here", false) boxCollider this.GetComponentInParent lt BoxCollider2D gt () Update is called once per frame void Update() public void OnTriggerEnter2D(Collider2D other) if (other.tag "Player") bubblecondition.Play("Appear", 0, 0f) else return public void OnTriggerExit2D(Collider2D other) if (other.tag "Player") bubblecondition.Play("Disappear", 0, 0f) else return What am I doing wrong? I spent an hour trying to know why. I even tried to have the console write a message on collision but it's just dead. Not only that, but I also tried to make it public and referenced it, still nothing. Help me see my mistake ) |
0 | Unable to wire UI Text object to C Script I have created UI text object And then created Text field in behavior class using UnityEngine.UI public class Explorer MonoBehaviour public Material mat public Text text ... void FixedUpdate () ... text.text string.Format( quot x 0 quot , scale) If I just run it, it says Object reference not set to an instance of an object at runtime. If I try to drag ZoomText to Text slot, it doesn't allow me If I first drag ZoomText from Hierarchy to Project then it allows me to set Text slot, but still gives Object reference not set to an instance of an object at runtime. If I am trying to set text field by Find private void Start() text (Text) GameObject.Find( quot ZoomText quot ) it gives me Cannot convert type 'UnityEngine.GameObject' to 'UnityEngine.UI.Text' What I am doing wrong? Suspect may be incorrect types, but how to know correct ones? |
0 | LookAt different object smoothly in unity3d As picture depicted my camera moving on path i want to lookAt bath different object smoothly. Currently have tried trasnform.LooAt(activePath.gameObject.transform) but it producing jerky result. object suddenly lookAt to next object how to avoid it. I searched and found this sloution but it also not working var targetRotation Quaternion.LookRotation(activePath.gameObject.transform.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime) |
0 | Unity Toolbox pattern is not safe When I create a toolbox such is in this tutorial. How do I defend against breaking the pattern with multiple instances like this gameObject.AddComponent lt Toolbox gt () gameObject.AddComponent lt Toolbox gt () I when calling Toolbox.Instance I get following message Singleton Something went really wrong there should never be more than 1 singleton! Reopening the scene might fix it. Is there a way to defend against it ? |
0 | Combining cubes Issue in Marching Cubes I was trying to implement the marching cubes and combine every little cube this way I get a cube of vertices depending on their surfaceLevel I look for the ones that are below the surfaceLevel and get the edges that relates to them get a vertice out of the edge using the formula on http paulbourke.net geometry polygonise I put every vertex i created based on the edges on mesh.vertices I make the order on mesh.triangles based of the edge number on triTable i combine everything but i get this Here's my code https pastebin.com jqetCk8r. My guess was that the combine order of every marched little cube is not good. I've got no idea know how to solve this. ps the triTable doesn't show in the pastebin, i copied it from the same link above. |
0 | Player Flying after colliding Unity I have a Player with a capsule collider on him and i have various objects in the scene. Most of the objects have either mesh collider or box collider enabled. When i move my player and the player collides with any object, my player just starts flying into space, literally. Any way to fix this? Thanks in Advance. The code i have on my player is this using UnityEngine using System.Collections public class Controller MonoBehaviour Animator anim Rigidbody rbody float inputH float inputV int Life 20 bool Dead false public float sensitivity 10f void Start () anim GetComponent lt Animator gt () rbody GetComponent lt Rigidbody gt () void Update () if (Dead false) inputH Input.GetAxis ("Horizontal") 50f inputV Input.GetAxis ("Vertical") 20f anim.SetFloat ("inputH", inputH) anim.SetFloat ("inputV", inputV) float moveX inputV Time.deltaTime float moveZ inputH 0.5f Time.deltaTime this.transform.position this.transform.forward moveX this.transform.position this.transform.right moveZ transform.Rotate(0, Input.GetAxis("Mouse X") sensitivity, 0) if (Input.GetKey (KeyCode.Z)) Life if (Life 0) Dead true anim.SetBool("Dead",Dead) |
0 | Unity Animation makes object spawn at x0 y0 z0 I was making an animation for a coin in my game in Unity, and when I was testing the full game, I saw that the coin is spawning at x0 y0 z0 and is doing the animation there. Then I realized that it was the animation, that increases and decreases y position and y rotation, starting at 0. So, I need to make the animation, that increases and decreases position y and rotation y, without affecting the actual position, because it will be different the position of the coins each time. In a while I will upload a screenshot for describing better the problem. Any clue? |
0 | Unity multiple servers for rooms I have an FPS game that I'd like to make multiplayer. It would need to support multiple matches at once with about 10 players in each. However I want physics to be server authoritative so that means running a Unity instance. How do I have multiple Unity processes running on a server, creating destroy them as needed, having players connect to the instance they need, and so on? How does this vary between uNet Sockets LLAPI Photon Bolt etc? There just seems to be an atrocious lack of information on Unity networking and when people ask online there's almost never any answer, or it's too vague to be useful. |
0 | Using Burst Compile attribute on methods Can we use BurstCompile attribute without using any Jobs or ECS System in Unity? does adding BurstCompile attribute before methods bring us any benefits? |
0 | How do I make a slot car game? I new to game development with Unity and my first project is a slot car racer. For a realistic slot car like driving experience, I first build a track with a channel in the track and a pin on the car. This kind of works, but it does not look like a slot car, its more like a car with a pin and sometimes the physics just go crazy and kick me out of the channel. I next tried making a spline with a simple game object following the track. I attached my car to my "follower" with a fixed joint. This didn't work so well My car was tumbling and pulled sideway but I never archived that my car gets pulled down the track. How should I be approaching this? I'd like the car to accelerate and decelerate quickly, with that acceleration and deceleration controllable by the user. |
0 | How to add scene after build and deployed in Unity? I want to be able to make new levels after build. I could use a map tool and script but I rather just add scene with all the resource packed with it. But what is the best practice forward? |
0 | How can I use one keycode key as toggle switch for two cameras? using System using UnityEngine using UnityEngine.UI using Cinemachine public class CameraSwitch MonoBehaviour public CinemachineVirtualCamera vcam public CinemachineFreeLook fcam private void Update() if(Input.GetKeyDown(KeyCode.V)) fcam.enabled false vcam.enabled true When pressing on the V key it's switching between the cameras. I want that if I will press on the V key again it will switch between the two camera back fcam to be true and vcam to be false and so on each time pressing on the V key to switch between the cameras. |
0 | Combining mesh on the fly without using gameObject I procedurally generate chunks and use the marching cube algorithm to create meshes in 3D. At first, I just created a gameObject for each cube (of course, I knew it was not optimized, but I wanted to see if the algorithm worked). For now I stock all gamesObject in child of "blocks" but it would be much more optimized to directly merge the meshes between them and only create a single gameObject. However, i did not find any way to directly merge the meshes between them. So my question is is there a way to directly merge meshes between them without having to use gameObject? (don't worry about texturing) Here's the code public static GameObject GenerateChunk(int ,, map, int chunkSize, Vector3 chunkPosition) GameObject blocks new GameObject("BlockList") GameObject newMesh int cubeVertices new int 8 create each mesh in a gameObject as child of "blocks" for (int x 0 x lt chunkSize x ) for (int z 0 z lt chunkSize z ) for (int y 0 y lt chunkSize y ) define the vertices (cubeVertices) Vector3 cubePosition new Vector3(chunkPosition.x x, chunkPosition.y y, chunkPosition.z z) newMesh GenerateCube(cubePosition, cubeVertices) if (newMesh ! null) newMesh.transform.parent blocks.transform combine every children of "blocks" and delete them MeshFilter filters blocks.GetComponentsInChildren lt MeshFilter gt () List lt CombineInstance gt combine new List lt CombineInstance gt () for (int i 0 i lt filters.Length i ) if (filters i .sharedMesh null) continue for (int j 0 j lt filters i .sharedMesh.subMeshCount j ) CombineInstance ci new CombineInstance mesh filters i .sharedMesh, subMeshIndex j, transform filters i .transform.localToWorldMatrix combine.Add(ci) Destroy(filters i .gameObject) create the chunk and set the final mesh with the CombineMeshes function GameObject chunk new GameObject("Chunk", typeof(MeshFilter), typeof(MeshRenderer)) chunk.GetComponent lt MeshFilter gt ().mesh.CombineMeshes(combine.ToArray(), true, true) Destroy(blocks) return chunk |
0 | Why do I see " lt " and " gt " in Unity C code? I copied Unity code from a website and now it contains stuff like amp amp lt T amp amp gt which my IDE flags as an error. It looks like the intended text has been corrupted somehow. What is this supposed to be, and how can I correct it? public class Tree amp lt T amp gt public T Data get set public IEnumerable amp lt Tree amp lt T amp gt amp gt Childs get set public bool Opened get set public Tree() Childs Enumerable.Empty amp lt Tree amp lt T amp gt amp gt () Opened true |
0 | Internet Access is always set to required in unity android player settings I am using unity 2019.4.2f1, I want to remove the internet access permission from the final android manifest file created by unity but, because this option is locked I am not able to remove the permission. Let me know if there is any workaround to do so or disable this option somehow. |
0 | Approximately circular range of motion on a square tile grid I've been working on a grid based tactics style game to learn the ropes of Unity. I have an issue with movement range for a player unit. Let's say the units move range is 3 spaces.. If I set up each grid tile with 4 neighbours (up down left right), I get this movement range If I give each tile diagonal neighbours too 8 in total, I get this What I'm actually looking for is what you'd see in these type of games traditionally, like this Here is the code that finds the unit move range list, starting at tile (5, 5). It adds the initial tile node and its neighbours to the movelist, then works outward looping through all their neighbours. It's based off a youtube tutorial. public HashSet lt Node gt getUnitMovementOptions() float , cost new float mapSizeX, mapSizeY HashSet lt Node gt moveList new HashSet lt Node gt () HashSet lt Node gt tempMoveList new HashSet lt Node gt () HashSet lt Node gt finalMoveList new HashSet lt Node gt () int moveSpeed 3 Node unitStartNode graph 5, 5 finalMoveList.Add(unitStartNode) Initial costs for the neighbouring nodes foreach (Node n in unitStartNode.neighbours) cost n.x, n.y costToEnterTile(n.x, n.y, unitStartNode.x, unitStartNode.y) if (moveSpeed cost n.x, n.y gt 0) moveList.Add(n) finalMoveList.UnionWith(moveList) while (moveList.Count ! 0) foreach (Node n in moveList) foreach (Node neighbour in n.neighbours) if (!finalMoveList.Contains(neighbour)) cost neighbour.x, neighbour.y costToEnterTile(neighbour.x, neighbour.y, n.x, n.y) cost n.x, n.y if (moveSpeed cost neighbour.x, neighbour.y gt 0) tempMoveList.Add(neighbour) moveList tempMoveList finalMoveList.UnionWith(moveList) tempMoveList new HashSet lt Node gt () Debug.Log( quot Total move spaces for this unit is quot finalMoveList.Count) return finalMoveList Here is the costToEnterTile function public float costToEnterTile(int targetX, int targetY, int sourceX, int sourceY) Tile t tileTypes tiles targetX, targetY get current tile type float cost t.movementCost diagonal if (sourceX ! targetX amp amp sourceY ! targetY) cost 0.3f return cost If I tamper with the cost value in here, I can get different results in the movement range overall shape, but it's a bit hit and miss depending on the movement range. Can anyone offer insights in to what path I need to head down to solve this? |
0 | can't make my unity character move so I'm starting with Unity , I followed the john lemon tutorial , and I wanted to apply what I learn on a model on my own coming from blender. Everythings works , animation , rotation , but not translation . For some reasons my character doesn't move at all . It might have to do something with root motion since I have apply root motion in grey with written just after "handled by script" . Not sure what to do .. I found something about character in place, I think I'm in this case but I'm not sure how to use it in my script .. https docs.unity3d.com Manual ScriptingRootMotion.html If you ask I'll give you my project . EDIT ok so I made some advances void OnAnimatorMove() m Rigidbody.MovePosition(m Rigidbody.position m Movement m Animator.deltaPosition.magnitude 10000) m Rigidbody.MoveRotation(m Rotation) Debug.Log("m Animator.deltaPosition.magnitude " m Animator.deltaPosition.magnitude) m Animator.deltaPosition.magnitude is actually always equal to 0 , explaining why my charachter doesn't translate but why is it always equal to zero ? |
0 | Hide "No custom tool available" window I have this annoying window in the bottom right of the scene view. From the manual, it seems like I opened it by clicking on the wrench amp scribe button next to the movement buttons. How do I make it do away now? Restarting doesn't make a difference, neither does creating a brand new project. The documentation say this appears it I've clicked on the tools icon and there aren't any custom tools (which I'm sure I have done). Surely is should vanish after a while though. |
0 | Unity development build not connecting to profiler my development build( with auto connect profiler checked ) is not working. The build runs correctly but no data is displayed in the profiler window. In the console, it says failed to connect. |
0 | How can i press the key, show the text and choose if i want to take the item? It's working fine right now, showing the text and then press the key and it takes the item but, i want something like resident evil, the text is not showing until you press acction button. How can i do that? The key script var TheKey GameObject private var playerNextToKey false var showMessage boolean false var nearKey boolean false var hasCollided boolean false var labelText String "" function OnGUI() if (hasCollided true) GUI.Box(Rect(140,Screen.height 50,Screen.width 300,120),(labelText)) function Update () if (Input.GetKeyDown(KeyCode.E) amp amp playerNextToKey true) TheKey.active false function OnTriggerEnter (theCollider Collider) if (theCollider.tag "Player") nearKey true playerNextToKey true hasCollided true labelText " Vas a coger la llave?" function OnTriggerExit (theCollider Collider) if (theCollider.tag "Player") nearKey false playerNextToKey false hasCollided false |
0 | Unity Rotations Not Following Local Nor Global Axis? In the gif below, you can see that rotating on X moves all 3 axis including the X axis. It's possible it's rotating on the global X rather than local X (hard to tell). But Y looks more like it's rotating on global Z and Z is quite clearly rotating on local Z. What is going on? Why is there no consistency? |
0 | The name FB' does not exist in the current context I am trying to allow the user to share the final game score on their FaceBook timeline. I am following FaceBook tutorial and examples. When I try to download and import the FaceBook SDK package (7.11 2.0) in Unity (2017.3) I get the error error CD1704 An assembly with the same name 'FaceBook.Unity.Settings' has already been imported. Consider removing one of the references or sign the assembly Library FacebookSDK FaceBook.Unity.Settings.dll (Location of the symbol related to previous error) I read on other posts that the latest version of Unity may have the Facebook SDK already integrated, and will not require importing the package manually. I therefore removed the from my project. The error disappear, but when I try to initialize the Facebook SDK for Unity using the code below, I get the error The name FB' does not exist in the current context using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using Facebook.Unity public class ShareOnFaceBook MonoBehaviour Use this for initialization void Awake () if (!FB.IsInitialized) Initialize the Facebook SDK FB.Init(InitCallback, OnHideUnity) else Already initialized, signal an app activation App Event FB.ActivateApp() |
0 | How can one replicate the 'Quake Disruptor' of Wipeout XL 2097? Following my previous question, I am wondering how one can achieve the same effect under Unity? The effect in action https youtu.be kzmmLeCwL0g?t 790 Description of the effect When you fire the Quake Disruptor weapon, it creates a sine wave that mimics an earth quake, it happens over the next track sections forward to the player ship as you can see on the small video. This results in instant damage and slowdown to the ships that are caught in the quake. Technical challenges Deforming the mesh The function for generating a quake like wave to apply to each section of the track mesh is easy, e.g. a Gaussian filter will probably be good enough https www.desmos.com calculator goasdepcmv Applying the deformation to mesh This is where it starts to get trickier, a track is made out of sections that have few faces, each face being nothing more than a quad. Here you can see three sections and their faces (wall, track, track, wall) The challenge in here is how to apply the deformation and yet being able to check collisions against the track (remember that we can't use a mesh collider since it'll be updated in real time). I first thought that subdividing the mesh using tessellation would be needed to apply smooth deformations, hence my previous question. However, if you look closely at the video they simply move either edge of faces according to where they're against the 'quake' function being applied to the track mesh. Here's a link to a video with the best quality, around 13 mins 10 secs https archive.org details PSX Longplay 243 Wipeout 2097 We're getting closer but we still need to be able to check for collisions. Being able to still collide against the track This is the big question mark, since we cannot update a mesh collider in real time as it's a CPU hog, I really have no idea on how to address this part of the problem. This also leads to another problem, since we cannot use a mesh collider, how are physics are going to be handled, by writing a physics system from scratch ? Question How can such effect be achieved under Unity, if possible at all? PS You will want to remember that the PS1 had a 33Mhz CPU and certainly no mesh collider like the one we can find in Unity, yet they achieved to do it. For sure there is a trick involved but I couldn't figure it out. |
0 | How to create HDR and bloom in Unity3D? Unity3D's reference describes the HDR Bloom as Using HDR allows for much more control in post processing. LDR bloom has an unfortunate side effect of blurring many areas of a scene even if their pixel intensity is less than 1.0. By using HDR it is possible to only bloom areas where the intensity is greater than one. My question is how to achieve it in a surface shader? I have tried to output both the Albedo and Emission greater than 1, but still when I set the Threshold of Bloom equal to or greater than 1, no visible effect can be seen. The relevant part of shader snippet is float rim saturate(dot(normalize(IN.viewDir), o.Normal)) if (rim gt 0.98) o.Emission 1.5 or any large value Which basically outputs a bright white circle when view angle and normal are at almost same angle, and I want to enhance it with HDR. But outputting a value greater than 1 is not being registered and setting the threshold almost equal to 1 (0.98 or above) creates the Bloom on areas other than the bright white spot, which is not what is needed. I have tried to output extremely large values of Emission and have also tried output Albedo 1. Please tell what I am doing wrong or missing. I think I have not been able to figure out what is the meaning of pixel intensity 1 and what settings does this translate to. |
0 | Imposters in Unity How to set which color is used as 'transparent' in the RenderTexture? I'm still working at making imposters for my Unity scenes. Here I am attempting to make a large block of stadium seating, using the one seat mesh as shown. I'll try to explain in full what Ive done so far Imported 3d mesh of seat Created RenderTexture 'seat' (default format R8G8B8A8 UNORM) Added new Orthographic camera in front of seat. (settings Clear Flags Solid Color TargetTexture 'seat' Created some quads and aligned them so I can see the textured side. Gave the quads a new material 'seat'. I've gone through many of the settings in the Material and other places changed many things here and there such as 'transparent' or 'cutout' and lots of the other settings but cannot get rid of the magenta color in the seating textures I created. Also tried making that color alpha 0 but it had no effect. And tried various colors as transparent (magenta, white, black). Am I doing this completely wrong? Hopefully I am just missing some small setting. Ideally somewhere I can just set the magenta color to mean transparent pixels. Really do need help here honestly have been trying very hard to achieve this alone but not getting anywhere fast. |
0 | How do I determine the rotation of a Tile using Tilemap in Unity 2d? I want to know the rotation of the tile in C in order to do some logic on another object that is sitting on the tile. The rotation matters for the logic. I don't see anything except GetTileData in the doc, but that doesn't actually seem to "Get" the tile data. I could cast to Tile but not all tiles are Tile. Alternatively, I think I can get the rotation if I can get the GameObject for the tile but I have no idea how to do that either from a BaseTile. Anyone have any suggestions? Maybe I'm trying to do this wrong and I should make different tiles for each orientation or extend BaseTile or some other solution instead of trying to determine rotation. Any help or ideas would be greatly appreciated! Additional info When I inspect around in the Unity editor I see that the rotation is stored in Z in something called "Grid Selection" but I can't find a programmatic way of accessing that. |
0 | World rotation independent mouselook Preface I am terrible at using quaternions right. I wanted to create a world rotation independent mouselook script. That is, no matter the 'down' for the camera, the mouselook should feel natural to the player in relation to what is displayed on screen. I now have the following script running on update in my camera Quaternion worldRot Quaternion.LookRotation(Vector3.forward, Vector3.left) xRot rotSpeed Input.GetAxis("Mouse Y") yRot rotSpeed Input.GetAxis("Mouse X") transform.rotation Quaternion.AngleAxis(yRot, worldRot Vector3.up) Quaternion.AngleAxis(xRot, worldRot Vector3.right) worldRot Unsurprisingly, it tumbles all over the place. I think the issue is in basing the rotation angles on the worldRot (World rotation as seen by the camera), while then also rotating the whole by worldRot. I cannot get my head around how else to go about it, though... My initial alternative was to use transform.rotation Quaternion.AngleAxis(yRot, Vector3.up) Quaternion.AngleAxis(xRot, Vector3.right) worldRot But this anchors the mouse's movements to the world rather than the camera, which as described above isn't desired either. Based on this (or, perhaps, in a completely different way), how do I make a mouselook system with an arbitrary down vector? |
0 | Is there a way to view all colliders in a unity project at runtime (after the game have been deployed)? I'm have created a small Unity project but physics has weird behavior (bug). Unfortunately it only happens on some specific hardware (after build), not on development machine. I don't know what is the reason it's probably due to different framerate. Viewing all object and their colliders would probably help me a lot. Is there a possibility in Unity to view all colliders in the game at run time (some kind of debug mode). Something similar as Game tab view in Unity with Gizmos option enabled, but for all objects ? |
0 | How do I draw a context menu next to my object? I want to show a menu next to an item in an inventory. This is what I try to rebuild I do this by placing a canvas in 3D world space next to the inventory As I don't want the menu to be rotated, I rotated the menu the opposite X value as the camera. The camera has an X rotation of 11, so I rotate the menu by 11 to make it look straight Since I don't want the menu to get stuck in the case, I move it closer to the camera One can see that the menu is now offset to the left and to the top because of the camera perspective. How could I offset the menu in such a way that it still aligns with the right top corner of the item? Thank you! |
0 | Unable to get accurate y position on terrain to spawn object all I am trying to spawn some crabbies and can't seem to get an accurate y height to spawn. I have a terrain created with GAIA Pro 2 and have tried a few things to get an accurate y value. When trying to get the y from the terrain data I keep getting a 0 for example newCrabStartPos.y mainIslandTerrain.terrainData.GetHeight((int) rayPosition.x, (int) rayPosition.z) getYPositionFromRay(rayPosition) 2.5f Here is my current implimintation IEnumerator SpawnCrab() while(spawnedCrabbies lt waveCount) GameObject instance Instantiate(Resources.Load( quot Whakin Crab quot , typeof(GameObject))) as GameObject instance.transform.position SetStartPosition() spawnedCrabbies 1 yield return new WaitForSeconds(spawnRate) Vector3 SetStartPosition() float minDistanceAwayFromGoal 10f float maxDistanceAwayFromGoal 50f float xpos Random.Range( 1f, 1f) lt 0 ? Random.Range( minDistanceAwayFromGoal, maxDistanceAwayFromGoal) Random.Range(minDistanceAwayFromGoal, maxDistanceAwayFromGoal) float zpos Random.Range( 1f, 1f) lt 0 ? Random.Range( minDistanceAwayFromGoal, maxDistanceAwayFromGoal) Random.Range(minDistanceAwayFromGoal, maxDistanceAwayFromGoal) Vector3 newpos new Vector3(xpos, 0, zpos) Vector3 rayPosition new Vector3(xpos, 100, zpos) Vector3 newCrabStartPos new Vector3(newpos.x, 15, newpos.z) newCrabStartPos newCrabStartPos goal.transform.position newCrabStartPos.y getTerrainDistanceFromRay(rayPosition) mainIslandTerrain.terrainData.GetHeight((int) xpos, (int) zpos) getYPositionFromRay(rayPosition) 2.5f return newCrabStartPos float getTerrainDistanceFromRay(Vector3 drawFromPosition) RaycastHit hit new RaycastHit() if (Physics.Raycast(drawFromPosition, Vector3.down, out hit, 100)) return (100 hit.distance) collider.gameObject.transform.position.y return 0 |
0 | Preparing a 2D character to export from Blender to Unity? I'm an animator for a game currently, and I don't have Unity (can't download due to too much gigs coupled with slow internet,) but the game designer told me I can use Blender to export animations into Unity. I asked if I needed to prepare multiple files to export, and they told me that I could just have one file with all the animations in it. The game, as stated in the title, is 2D. My problem now is, how do I turn a rig into an actual character with different animations under it? (Right now I only have an 'idle' animation, but need to make running, jumping, walking, etc.) I mean how do I save this 'idle' animation and work on another animation without overwriting the previously finished animation(s)? Thank you much |
0 | accelerometer not working unity why is the cube moving when I use a controller, but not with the accelerometer? void Update () text.text "X " Input.acceleration.x " Z " Input.acceleration.z transform.position new Vector3(10 Input.acceleration.y, 0, 10 Input.acceleration.z) transform.Translate(Input.acceleration.x, 0, Input.acceleration.z) transform.position new Vector3(10 Input.GetAxis("Horizontal"), 0, 10 Input.GetAxis("Vertical")) transform.Translate(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) (I'm on a Xperia Z3 compact by the way) |
0 | How can I implement UI in Unity using Chromium? I'm looking for an alternative to UI Builder. Ideally I'd like to have basically a Chromium instance atop Unity3D which would have its JS calls somehow land in the C (maybe in the quot Update quot loop it listens to a constant stream of potential calls and the parameters will correspond to function names in my Unity code, I don't know) here's what I found which doesn't quite live up to my expectations Unity WebView doesn't support Windows. 3D WebView for Windows and macOS (Web Browser) requires the UI to be served on an actual live URL and for Unity to access it via that URL and for all interaction to be handled via API, impractical or slow at best. PowerUI HTML CSS is interesting, but was made in 2011. The documentation is all gone. the support for css feature is probably incredibly slim. Embedded Browser looks pretty good, but I'm unsure that it could be bent into a UI system. I want it to frame my game, not to cover it. Coherent Gameface looks probably the best, although the CSS implementation seems a tad lackluster. Also this project was started in 2012, it's probably carrying very old, very slow code. This Unity forum thread may be relevant. Chromium Embedded Framework was a tool used by some assets on the asset store to create chromium UI but it has been removed. If not using these assets, how can I implement my idea of using Chromium as my UI layer? |
0 | Why does Unity3D crash in VirtualBox? I'm running Unity3D in a virtual instance of Windows, using the Virtual Box software on Linux. I have guest additions installed with DirectX support. I've tried using Windows XP SP3 32 bit, and Windows 7 64bit. My host is Ubuntu 12.04 64bit. I installed and registered Unity on both. It loads up fine, and then crashes my entire VirtualBox instance (equivalent of a computer shutting off with no warning). |
0 | How to create a solid cross scene game manager in the editor of unity? I have been checking dozens of known 'solutions' for how to create a game manager in Unity, but none leave me satisfied. I know I can create a singleton GameManager.Instance() that would have data to persist across multiple scenes, but it doesn't show up in the editor unless I assign it to a game object. The problem is, this game object would then be destroyed upon loading a new scene except if I use DontDestroyOnLoad(). However, when I use DontDestroyOnLoad(), and I open up a new scene in the editor, this GameManager Object doesn't exist in the new scene. The DontDestroyOnLoad() method assumes that the program entry point will always be the main first scene, which is often not the case when working in the editor. This isn't great. Example When I have events within scene2 (say a button or something), I cannot reference the gameobjects in scene1 in the Unity Editor (most importantly, the game manager). Instead, I have to first attach a settings.cs script to my UI Button GameObject. When pressed, the Button will then call a function from the settings.cs void ChangeInput() GameManager.Instance().ChangeInput() . This feels quite clunky because the Button Element cannot reference the GameManager directly, since the Button is scene specific but the gamemanager is not. Is there a proper solution for issues like this? |
0 | Architecture for extremely modular game? I'm developing a modular game in Unity 5.6. Each module has very little overlap in assets with the others. I'm concerned about having a bloated repository after a few months of development, and since I'm using Bitbucket (a free account) I'm limited in my repo size, but not in my number of repos. So instead of having one huge folder for my game I'm considering having a launcher project and scene that loads builds from a folder in Assets. Each module would be its own project, and I would just drop its build into the launcher's folder. My question is, is this a reasonable approach to building a highly modular game? Hopefully I'll be continuing development for quite a while, and I want to make sure the project is as lightweight and extendable as possible. Or am I overthinking this, and should I just use one big repo? |
0 | Avoiding singletons for puzzle system Say for instance I have a puzzle with 3 switches that need to be in some configuration (say all on) in one room, that opens a door in another, with a load screen separating, so I can't link the switches directly to the door. My first thought was to create a singleton that stored the state of each "solution element" which in this case is the switches, but could be a correctly turned knob, ect. then a given "Puzzle Gate" like a locked door would check the required solution elements to decide it's own state, but I'm hesitant to use singletons for all of the commonly given reasons. What alternatives do I have to singletons that would give me the same or similar control? |
0 | Duplicating and adding sprites at runtime in Unity I am trying to create a 2D game in Unity in which objects keep falling from top and the player has to dodge them. Suppose I have created a sprite which serves as a single enemy that the player has to dodge.Now I have to create multiple such sprites at runtime so that they can keep on spawning from random positions.Despite searching on the net for quite some time i could not find a clear answer. I am just a newbie and I am just starting to learn game development in Unity so answers in detail will be very helpful. Thanks in Advance. |
0 | Unity3d How to use controller joystick to look around? I try to use my xbox controller as input device for a game targeted to run on windows. However the documentation fails to explain how to set it up. E.g. how can I use the right stick from my xbox controller to look around, like in any 3D game? Even such a common task is not documented. I found a very old wiki entry where the xbox controller is briefly described, I was able to find out that the Y Axis of the right analog is called 5th axis (Joysticks) and the X Axis is called 4th axis (Joysticks). I post the images below, in case the link get's dead. Linux Note wired controllers only support axises for the d pad, while the wireless controller only supports buttons for the d pad, refer to the table above for the wireless controller configuration. I figured out that the name of a control is responsible for the action which the button, stick, key, pedal etc. does. But it is not documented how the control has to be named for looking around vertically or horizontaly like you can do in an 3D game to look around with the camera by using the right joystick (e.g. witcher 3) How can I control the camera by using the right joystick? |
0 | My bullet keeps going up So I have a bullet script that fires a bullet straight in the Y direction that gets called as the bullet is instantiated. The plan is to always shoot in the same direction, straight in the Y, but to just rotate the bullet upon instantiation so that the straight is the right kind of straight if that makes sense? What i really want to know i think is how to work out the value for the 3rd property of the instantiate based on the key pressed before the fire, what makes it worse is that i dont even know how to create a rotation variable. Instantiate(Resources.Load("P1Bullet"), transform.position, transform.rotation) this is how i move my bullet in the bulletmove script void Update () Vector3 pos transform.position Vector3 vel new Vector3(0, speed Time.deltaTime, 0) pos pos transform.rotation vel transform.position pos |
0 | Can a material be created from a gameobject in Unity? I am trying to manually create snowflakes in unity, after I created a snowflake in the unity scene, is it possible to create a material out of it? |
0 | Unity change default settings for standard components How can I change the default settings for the standard components or is this even possible? E.g. setting the default font size for a text component so that each new text component I add will have the same font size? |
0 | Relative vertical alignment of 3 Texts on Canvas This is a menu that appears if I press Enter on the RE4 inventory if an item is selected. I have drawn a thin red rectangle around it And here is a video that shows some of the menu's effects. I am familiar with a simple text canvas. I understand that I need to make each line a separate "Text" object so that I can scroll up and down through them. Here is what I have so far The problem that I'm facing now is that the Canvas will be scaled at runtime. I don't work with fixed values. This is a problem since I don't see how I could easily make it so that each TextLine object fills 33,3 of the canvas. Am I right to assume that I can only solve this by making a scripts that holds a reference to each TextLine object and which then calculates their position when the scale of Canvas is known? Or is there any easier solution? Thank you! |
0 | Need advice concerning the creation of open world game in Unity 3D I just wanted to ask for advice those being an expert in Unity 3d and overall in game industry about how it is possible to create an open world game by means of Unity 3D, that is, I already tried to combine several tiles of terrains, 4 to be exact, and their respective size is 500x500. However, once I started to add the fifth terrain to those terrains, Unity stopped working. Moreover, another problem that I faced was with light mapping in Unity, that is, the more terrain I add to the scene the more it is difficult to bake the light mapping. The question is if I am doing correctly by adding terrains to each other and how open world games are actually created. Yes, I heard of chunk loading but is it possible to code it on my own without using ready plugins. Lastly, Is it possible to combine tiles of terrains just manually without using any tools like Terrain Slicing kit or Gaia please I really need your help Thank you for your attention))). |
0 | Accelerometer input for flying game I'm trying to create an infinite flying game where the gameobject (a plane) keeps moving forward and at a particular height throughout the game. I want to be able to roll and pitch the plane but not move it up down. I added a rigid body to the plane and selected "y" position constrain. However the plane doesn't stay in the 'y' position but starts move up or down. I just have a script that translates the plane in the z direction. Not sure how to implement the mobile input and keep at the same "y" position throughout. Update Here is the code for the plane. Its very basic as I'm not sure how to use the accelerometer public class Player MonoBehaviour public float speed 1.0f void Update () float tempx Input.acceleration.x float tempy Input.acceleration.y float tempz Input.acceleration.z transform.Translate(0, 0, 10) move forward in z transform.Rotate( 0, tempy speed, tempz speed) As for the freezing of the 'y' position, I'm just selecting the y constraint available in the inspector that comes along with the rigidbody. |
0 | Unity Performance Recycling Pooled Objects OR Re Instantiating? Re using pre instantiated objects in a pool. Destroying then re instantiating objects in a pool. Both pools are limited. When creating loads of objects which is better for performance? |
0 | Proper way to calculate x and y components of two 2D vectors I'm having some issues on resolving this with the current set of Vector2 methods. Could you help me to define a universal solution? The idea is to move a spaceship to another point using only relative to (A) lateral and forward movements. Given two points A(1, 1) and B(2, 3) A has a known angle with the y axis alpha How to calculate the x dist and y dist relative distances in order to move A to B? |
0 | How to display a GUI text at run time in unity? I'd like to display a GUI text at run time in my game for a second, so I want to know if it's possible to add or remove a GUI label to the scene at run time? |
0 | Unity Small holes of light seems to go through my blender mesh So, I am currently working on a low poly terrain in Blender which will be flat shaded in Unity. It all works great, however I am working on a cave for the terrain, and I seem to be getting these small odd light artifacts I have tried to highlight them with the read circles. If you look carefully, you can see the small holes. The odd thing is, the entire mesh should be completely solid. Here's a screenshot of the cave entrance in blender (which is the floor I'm looking at in Unity) All normals of the faces seems to be facing correctly, and mesh has simply been modelled by extruding edges from existing parts of the mesh, so there shouldn't actually be any actual holes. Does anyone have any experince with this kind of problem? |
0 | How can I call two functions in a sequence with onclick? I'm learning Unity. I have two functions, one that transitions to a new scene and the other one is the button animation. I add both functions to the onclick of a given button. I assume it calls both functions at the same time and executes the transition without running the animation. I want the button to run the animation first (I'm using DOTWEEN) and once it's done to execute the transition. |
0 | Split group of enemies? . . In my script, enemy goes to dead point and if player closet to him he attacking player. When I started making wave of enemies I notes that all of them goes to player. Now, I need to add something making enemy avoid player in case there are 4 enemy around him and goes to dead point. What I did is, I attached every player script "enemyAround" to count any enemy around player. public int enemies 0 void OnTriggerEnter(Collider other) enemies void OnTriggerExit(Collider other) enemies But I couldn't figure how to make enemy read it ?. If Enemy select player to attack him, He reads or knows How many enemy around the selected player. enemy script private Animator enemy anim private NavMeshAgent mAgent private GameObject player public GameObject dead point public int farPoint, dead point number, player number public float dist public bool enemt run, enemy atack false public bool near private enemyAround arounds public int enemy around player Use this for initialization void Start() mAgent GetComponent lt NavMeshAgent gt () enemy anim GetComponent lt Animator gt () player GameObject.FindGameObjectsWithTag("Player") dead point GameObject.FindGameObjectsWithTag("dead point") 3 points enemy dirction() void Update() count enemies around player enemy around player selected player for (int i 1 i lt player.Length i ) if (Vector3.Distance(transform.position, player i .transform.position) lt Vector3.Distance(transform.position, player player number .transform.position)) player number i dead point number dead point.Length dist Vector3.Distance(transform.position, player player number .transform.position) if (dist lt 5) near true else near false if (player ! null amp amp dist lt 5.1f) mAgent.destination player player number .transform.position if (dist lt 1.2f) enemy atack true else enemy atack false else if (dead point number gt 0) mAgent.destination dead point farPoint .transform.position else mAgent.destination player player number .transform.position if (mAgent.remainingDistance lt 1.5f) enemy atack true else enemy atack false enemt run true mAgent.speed 1.0f enemy anim.SetBool("run", enemt run) enemy anim.SetBool("attack", enemy atack) end update choose any deat point. void enemy dirction() if (dead point number gt 0) farPoint Random.Range(0, dead point.Length) mAgent.destination dead point farPoint .transform.position else |
0 | Animation imported from Blender into Unity via FBX doesn't play? I started building this model in Blender and gave it a simple animation that rotates the board about the axel. ...I exported it as FBX and imported it into Unity. I can see the animation is stored in the file when I import, but I can't find an animation file after I drop it in the scene, and there is no controller for the Animator controller it generated, either. I can watch the animation play in the FBX preview thumbnail but nowhere else. How can I get my animation working? |
0 | IConvertGameObjectToEntity interface on Unity ECS Was working on ECS and following the tutorials by Mike Geig in Unite Copenhagen on YouTube(https youtu.be BNMrevfB6Q0), and understood that unity automatically converts transforms, mesh renderers and things like that to ECS, the IConvertGameObjectToEntity interface converts entities that I want specifically for my game. But, while following his tutorial exactly as he did it, the entities that I have on my game do not have colliders in them, but is seen in his demo, how do I resolve that? EDIT I've Instantiated an entity, and it works fine, but then implementing the void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) from the IConvertGameObjectToEntity interface, I just have an entity, and only the mesh is visible, and an empty Component data that I've assigned on the Convert() method is available, I don't have a collider as it is on the prefab. Here is my Spawn Entity Code void Start () manager World.Active.EntityManager ObjectEntityPrefab GameObjectConversionUtility.ConvertGameObjectHierarchy(ObjectPrefab, World.Active) for (int i 0 i lt 100 i ) SpawnTheObject() private void SpawnTheObject() Entity object manager.Instantiate(ObjectEntityPrefab) manager.SetComponentData(object, new Translation Value transform.position ) manager.SetComponentData(object, new Rotation Value Quaternion.identity ) Here is The code attached to The Object public class AsteroidLifeECS MonoBehaviour, IConvertGameObjectToEntity public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) MoveSpeed moveSpeed new MoveSpeed Value MovementSpeed A component data that has only one float called Value dstManager.AddComponentData(entity, moveSpeed) RotateSpeed rotateSpeed new RotateSpeed Value RotationSpeed A component data that has only one float called Value dstManager.AddComponentData(entity, rotateSpeed) Health health new Health Value Health A component data that has only one float called Value dstManager.AddComponentData(entity, health) |
0 | Unity 2D Dealing damage when character is crushed between two solid objects Whats the best approach to dealing damage to a player when they get stuck between two solid objects? For instance, I'm trying to make moving platforms that the player can ordinarily touch. It's only when the player is caught in between the moving platform and the ceiling, for example, that damage is dealt or the player dies. So, what would be the best way to approach this? Thanks in advance! |
0 | Relative vertical alignment of 3 Texts on Canvas This is a menu that appears if I press Enter on the RE4 inventory if an item is selected. I have drawn a thin red rectangle around it And here is a video that shows some of the menu's effects. I am familiar with a simple text canvas. I understand that I need to make each line a separate "Text" object so that I can scroll up and down through them. Here is what I have so far The problem that I'm facing now is that the Canvas will be scaled at runtime. I don't work with fixed values. This is a problem since I don't see how I could easily make it so that each TextLine object fills 33,3 of the canvas. Am I right to assume that I can only solve this by making a scripts that holds a reference to each TextLine object and which then calculates their position when the scale of Canvas is known? Or is there any easier solution? Thank you! |
0 | Horizontal scrollview only I am using unity's scrollview. I want to disable the vertical scrollbar and i want the viewport to resize vertically depending on the content. Too confusing to explain with word so i have created the example picture below How do i achieve this properly ? |
0 | Unity can i make children of a moving platform also work as moving platforms? I have a moving platform that is a kinematic body, moving by a script, which is working as expected. I tried to parent it to another kinematic body, and make the child also function as a moving platform (the script only moves the parent), but it seems that the friction is ignored for the child object, and the carried object slips behind it and falls down when the child platform moves. The child platform is the same physical material as the parent. Is there any way i can make the child's friction work too, while having the script only move the parent? This is important, because in my real application the child moves and rotates inside a couple nested levels of transformations (basically the fork teeth of a fork truck). here is a simple abstraction of my question https youtu.be U854IcS96 Y Thanks! |
0 | Tab between input fields I am new to working with Unity3d, I need to navigate between several inputField, for this I have looked at the solution that is in tab between input fields, but always the FindSelectableOnUp() or FindSelectableOnDown() returns null, so my next is always null and always ends in next Selectable.allSelectables 0 |
0 | Controlling noise density I'm trying to fake terrain blending by using an opacity mask on my road mesh to reveal the grass underneath. I'm currently multiplying some Perlin noise by a Rectangle node displaying my texture at 80 width which is giving me the following Obviously this doesn't look great for reasons that should be apparent. The blotches are unnaturally spaced and they abruptly end with a sharp line at the end of the texture. What I would like to do is generate noise that looks more along the lines of this Is there a way to apply some sort of gradient to my noise to achieve this? I know I can just use the texture itself but I would like to be able to adjust properties like the extent of the noise during runtime. |
0 | Canvas not scaling to screen size So I have a very simple scene set up with just a camera, a game object called TestGrid with a grid script, and then a canvas. I have a TextMeshPro prefab that I instantiate to fill the 10 x 20 grid with cells. If I build and run the game, I see all the cells on my screen. However, in the editor play view, I can only see as many grid cell as would fit on startup. Making the game view smaller or larger will scale the ones already there, but everything that didn't fit initially is quot clipped quot out. The quot canvas quot is in the bottom left corner of the quot grid quot I'll share my code as well using System using System.Collections using System.Collections.Generic using TMPro using UnityEngine using UnityEngine.Diagnostics public class TestGrid MonoBehaviour private float cellSize 50.0f SerializeField private float width 0.0f SerializeField private float height 0.0f SerializeField private TextMeshProUGUI labelPrefab Start is called before the first frame update private void Start() if (labelPrefab null) Debug.LogError( quot You must set a label prefab. quot ) return GameObject canvas GameObject.Find( quot labelCanvas quot ) if (canvas null) Debug.Log( quot Unable to find canvas quot ) return This is just a 2D array of ints. Grid grid new Grid((int) width, (int) height) var canvasRect canvas.GetComponent lt RectTransform gt ().rect cellSize Math.Min((canvasRect.width width), (canvasRect.height height)) for (int x 0 x lt grid.Data.GetLength(0) x) for (int y 0 y lt grid.Data.GetLength(1) y) SpawnLabel(new Vector3(x, y, 0), canvas, grid.Data x, y .ToString()) TODO Replace this with LineRenderer Debug.DrawLine(GetWorldPosition(new Vector3(x, y)), GetWorldPosition(new Vector3(x, y 1)), Color.white, 100f) Debug.DrawLine(GetWorldPosition(new Vector3(x, y)), GetWorldPosition(new Vector3(x 1, y)), Color.white, 100f) Debug.DrawLine(GetWorldPosition(new Vector3(0f, height)), GetWorldPosition(new Vector3( width, height)), Color.white, 100f) Debug.DrawLine(GetWorldPosition(new Vector3( width, 0f)), GetWorldPosition(new Vector3( width, height)), Color.white, 100f) void Update() NYI private void SpawnLabel(Vector3 localPos, GameObject canvas, string text) float x localPos.x float y localPos.y var world GetWorldPosition(new Vector3(x, y, 0)) new Vector3( cellSize, cellSize) .5f var label Instantiate(labelPrefab, world, Quaternion.identity, canvas.transform) label.text text label.fontSize 100 label.autoSizeTextContainer true private Vector3 GetWorldPosition(Vector3 local) return local cellSize Additional images of environment I'm actually not too sure what is going on here, so here is everything I know I'm parenting my TextMeshPro prefab transform to the canvas transform, so that it scales properly My Canvas Scalar is set to reference resolution of 2560 x 1440, with a RPPU of 108 Canvas Scalar is also set to Scale With Screen Size Canvas Screen Space is set to Overlay I've also read the following links with no luck https stackoverflow.com questions 32347009 unity canvas does not fill screen https answers.unity.com questions 943190 ui panel not covering whole screen.html https answers.unity.com questions 1331722 ui scaling issues.html Expected Results No matter what the screen size is, I should see my full 10 x 20 grid of quot cells quot (in play view they're just 0's). Question If my canvas is supposed to scale with screen size, why is it that when I choose a cell size calculated from the canvas size, that it thinks the canvas is 2560 x 1440 when the screen size is clearly much smaller than that? Do I need to calculate with a different value? Must I dynamically resize everything I draw within the canvas? What's going on here? |
0 | In Unity, How to format Old RPCs into new "PunRPCs" In older unity versions you could simply used RPC. With newer verisons of Unity my code now doesn't work and it says that it needs to be transformed into "PunRPC" , Pun being "Photon Unity Networking." I am not sure how to reformat it to work with current unity versions. Can anyone shed light on this? My Code FXManager.cs 1 using UnityEngine 2 using System.Collections 3 4 public class FXManager MonoBehaviour 5 6 RPC 7 void SniperBulletFX( Vector3 startPos, Vector3 endPos ) 8 Debug.Log ("SniperBulletFX") 9 10 11 PlayerShooting.cs 1 using UnityEngine 2 using System.Collections 3 4 public class PlayerShooting MonoBehaviour 5 6 public float fireRate 0.5f 7 float cooldown 0 8 public float damage 25f 9 FXManager fxManager 10 11 void Start() 12 fxManager GameObject.FindObjectOfType lt FXManager gt () 13 14 if(fxManager null) 15 Debug.LogError("Couldn't find a FXManger.") 16 17 18 19 20 Update is called once per frame 21 void Update () 22 cooldown Time.deltaTime 23 24 if (Input.GetButton ("Fire1")) 25 Player wants to shoot...so. Shoot. 26 Fire () 27 28 29 30 void Fire() 31 32 if (cooldown gt 0) 33 return 34 35 36 Debug.Log ("Firing our gun") 37 38 Ray ray new Ray (Camera.main.transform.position, Camera.main.transform.forward) 39 Transform hitTransform 40 Vector3 hitPoint 41 42 hitTransform FindClosestHitObject (ray, out hitPoint) 43 44 if (hitTransform ! null) 45 Debug.Log ("We hit " hitTransform.name) 46 47 We could do a special effect at the hit location 48 DoRicochetEffectAt (hitPoint) 49 50 Health h hitTransform.GetComponent lt Health gt () 51 52 while (h null amp amp hitTransform.parent) 53 hitTransform hitTransform.parent 54 h hitTransform.GetComponent lt Health gt () 55 56 57 Once we reach here, hitTransform may not be the hitTransform we started with! 58 59 if (h ! null) 60 This next line is the equivalent of calling 61 h.takeDamage( damage) 62 Except more "networky" 63 PhotonView pv h.GetComponent lt PhotonView gt () 64 if (pv null) 65 Debug.LogError ("Freak out!") 66 else 67 h.GetComponent lt PhotonView gt ().RPC ("TakeDamage", PhotonTargets.AllBuffered, damage) 68 69 70 71 if (fxManager ! null) 72 fxManager.GetComponent lt PhotonView gt ().RPC ("SniperBulletFx", PhotonTargets.All, Camera.main.transform.position, hitPoint) 73 74 75 else 76 We didn't hit anything (except empty space), but let's do a visual FX anyway 77 if (fxManager ! null) 78 hitPoint Camera.main.transform.position (Camera.main.transform.forward 100f) 79 fxManager.GetComponent lt PhotonView gt ().RPC ("SniperBulletFx", PhotonTargets.All, Camera.main.transform.position, hitPoint) 80 81 82 83 cooldown fireRate 84 If anymore information is needed, please let me know, I would love to figure out how the new "PunRPC(Photon Unity Neworking)" works so I can use it in future projects. Edit This is the error I get "PhotonView with ID 2 has no method "SniperBulletFx" marked with the PunRPC or PunRPC(JS) property! Args Vector3, Vector3 UnityEngine.Debug LogError(Object)" |
0 | Unity 2d text not rendered properly in scene mode I am a beginner in Unity and trying to add a text box to my scene. I have done this before and was able to do it properly. Problem But recently I created a new project, added a text element to it, but text is not rendered properly in that text box. Anything I type in it is shown as boxes. Here is the screenshot for it. While text is shown properly in play mode. I also tried adding custom fonts in it but it didn't made any effect. What can be the cause for this. |
0 | Controlling Source Image From Script I am trying to make a health system where hearts display how much health you have. On each heart, I have an Image component. I am trying to control what source image the Image component uses from a script, but it is not letting me. I read the documentation for the Image component here and it has no sprite property. This is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UIElements public class HeartScript MonoBehaviour public GameObject heart1 public GameObject heart2 public GameObject heart3 public Sprite halfHeart public Sprite fullHeart public Sprite emptyHeart private double playerHealth 3 Update is called once per frame void Update() if(playerHealth 2.5) heart1.GetComponent lt Image gt ().image fullHeart heart2.GetComponent lt Image gt ().image fullHeart heart3.GetComponent lt Image gt ().image halfHeart else if(playerHealth 2) heart1.GetComponent lt Image gt ().image fullHeart heart2.GetComponent lt Image gt ().image fullHeart heart3.GetComponent lt Image gt ().image emptyHeart else if(playerHealth 1.5) heart3.GetComponent lt Image gt ().image emptyHeart heart2.GetComponent lt Image gt ().image halfHeart heart1.GetComponent lt Image gt ().image fullHeart else if(playerHealth 1) heart3.GetComponent lt Image gt ().image emptyHeart heart2.GetComponent lt Image gt ().image emptyHeart heart1.GetComponent lt Image gt ().image fullHeart else if(playerHealth .5) heart3.GetComponent lt Image gt ().image emptyHeart heart2.GetComponent lt Image gt ().image emptyHeart heart1.GetComponent lt Image gt ().image halfHeart else if(playerHealth 0) heart3.GetComponent lt Image gt ().image emptyHeart heart2.GetComponent lt Image gt ().image emptyHeart heart1.GetComponent lt Image gt ().image emptyHeart public void RemoveHealth() playerHealth playerHealth 0.5 How do I change the sprite the heart uses from a script? |
0 | How do i play mp3 files in Unity Standalone? I am making a game in Unity in which the player can select music files in their hard drive to use them in game. I use the WWW class to load the sound files, but this only works for OGG, WAV and Tracker files. I use the following code WWW www new WWW ("file " soundPath) while(!www.isDone) yield return 0 GetComponent lt AudioSource gt ().clip www.GetAudioClip(false, true) I want to play audio files in mp3 format, which is the most widely used format for music in general, but when i try to play them, this gets printed to the debug log Streaming of 'mp3' is not supported on this platform. How can i easily achieve mp3 playback on desktop? |
0 | Unexpected result when generating world with 2 perlin noises I try to generate a world with a temperature and an humidity noise to generate biome based on the y values of the two. I take the y values and round them on a 33 base for the humidity and 25 for the temperature then add the two to get 12 possibilities of biome. to test it I first tried generating a chunk by assining the sum of humidity and temperature to their y location. I was expecting to get multiple platform at different height (12 possibilities of height) but I instead got this even if it doesn't look like it, there are random patterns within the bigger layers. i don't understand why I got that result (which looks pretty sick not gonna lie). here is my script const int seed 50 const int FREQUENCE 100 const int AMPLITUDE 100 const int size 100 int BIOME DATA 0, 33, 66, 25, 58, 91, 50, 83, 116, 75, 108, 141 int temp VERT new int 100 100 int hum VERT new int 100 100 public int biome VALUE new int 100 100 void Start() generate the y values for the humidity vertices for (int x (int)transform.position.x, i 0 x lt size (int)transform.position.x x ) for (int z (int)transform.position.z z lt size (int)transform.position.z z ) float y Mathf.PerlinNoise((float)x seed FREQUENCE, (float)z FREQUENCE) AMPLITUDE y Mathf.Floor(y 33) 33 hum VERT i (int)y i generate the y values for the temperature vertices for (int x (int)transform.position.x, i 0 x lt size (int)transform.position.x x ) for (int z (int)transform.position.z z lt size (int)transform.position.z z ) float y Mathf.PerlinNoise((float)x seed FREQUENCE, (float)z FREQUENCE) AMPLITUDE y Mathf.Floor(y 25) 25 temp VERT i (int)y i assigne une valeur repr sentant un biome pour chaque vertex for(int i 0 i lt biome VALUE.Length i ) biome VALUE i System.Array.IndexOf(BIOME DATA, (hum VERT i temp VERT i )) biome VALUE i new Vector2(temp VERT i ,hum VERT i ) GenerateChunk(biome VALUE) void GenerateChunk(int Y VERTICES) Mesh meshy MeshRenderer meshRenderer GetComponent lt MeshRenderer gt () meshRenderer.sharedMaterial new Material(Shader.Find( quot Standard quot )) MeshFilter meshFilter gameObject.GetComponent lt MeshFilter gt () Vector3 VERTICES new Vector3 Y VERTICES.Length List lt Vector2 gt UV new List lt Vector2 gt () List lt int gt TRIANGLES new List lt int gt () List lt Vector3 gt NORMALS new List lt Vector3 gt () meshy new Mesh() cr ation des Vecteur for (int i 0, x 0 x lt size x ) for (int z 0 z lt size z ) VERTICES i new Vector3(x transform.position.x, BIOME DATA Y VERTICES i , z transform.position.z) i cr ation des normales for (int i 0 i lt VERTICES.Length i ) NORMALS.Add( Vector3.forward) cr ation des triangles for (int x 0 x lt size 1 x ) for (int z 0 z lt size 1 z ) int i size x z TRIANGLES.Add(i) TRIANGLES.Add(i 1) TRIANGLES.Add(i size) TRIANGLES.Add(i size 1) TRIANGLES.Add(i size) TRIANGLES.Add(i 1) cr ation des uv for (int i 0 i lt VERTICES.Length i ) UV.Add(new Vector2(VERTICES i .x, VERTICES i .z)) assignation des valeurs meshy.vertices VERTICES meshy.triangles TRIANGLES.ToArray() meshy.uv UV.ToArray() meshy.normals NORMALS.ToArray() meshFilter.mesh meshy |
0 | "Instantiate" function in Unity spawns enemy but it doesn't show up So, I'm making a top down shooter (2D) and I already made an enemy prefab. It walks to the player and damages it, and reacts to bullets physically until it eventually dies. The prefab itself is ok, because I can spawn it manually and it works as intended. The problem comes when I want to automate the spawn process with a script. So I made a script to do so, here it is using System.Collections using System.Collections.Generic using UnityEngine public class GameController MonoBehaviour public GameObject enemy private float spawnPositionX private float spawnPositionY Vector2 spawnVector Start is called before the first frame update void Start() SpawnEnemy() void SpawnEnemy() spawnPositionX Random.Range( 630f, 630f) spawnPositionY Random.Range( 340f, 340f) spawnVector new Vector2(spawnPositionX, spawnPositionY) Instantiate(enemy, spawnVector, Quaternion.identity) As you can see, it's nothing too complex. I just refer to a game object (which I linked by the way) and then create some variables that will hold the x and y positions in which the enemy will spawn at random. Then when I call the function, those positions get set and stored into a bi dimensional vector to then be used with the instantiate function. This... works... kinda? When I run the game, the instance of the enemy gets made, I can see the clone in the hierarchy and I can select it and see that it's indeed moving, but it's like... not there? I can't actually see it on the screen and it's not invisible as I can't interact with it either. It's really weird and I have no idea what's going on. I tried to put the script on the camera, on the canvas, on a new empty object, nothing. I also checked that the prefab and the instance that's being spawned are indeed active. I thought about the coordinates being out of bounds, but when I check my player coordinates they are inbounds, so that can't be it either. I'm completely lost on this one, thoughts? Thanks. |
0 | Animate an element from ngui in Unity How can I animate an element from ngui in Unity? For example, how can I move it from the left to the scene when the button is clicked? |
0 | Unity Render only select objects but show previously rendered objects I am making an RTS game which is having performance issues. Is it possible to render the ground and units separately so I can only render the ground when the camera moves but keep the result displaying the units over the top? I'm not sure what details to include but The camera is fixed angle and orthographic The profiler says drawing takes up about 50 of CPU when units are moving. All the logic is done by a c script outside of monoDevelopment but called through a gameobject each frame, (takes 2 of cpu in tests). Units are put in place using the "transform.position" command each frame. Units and tiles are instantiated and destroyed when the Camera passes them. The game is using rigged .3ds models for the units. The units have disabled rigidbodies. Each tile in the game is a separate sprite. The performance drops with 100 low poly units without animation or 20 higher poly units with animation. |
0 | 3d Maya object mesh problems when used in Unity Asking for help to solve a problem 3d Maya objects imported in Unity to make an ios app. Maya object change when imported on Unity mesh attributes disappears and mesh structure comes evident. Has anyone some suggestion to fix this problem? |
0 | how can i fix my code in order to get rid of the error that says that the object I want to instantiate is null? using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class replicate MonoBehaviour public void replicateCube(InputField T) int H int.Parse(T.text) for (int i 0 i lt H i ) GameObject prefab Resources.Load("Cube") as GameObject GameObject go Instantiate(prefab) as GameObject go.transform.position new Vector3(0, i 5, 0) |
0 | Generate static 2D Tilemap from array How do I generate a 2D tile map from an array like in this tutorial for XNA ? I basicly want to generate a static map based on my tile prefabs. |
0 | How to create a Unity Editor box grouping with a header and vertically stacked content inside? I am trying to do something like this with Unity Editor for my window but I am not sure how it is done. So it is basically a box ( a wrapper ) with a title at top. Beneath the title there are boxes or "cards" where you add text to it. Any help is appreciated! |
0 | How to make the whole game wait until some new feature at beginning is finished? In Unity I have been working on a driving game and its almost finished. I'm just trying to add some polishing touches. Ironically this part im stuck on now would not have been any issue at all in purely code based frameworks i used before (LibGDX Xna) because I could just make a boolean that's called ReadyToPlay or something and just put that around all the code i want to wait to start. I've made a secondary camera which rotates around the players car, it works fine but my problem is that the GUI is also already loading AND the race start countdown occurs still whilst the camera is still spinning. I'm not sure in Unity how to go about stopping that to allow the time for the camera to spin. One idea I have to fix this (i'm checking first because this doesnt seem right to me) is to use the yield routine in the GUI loading script and tell it exactly how many seconds the camera is going to spin for. I'd rather have just have the camera detected when its done a full spin and then make a boolean true, or trigger another method to start the game properly. I promise I have done some research trying to find ways but the only thing i can find except yield, is Monobehaviour.Invoke but the invoke method still requires me to specify the time. The whole strategy for yield or invoke feels wrong to me. I guess my main problem is that the code is spread over a few scripts, instead of being funneled thru a main.cs and then gameManager.cs etc etc so theres no way (that I know) to break the chain higher up. I'd have to add bools to each script to say isLuxuryCameraAlive and that still seems wrong to me as I might have 5 10 scripts and have to also section of bits of code in each script. How would you experienced programmers attack this issue?? Thank you!! |
0 | Issues with 3dsmax and Unity3d scale I changed the units in Blender so they are identical to Unity 3d. If I make a 1m 3 box in Blender, it will import into unity as exactly the same size as the standard cube. With 3ds max, I changed the unit setup to metric and made sure it was centimeters in the system unit setup tab. However, when I import an obj file made in Blender and used in Unity, it is absolutely tiny. I have to convert the model to meters on import and then, when exporting, I have to set the model scale to .01 otherwise it is enormous in the unity scene. I've tried changing the max units to meters and nothing changed. How do you change the max unit grid setup so one grid unit is 1m 2 and exactly equivalent to unity's grid? |
0 | Unity Blurry on new Windows 4k Computer I just got a Razer 14 Inch 4k with a GTX 1060 and am having some blurry rendering in unity. Also the cursor is tiny... Here is a screen shot As you can see, the rendering is really blurry. I came from a mac and did not expect unity to look worse after switching to a computer with a great screen res and graphics card... Please help! EDIT I am still getting jagged shadows but now I seem to be able to fix it with changing shadow distance in Quality Project Settings But then the shadow disappears really quick if i have low shadow distance... |
0 | How to make Scriptable Objects derive from other Gameobejcts? I encountered a problem where I want to make a Scriptable Object that derives from another class, but C does not support multiple inheritance. Further, I do not think it would not make sense to make interfaces for this example. There is a lot of duplicate code within methods that only an abstract class could contain implementations of. Basically, I want an abstract class that models "anything that can take a turn." I call it a TurnTakeable. But I also want the TurnTakeable to be split into friend and foe derived types, as the two are slightly different. Yet they mostly have the same behavior. Is there a workaround, or do I have to make an interface? ( |
0 | Whats the best way to make my Unity game moddable? Basically the title. I'm building a game with several NPCs and complex systems, and I want it to be nice and modular for modders right from the beginning. So far, I have looked into Asset Bundles, I don't completely understand these, probably will have to write some custom loading code? I don't know how if this will let the modders write code. Lua Based Modding, I don't particularly like Lua, but I will fall back to it if I absolutely have to (The Unity Lua Plugin makes this a seemingly very fast way.) Exposed C (original idea from this Question). But again, as stated in the question raw c has a lot of disadvantages, not to mention the security risks and compatibility issues. Minecraft Style? Completely custom? Basically a lot of events and registries? I'm not sure about this option. To give you an example, there are several Tribes in the game. Ideally, if a modder wanted to make a new tribe they would need to extend from some Tribe base class and then register add their custom tribe to my AvailableTribes list. Not to mention the models, animations, and sounds for the Tribe NPCs and such. Any help is appreciated! |
0 | Unity detecting edge of mesh or end of mesh I'm trying to create procedurally generated tiles and I've reached a point where I need to figure out the boundaries of the mesh or the outer vertices of the mesh. RaycastHit hit if (Physics.Raycast(bound i .v2, Vector3.forward, out hit)) if (hit.distance gt 2) I've tried raycasting all the vertices, but still can't get the vertices of the edge. The mesh does have a collider. any help on how i would go about this is appreciated, Thanks. |
0 | Weird windowed resolution can't seem to change without changing the name My game is windowed, and when I set the resolution in the build settings (960x540 16 9 Windows standalone), and build it, it works as intended, but from then on, I can no longer change the resolution (can change it in the editor, and it also saves, but when I build it, it is still the original res (960x540))unless I change the Product Name as well. When I change the product name, I can change the resolution, build it, and it will change, but then it is stuck as well. When I change back to the first name, the resolution automatically change it the resolution for the first name (960x540) (it doesn't show up in the editor, only when you build it.) So basically Name1 960x540 Name2 1280x720 Name3 1024x576 etc So you can change the resolution every time you change the name and build it, and that name is stuck with that resolution (no matter what you change it to in the editor later). I am fairly new with unity, so am I missing something very basic here? Thanks for any help! |
0 | Why do these textures tile rather than just overlap? It might help to provide all the details, so here is the YouTube tutorial which sparked my question. There's a prefab of the background tile called "Tile Background." This prefab has the default settings, except that Pixels Per Unit is set to 512, and that it has a script attached to it called BackgroundTile which hasn't even been opened. It's just there for the other script to reference. An empty object was created called Board, which has Tile Background as its tile prefab. It also has a script, Board.cs, the contents of which are here using System.Collections using System.Collections.Generic using UnityEngine public class Board MonoBehaviour public int width public int height public GameObject tilePrefab private Backgroundtile , allTiles Start is called before the first frame update void Start() allTiles new Backgroundtile width,height Setup() private void Setup() for(int i 0 i lt width i ) for(int j 0 j lt height j ) Vector2 tempPosition new Vector2(i, j) Instantiate(tilePrefab, tempPosition, Quaternion.identity) Width is set to 4. Height is set to 7. Other than that, the camera position is X 1.5,Y 3 and the aspect ratio is 9 16. My question is this why, when this is run, does Vector2(i,j) get interpreted as tiling the sprites, rather than placing the sources of the sprites in a 4x7 pixel grid, where they overlap almost entirely? There's no place where their positions get multiplied by the size of the tiles, right? Halving the pixels per unit doesn't even just halve the height of the board it stays a constant size and looks really weird, despite the board not having set dimension attributes. What's going on here? |
0 | Unity text component not updating text properly It was worked fine previously, but after some point, it's not working. This is the code. It's not a pseudo code, actual code in game public Text healthText void Start() healthText GameObject.Find("UI InGameUI CharacterStatus HealthText").GetComponent lt Text gt () void Update() if(healthText) print(health) healthText.text Time.deltaTime.ToString() healthText.text "HP " health.ToString() healthText.text "HP " health variable "health" is float value. I just want to print it to the screen, but it's always prints "Health 100" even it changes. So I printed the value to the console, but it prints well in the console and only text components was not printed properly. So I printed Time.deltaTime instead of the health and it works! Seriously, what the hell is happening? Is this a bug? If health variable wasn't changed, it should be also printed 100 in the console, but it's not! Try this to another text component, still not working. |
0 | Button onClick in a menu prefab doesn't work I don't seem to be able to make a reference to a Button inside a menu prefab. My menu prefab consists of a panel and the panel has 4 buttons. I added public GameObject prefabMenu in my code and drag and dropped the prefab in the Unity Editor to it. When my scene is starting (Start() method) I instantiate this prefab into a GameObject like this panelMenu Instantiate(prefabMenu, canvas.transform) after that I try to refer one of the buttons with this line and set an onClick listener btnResume panelMenu.transform.Find( quot BtnResume quot ).GetComponent lt Button gt () btnResume.onClick.AddListener(() gt Log.I( quot Working quot )) The log method however doesn't not get called when I click on the button (I checked and the btnResume is not null). I appreciate any help on this. Thank you. |
0 | Can a material be created from a gameobject in Unity? I am trying to manually create snowflakes in unity, after I created a snowflake in the unity scene, is it possible to create a material out of it? |
0 | Mesh vs LineRenderer Performance I've created a script, which is drawing a line along a bezier curve, so that I can animate whatever I want with lines, mostly for UI purposes. For the moment I'm using a line renderer, which works, but the performance is not that great in my opinion. So I was wondering if there are actually some better methods to draw lines, like simply creating a mesh along the path I've got. |
0 | Problem modifying GameObject in list of GameObjects Unity So I've been working on a little project that involves Valve's quot Portal quot style portals, the type where you can seamlessly see what's on the other side and walk through. I've run into a problem when it comes to teleporting an object to it's new location upon hitting the portal. I have a List lt GameObject gt that contains all the objects that are in close enough range to feasibly travel through the portal, but when I try to modify the transform.position of one of these GameObjects, nothing happens, no error messages. So I've been going through my script line by line and writing little dummy functions to test different parts of it to see where the problem lies, and everything seems to work up until I index the list and try to modify a value, nothing happens. So was thinking that perhaps the List doesn't actually contain a reference to the GameObject in the scene, but simply a copy of the GameObject's data at the time it was passed into the list. So I checked this by making the list public so that I see it in the inspector, and when I click on an item in the list it highlights that same GameObject in the hierarchy, which suggests it is actually a reference. See bellow... I am at a loss as to what's happening here and would really appreciate if anyone could offer a suggestion, Here is the dummy function where I try to arbitrarily modify the GameObject data from the List... if (Input.GetKeyDown( quot k quot )) for (int i 0 i lt trackedTravelersObjects.Count i ) trackedTravelersObjects i .transform.position new Vector3(0, 30, 0) Debug.Log( quot K quot ) You'll notice a Debug.Log( quot k quot ), this is just to check that the code is actually being called, which it is. Thanks. |
0 | Best way to constrain character to a path? I'm in the process of developing a level based runner for mobile phones, and I've hit a wall when deciding which method to use to get the character to move through the level. Basically I need my character to travel a constrained path across the level as I manipulate the character by speeding up down and jumping to avoid obstacles. I couldn't just place a straight path and use Curved World look as I needed a realistic feel to character motion. I also have up down slopes that have to affect the character's speed. I'm not use whether using iTween is the best for this as it makes it difficult to manipulate character speed and especially the jumping 'arc'. I've tried using MoveTo() but problems arose when trying to change character parameters... PutOnPath() made sense in theory but I found it harder to implement. Is there any easier way to go about this? I'm almost completely new to Unity, so an easier implementation is what I'm going for, for now. Thanks in advance! |
0 | How to make a character that moves like a slinky? I have a school assignment to make a 2D platformer game, with a character that moves like a slinky (Animated example from the assignment linked above) At first, the character needs to grow in height over time When the player presses a button, the character starts to bend toward the next platform Its height when you press the button determines whether it will hit the next platform After that it must shrink to its initial size, and it goes over again. How can I approach this? |
0 | Basic Character Controller Not Working Properly in Unity I've been trying to setup a simple mouse camera which I had all the code working fine, except when I move with wasd and move my mouse to turn the camera simultaneously the input freezes up and gets stuck repeatedly inputting whatever the last input was. I've tested the simplest way to replicate the issue and it doesn't even need a camera for the issue to come up. If anyone would like to test and try to replicate the issue these are the steps its super fast and simple. create new project(basic PC 3D project) create a plane, and a cube Add a basic character controller script to the cube (this time I used the official Unity code to be sure it's not an issue with code) and that's it, that's actually all that was needed to create the issue for me. And to explain to anyone who may want to test it the issue is as follows when you use wasd keys normally, everything works fine and the controls are responsive. However if you hold down one of the wasd keys while also moving your mouse (just wiggling the mouse should suffice) suddenly things will lock up and the cube will keep moving for a bit even after you let go of the respective wasd keys. In general if you hold a direction while simultaneously wiggling the mouse for a longer period of time, it will extend the amount of time the cube keeps moving after you let go of the direction. And this was done on Unity version 2020.1.16f1 If anyone has any idea what the issue may be its really appreciated. |
0 | How to display full website in Unity WebGL? I want to display the complete website within the WebGL in Unity. I have tried Awesomium plugin but it doesn't work in WebGL. Please tell me is there any way to display the webpage. Thank you. |
0 | How would I properly flip a character when they reach the edge of a ground object in Unity 2D? The idea here is that the raycast shoots downwards from an empty game object and when it detects that there is no ground below it the character should bounce back and walk the other way. When I get to the edge of my platform the character just gets stuck in place and keeps rotating on the Y axis. public class npcAI MonoBehaviour public float speed public float distance private bool movingRight true public Transform groundDetection raycast goes downward from this point private Vector2 movementDirection void Start() Initialise direction movementDirection Vector2.right void Update() transform.Translate(movementDirection speed Time.deltaTime) RaycastHit2D groundInfo Physics2D.Raycast(groundDetection.position, Vector2.down, distance) if (groundInfo.collider false) if (movingRight) movingRight false movementDirection Vector2.left transform.localScale new Vector3(0.30F, 0, 0) else movingRight true movementDirection Vector2.right transform.localScale new Vector3(0.30F, 0, 0) The code above was edited to reflect the answer below. If you find yourself attempting to do the same thing and need to flip your sprite when you reach the edge change 0.30F to whatever double the X value of your sprite is in order to flip it. My sprites scale was (0.15, 0.15, 0) so I used 0.30F to flip my sprite. Be mindful of when you should use and when you should use . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.