_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Baking artifact in Unity I am using unity 2017.1.0 f3, Enlighten baking, with Generate lightmap UV ticked in import settings. Also the object has prioritized illumination and the light map resolution is high. An example of the artifact is shown. The lightmapping settings is as follows. The issue doesn't appear in Realtime illumination. The object is marked static. Can someone help me? |
0 | Unity How to add a shader to a material via c script? I found already some things but those seem not quite what I need. (perhaps outdated functions?) https docs.unity3d.com ScriptReference Material shader.html here, it seems you can add a shader to a renderer using UnityEngine using System.Collections public class ExampleClass MonoBehaviour public Shader shader1 public Shader shader2 public Renderer rend void Start() rend GetComponent lt Renderer gt () shader1 Shader.Find("Diffuse") shader2 Shader.Find("Transparent Diffuse") void Update() if (Input.GetButtonDown("Jump")) if (rend.material.shader shader1) rend.material.shader shader2 else rend.material.shader shader1 well i dont have a renderer. i only have a material. and there is no "material.setShader" , only a material.setTexture" sooo can anyone solve this mystery of how to add a shader to a material via script? |
0 | Change value in arrays in array The title might be confusing and I don't think this short explanation is 100 accurate, but I will try my best to show the problem. So I have this hierarchy And I want to change quot measureOfTime quot value in all subWave in wave i , because I had no clue how to do this in a short way (at least I bet there is a shorter way) and I made this using UnityEngine public class EnemySpawner MonoBehaviour Header( quot Set this value here to set time to 1 wave quot ) public float timeUntilWave Header( quot Measure Time basically 0 quot ) public Wave waves public float waveTime public bool roundStarted public int wave private void Start() wave 1 roundStarted false private void Update() if (timeUntilWave gt 0) timeUntilWave timeUntilWave 1 Time.deltaTime else if (timeUntilWave lt 0) roundStarted true wave if (roundStarted true) waveTime waveTime 1 Time.deltaTime int subwaveLenght waves wave .subWave.Length int count 0 while (count lt subwaveLenght) waves wave .subWave count .measureOfTime waves wave .subWave count .measureOfTime 1 Time.deltaTime count And in lines 33 and 37 I see an error quot IndexOutOfRangeException Index was outside the bounds of the array. quot And here are 2 questions Why those errors appear here? Is there an easier way to raise the value in arrays in an array? I hope it's not too confusing, and thanks for your help! |
0 | When I exit the pause menu of my game the gun fires When The player exits the pause menu in my game the gun will fire. I figured out that it happens when the player clicks when the game is paused. Basically i the player goes to the pause menu and exits without clicking the gun will not fire, but if they go to the pause menu and click then exit the gun will fire. Here are my scripts public class Shooting MonoBehaviour Animator anim public float FireRate 15f private float NextTimeToFire 0f Start is called before the first frame update void Start() anim GetComponent lt Animator gt () Update is called once per frame void Update() if (Input.GetButton("Fire1") amp amp GetComponentInParent lt PlayerController gt ().moving false amp amp Time.time gt NextTimeToFire) NextTimeToFire Time.time 1f FireRate Shoot() public class PauseMenu MonoBehaviour public static bool GameIsPaused false public GameObject HUDPanel public GameObject PauseMenuPanel public GameObject OptionsPanel private void Start() Time.timeScale 1f GameIsPaused false void Update() if (Input.GetKeyDown(KeyCode.Escape)) if (GameIsPaused) Resume() else Pause() void Resume() Cursor.lockState CursorLockMode.Locked Cursor.visible false PauseMenuPanel.SetActive(false) OptionsPanel.SetActive(false) HUDPanel.SetActive(true) Time.timeScale 1f GameIsPaused false void Pause() Cursor.lockState CursorLockMode.None Cursor.visible true PauseMenuPanel.SetActive(true) HUDPanel.SetActive(false) Time.timeScale 0f GameIsPaused true |
0 | Why is my inherited class's transform always null? I have a class inherited to another class, and I can't get the transform on the inherited class. Here's what i have and trying to do Class A Monobehavior Class B A somewhere else A object new B() but right now, whenever I try to get the transform of object, either from a function in B or out here via object.transform, it will always return null. How do I fix this? |
0 | UNet send message by Client.Send error I'm try to implement client server communication base on UNET. The problem i got now is send custom message to server, but the Client.Send always show error without my understanding. So what i'm wrong? I jus try to implement from scratch, not inherit from NetworkManager. Here is the code using UnityEngine using System.Collections using UnityEngine.Networking public class ZMessageTransfer NetworkBehaviour private static ZMessageTransfer instance public static ZMessageTransfer Instance get return instance NetworkClient m Client public class MessageType public static short Login 1001 public class LoginMessage MessageBase public string username public string password void Awake () instance this public void SendLoginMessage(string username, string password) LoginMessage loginMsg new LoginMessage() loginMsg.username username loginMsg.password password m Client.Send(MessageType.Login,loginMsg) Server using UnityEngine using System.Collections using UnityEngine.Networking using UnityEngine.UI public class ZMatchServer NetworkBehaviour public int listenPort public int maxConnection public bool enableNAT public Text currentPlayer public Text currentLog private int onlinePlayer void Start () Network.InitializeSecurity() Network.InitializeServer(maxConnection,listenPort,enableNAT) NetworkServer.RegisterHandler(ZMessageTransfer.MessageType.Login,OnPlayerLogin) void OnPlayerLogin(NetworkMessage netMsg) var loginMsg netMsg.ReadMessage lt ZMessageTransfer.LoginMessage gt () string username loginMsg.username string password loginMsg.password currentLog.text "Player send login " username " " password void OnServerInitialized() Debug.Log("Server Initialize completed! ") currentLog.text "Server Initialize completed! " void OnPlayerConnected(NetworkPlayer player) onlinePlayer 1 currentPlayer.text "Current player online " onlinePlayer.ToString() currentLog.text "Player connected" Debug.Log("Player connected " ) void OnPlayerDisconnected(NetworkPlayer player) onlinePlayer 1 currentPlayer.text "Current player online " onlinePlayer.ToString() currentLog.text "Player disconnected" Client using UnityEngine using System.Net using System.Collections using UnityEngine.Networking using UnityEngine.Networking.Types public class ZNetworkConnection NetworkBehaviour SerializeField private string serverURL SerializeField private string serverIP SerializeField private int serverPort NetworkClient m Client private static ZNetworkConnection instance public static ZNetworkConnection Instance get return instance void Awake() instance this void Start () ConnectToServer() protected void ConnectToServer() Network.Connect(serverIP,serverPort) public void LoginToServer(string username,string password) ZMessageTransfer.Instance.SendLoginMessage(username,password) protected void OnConnectedToServer() Debug.Log("Connected to server complete ") |
0 | Character on Moving Platform Shaky. How to Fix? I have an elevator (rigid body platform) that is meant to transport a character. The character (RigidBodyFPSController) shakes while platform descends. What is an elegant way to fix their relative motions while the elevator is in motion, still allowing the character to move around in it? NOTE I tried parenting the character but that flips him on his side. |
0 | How do I get light to go through a window texture in Unity? I'm having trouble with the lighting (I have windows and the light wont go through). How do I get the light to proceed through the glass? |
0 | Would I need to delete unused assets from my Unity packaged build? I'm going to make a release for my Unity game. Does Unity include unused assets in build output? Would removing unused assets from a project reduce build size Time? I want to know if Unity packages all the assets to my build (which I would need to delete), or if Unity packages only the assets that are actually used in the game. |
0 | Unity Client and Multiplayer Networking Architecture My background is in Enterprise and SaaS web infrastructure. Zero information about games and how their networking works. I only know about the world of browsers and RESTful APIs. I'm planning on using Unity for the client FYI. Authentication and Authorization I'm planning to use Unity and Firebase. Seems like this is fairly standard HTTP connections during the auth faze. Nothing surprising here unless there is something I missed. The client authenticates against a service, Firebase in this case. And then all future calls after authentication are made using the returned credentials. Gameplay and Player State This part confuses me. I assume shooters use a UDP type protocol or some proprietary protocol on top of UDP. But can a game use a REST API and HTTP or TCP connections to send client updates? Clients would then poll the game server or have a long running connection open to request updates. For example the Auction House in WoW. Is there a long lived TCP connection open between the client and the server updating the auction house data every X seconds? Then when a player submits a purchase order that same long lived TCP connection is used to update the game server state? Or is it all literally a REST API like a SaaS app would use? Is my experience with browsers and Single Page Apps in an Enterprise environment applicable to a WoW auction house type situation? Thank you, Any tips or feedback is helpful at this point. |
0 | Help understand Z value of CameraToWorldPoint I do not understand what this CameraToWorldPoint function is used for, what is the use case of this function 1.From my understanding, my cursor is sitting on the near clipping plane, so I am actually clicking all the points on the near clipping plane, the near clipping plane represents my screen, am I right? 2.When I use this function to convert B point to world point, I am getting the point C position, is that true? 3.Is part A gt C represent the Z value, or part B gt C is the Z value? 4.Then finally, is this function useless? Because I get a world position in the predefined Z position, and I do not even know what Z value should be in the first place, I can randomly assign a pointless Z value, so what is use case for this function, I know raycast can do anything I want, but when to use this function? |
0 | How do I use GetComponent on multiple children? I'm a beginner and I'm making a game in Unity where I set random colors for four enemies. I made an empty object called "enemies" for me to use it as a folder for the four enemies. I want to get the colors of the enemies and pick randomly one of them for my player. I wrote this piece of code and I wanted it to store the colors in a list, but whenever I try to print it I find out that it only stores the color of the first child in the "enemies" hierarchy. How do I fix this? enemies GameObject.Find("enemies") GameObject allenemies new GameObject enemies.transform.childCount List lt Color gt colors new List lt Color gt () foreach (Transform child in transform) allenemies i child.gameObject i foreach (GameObject child in allenemies) thecolor enemies.GetComponentInChildren lt Renderer gt ().material.color colors.Add(thecolor) finalcolor Random.Range(0, colors.Count) Debug.Log(finalcolor) mr.material.color colors finalcolor |
0 | Efficient way to store information about neighbour chunks I've finally managed to implement an infinite chunk loading system for my voxel engine. Since every chunk needs to have information about the border of the neighbouring chunks, I need to access them fast. First some information about how I'm storing the voxel data I have an Integer array of block information on each chunk (rather than byte because of the read write access speed), which is stored in an Dictionary(Vector3i chunkPos, Chunk chunk). When building a chunk I have to access the voxel data of the chunk and of the neighbouring chunks several times. Without information about their neighbours it currently looks like this So I've tried the following two things getting the chunk data every time like this public static int getBlockAt(int x, int y, int z) Vector3i chunkIndex new Vector3i( x gt gt ChunkManager.logChunkSize, y gt gt ChunkManager.logChunkSize, z gt gt ChunkManager.logChunkSize ) if (chunkManager.chunkData.ContainsKey(chunkIndex)) return chunkManager.chunkData chunkIndex .data x amp ChunkManager.chunkMask, y amp ChunkManager.chunkMask, z amp ChunkManager.chunkMask return 0 storing chunkSize 2 information on each chunk, which makes editing much, much slower, but improves chunk loading alot In general I want to implement something like using approach 1 only when the block data isn't on the chunk. I really don't know how I could do it! Do you have an idea, or experience from writing voxel engines? Thanks in advance! |
0 | Game 30 done on HTML5. Maybe it was a bad idea. Should I change to Unity3d? I'm creating a 3d game on HTML5. It's 30 complete and the hard part is already coded. The server is on node.js.Now I'm realizing that maybe it was not a wise choice. This is because I realized Three.js still has many bugs. I don't see the same thing on every machine. Each browser, OS, can give different results. I'm afraid my clients will have a great stress installing my game properly. I have tons of sprites and models on my game. I wonder if my clients will have to load all them again everytime they want to play? I wonder if a Node.js server will be fast enough to handle it, and I'm afraid it won't be scalable. What would you advise me? Should I continue and finish the game on HTML5 or is it better to remake it on something else, like Unity3d for the client and (what?) for the server? |
0 | Center Gravity in Unity a 2d planet in the center, where the players will be able to walk on it and also will be affected by center gravity. planet will be static and there won't be any other planets. so Is there a way that I can change the gravity position? yes you can adjust gravity via project settings but I want it to be in the middle x,y,z(0,0,0) I have tried creating my own gravity but it wasn't very useful because objects wouldnt fall, stand on foot and also in contact with another object they would vibrate instead of standing still. (if they stand on the planet they would vibrate) private void FixedUpdate() foreach(GameObject item in grav) Attact(item) private void Attact(GameObject gmf) Rigidbody2D rgg gmf.GetComponent lt Rigidbody2D gt () Vector3 direction rg2d.position rgg.position float distance direction.sqrMagnitude float forceMag (10 rgg.mass) distance Vector3 force direction.normalized forceMag 10 rgg.AddForce(force) I can create a script that will change the gravity by the opposite of the object's position. this does work but I cannot see any way to do it for more than one object. |
0 | Inconsistent CapsuleCast Collision behavior when a GameObject is selected My gameobject has a CapsuleCollider and I use CapsuleCast to check for horizontal collisions when moving horizontally so the gameobject won't pass thru obstacles. It works 100 of the time except when I select the gameobject in Hierarchy. When I have the gameobject selected, whenever I try to bump a wall continuously, it shakes jitters until it eventually goes thru the wall. But this only happens when I have the object selected in Hierarchy. If I click on the scene so that the object is not selected and do the exact same thing (bump a wall continuously), there is no shaking jitter and it doesn't pass thru the wall no matter how long I bump it. This passing in the wall when selected is also consistent. Hundred percent of the time it will pass thru when I have it selected (and does the shaking) and also hundred percent of the time it doesn't if I don't have the object selected. Shouldn't selecting an object don't have any effect on this? Please give me some ideas of why. |
0 | Smooth rotation for a bone? I'm trying to make my character bone "chest" rotate smoothly when face enemy and get back to his stand. Can anyone help me with this ? public Transform Target public Vector3 Offset Animator anim Transform chest public float rotation speed public bool aim at traget false void Start() anim GetComponent lt Animator gt () chest anim.GetBoneTransform(HumanBodyBones.Chest) void LateUpdate() if (aim at traget true) smooth rotation to face target chest.LookAt(Target.transform.position) chest.rotation chest.rotation Quaternion.Euler(Offset) else get back to you stand smoothly |
0 | Synchronization problem with Visual Studio 2017 and Unity 2017.1.1f Sometimes I need to change a lot of files and Clean and Rebuild the Solution to get the changes on Unity, am I missing some configuration on Visual Studio or Unity? I uninstalled everything and make a clean install and few days later I'm getting the same problems. Sometimes if I create a stardard MonoBehaviour script from Unity and I try to attack it to a gameObject I get the error "Can't add script component XXXXXX because the script class can't be found"(see image screenshot). The class name and file name are the same, with no syntax errors. Some times opening a file with an external editor changing the encoding, cleaning and rebuilding the project solves the problem, but just sometimes and I'm tired of do that for test any change, now I have a lot of Debug.Log just to check if Unity is getting my code changes. Any suggestion will be very greatful |
0 | Unity What changes to a game object trigger baked lights to need a rebake? I've noticed that sometimes when I make changes to game objects in scenes that have baked lights that the baked shadows will no longer be in effect and dynamic lights will instead be showing. Destroying and recreating the object seems to trigger this reliably, but what other changes to games objects in a scene can cause a rebake to be needed? |
0 | UNET Performance of (many) Kinematic Rigidbodies I am building a game in Unity in C using the UNET networking elements. I am trying to figure out what is the performance cost of kinematic rigidbodies? My understanding is that, when kinematic, rigidbodies are outside the physics system and therefore are not as resource heavy as non kinematic rigidbodies. For my game, I will need to use a lot of kinematic rigidbodies in the scene, because they are used to detect collisions between player placed objects (with box colliders) and the rigidbodies. All the objects instantiated in the scene will therefore need a kinematic rigidbody to allow this collision checking to take place. Thanks very much for your help. |
0 | How do I make an infinitely scrolling background? I am trying to make a game where a torpedos keep coming from random directions and the player has to maneuver a submarine to escape them. I am currently offsetting the background to give it an illusion that the submarine is moving i.e. if the submarine moves forward, I move the background (quad) backwards. This is primarily being done as I want it to be an infinite space. The position of the submarine does not change, the player just controls the rotation of the submarine and the background moves in the opposite direction. The background is set to repeat to give it an infinite space illusion. The torpedo gets spawned at a random distance and moves towards the submarine. Since, the position of the submarine does not change, the torpedo will always hit the submarine. How do I structure this game, specifically the background repeat so that I can actually move the submarine in absolute dimensions and still maintain the infinite space illusion? |
0 | Jittery collisions in Unity 2D I tried to implement a simple movement to my object. My object moves perfectly fine but I'm having issues with its collision. When I keep on moving object towards the obstacle ground, collision are jittery. Here the code for what I've written. using System.Collections using System.Collections.Generic using UnityEngine public class TempScript MonoBehaviour SerializeField float walk speed 5f SerializeField float jump speed 10f SerializeField float max up 7f SerializeField float max low 1.5f void Update() PlayerMovement() void PlayerMovement() if (Input.GetKey(KeyCode.W) amp amp transform.position.y lt max up) transform.position transform.position Vector3.up jump speed Time.deltaTime if (Input.GetKey(KeyCode.S) amp amp transform.position.y gt max low) transform.position transform.position Vector3.down jump speed Time.deltaTime if (Input.GetKey(KeyCode.D)) transform.position transform.position Vector3.right walk speed Time.deltaTime if (Input.GetKey(KeyCode.A)) transform.position transform.position Vector3.left walk speed Time.deltaTime The cube goes below the ground and bounces right back up. making it look like its jittering. what i want is movement should stop when its colliding with object. just like it happens with addForce method. for now you can ignore max up and max down variable, it was just to make sure its in the camera. |
0 | How to make multiple AI surround a player I am working on a top down RPG game and I have come across a problem. I am working on an AI system to allow the enemy AI to surround the player. I've been trying to keep my implementation really simple, however, I've been running into problems. Here is what it currently looks like X represents the player and Y represents the friendly AI. There are 42 waypoints in total that the enemy can potentially occupy. However, if any of the waypoints of the player object encounters an obstacle, or if another friendly AI is too close, it will disable those waypoints This poses a big problem because I do not have all 42 waypoints. From the looks of it, I might need something more dynamic in my case. Are there any alternative ways to allow a large number of AI to surround the player or its allies? |
0 | Unity aircraft physics I want to make a simple aircraft controller, what looks like little realistic in unity. I watch some video from airplane physics. and make a simple script in unity, but if I start, my plane cant move or if I change drag to zero, it cant lift. I tried to use real data and get it from wiki(F22 Raptor). To my game object, I gave the rigidbody component mass 19670 kg. Engine thrust 2 116000.0f Newton. private void calculateEnginePower() EnginePower engineThrust ThrottleInput private void calculateForces() angleOfAttack Vector3.Angle(Vector3.forward, rb.velocity) angleOfAttack Mathf.Clamp(angleOfAttack, 0, 90) coefficient Mathf.Pow(1225.04f rb.velocity.magnitude, 2) 1 M 2 2 where M is mach. if (coefficient gt 0.0f) coefficientLift (4 angleOfAttack) Mathf.Sqrt(coefficient) lift 1.2754f 0.5f Mathf.Pow(rb.velocity.magnitude, 2) coefficientLift 78.04f densy1.2754 kg m3, speed m s , (F22)Wing area 840 ft (78.04 m ) coefficientDrag 0.021f rb.drag coefficientDrag 0.5f Mathf.Pow(rb.velocity.magnitude,2) 1.2754f 78.04f rb.AddForce(transform.up lift) rb.AddForce(transform.forward EnginePower) roll, pitch... inputs from keyboard and mouse, EnginePower, RollInput... are simple properties and I call the Move function in a controller inside void Update. Move(float roll, float pitch, float yaw, float throttle) transfer input parameters into properties.s RollInput roll PitchInput pitch YawInput yaw ThrottleInput throttle AirBrakes false calculateEnginePower() calculateForces() calculateRotation() used these formulas for Lift force Lift formula for Lift coefficient Cl formula for Drag Drag formula and for Drag coefficient I used data from wiki too (0.021f). |
0 | How to find a non active gameobject in unity? I am trying to find a gameobject, which is not active in the current scene.It throws Null Reference error. GameObject gameObject void start() a non active gameobject tagged with InactiveTag gameObject GameObject.FindGameObjectWithTag("InactiveTag") void update() if(someCondition) gameObject.setActive(true) this line throws Null Reference error |
0 | Push data in unity Player without Requesting I have a unity3d Player where I need some data from the server. The server code is written in python while on client side is C . Now I am searching a way that server directly post push data to my unity player. IMO! it is not possible to push data to unity player without requesting the server using WWW class. My question is can python post data to my client unity player? with something like response requests.post(client url, data request data, headers headers) I want to do this because i want to avoid repetitive calls to server which is not an efficient way. |
0 | How can I get the parents and childs from the hierarchy in the same order it is in the hierarchy the structure of the hierarchy? The line var gameObjects GameObject.FindObjectsOfType lt GameObject gt () Is getting all the parents and children but not in the order it is in the hierarchy. I tried to use the gos List and to add first the childs then the parents to create a List with all parents and it's childs but it's getting messed. I want to get the structure of the Hierarchy. var gos new List lt GameObject gt () var gameObjects GameObject.FindObjectsOfType lt GameObject gt () for (int i 0 i lt gameObjects.Length i ) if (gameObjects i .transform.childCount gt 0) get children GameObject children new GameObject gameObjects i .transform.childCount for (int z 0 z lt children.Length z) children z gameObjects i .transform.GetChild(i).gameObject gos.Add(children z .gameObject) else gos.Add(gameObjects i ) |
0 | Unity Shader Outlined Uniform uses undefined Queue 'Geometry 1' my outline shader was working fine but suddenly it started throwing this error. the game still works fine in the editor though but when i try to build it gets stuck on the step Packing assets sharedassets0.assets this is my shader Shader "Outlined Uniform" Properties Color("Main Color", Color) (0.5,0.5,0.5,1) MainTex ("Texture", 2D) "white" OutlineColor ("Outline color", Color) (0,0,0,1) OutlineWidth ("Outlines width", Range (0.0, 2.0)) 1.1 CGINCLUDE include "UnityCG.cginc" struct appdata float4 vertex POSITION struct v2f float4 pos POSITION uniform float OutlineWidth uniform float4 OutlineColor uniform sampler2D MainTex uniform float4 Color ENDCG SubShader Tags "Queue" "Geometry 1" "IgnoreProjector" "True" Pass Outline ZWrite Off Cull Front CGPROGRAM pragma vertex vert pragma fragment frag v2f vert(appdata v) appdata original v v.vertex.xyz OutlineWidth normalize(v.vertex.xyz) v2f o o.pos UnityObjectToClipPos(v.vertex) return o half4 frag(v2f i) COLOR return OutlineColor ENDCG Tags "Queue" "Geometry" CGPROGRAM pragma surface surf Lambert struct Input float2 uv MainTex void surf (Input IN, inout SurfaceOutput o) fixed4 c tex2D( MainTex, IN.uv MainTex) Color o.Albedo c.rgb o.Alpha c.a ENDCG Fallback "Diffuse" i tried looking on the internet but couldn't get any help on this error. |
0 | How to make game scene bigger in 2d platformer? Hi i am current making a 2D platformer game but after i reach an end of screen then it doesn't move forward how to increase the game play screen area so that i will be able to go in vertical direction i am pasting an image of the problem i am new to unity please help me! 1 |
0 | Unity networking, make player disappear for all clients As title says I need to make the player disappear when he gets in car. Right now, it works as a single player, but since I am new to unet I don't really know how to achieve this, I tried some ways, but they didn't work. Here is script Client void OnControllerColliderHit(ControllerColliderHit hit) so if we hit car if(hit.collider.tag "Vehicle") if we pressed "E" if (Input.GetKeyDown(KeyCode.E)) call method to disable some stuff taht should be disabled, like controller, shoot, weapons etc. if (isServer) CmdCall(inVehicle, hit) else RpcCall(inVehicle, hit) Command void CmdCall(bool invehicle, ControllerColliderHit hit) RpcCall(inVehicle, hit) ClientRpc void RpcCall(bool invehicle, ControllerColliderHit hit) disable(inVehicle, hit) I can't see any errors in console but I cant enter play mode cause there are some compiler errors, which again i cant see in console. thank you for any tip, comment, downvote, upvote, or hint ) Nick. |
0 | Additive scene loading to UNet I have a main scene where my player is loading as I start or join the server. On some player action, I want to load additive scenes in to my main scene. It is loading fine on the client, but not across the network. My other clients are unable to watch it. I checked different links, and found a forum post and a Unity Suggestions page. It seems, to me, that this "Additive scene loading to UNet" feature is not available in Unity. If additive scene loading in UNet is not available, then what are the alternatives? I am able to load scene through ClientRpc . Is this the correct way to do this? ClientRpc public void RpcLoadLevelAcrossNetwork() SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive) |
0 | Move Object to another Object's position on click Raycast I have one object, a knight, that I click on and want to move around on terrain. private void OnMouseDown() if (Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit, 10000)) if (unitSelected) MoveUnit(hit) else if (unitSelected amp amp hit.collider home) GoHome(hit) And private void OnMouseDown() if (Input.GetMouseButtonDown(0)) Ray ray cam.ScreenPointToRay(Input.mousePosition) if(Physics.Raycast(ray, out hit)) MoveUnit(hit) Both scripts work fine when clicking on the terrain. The Problem I want to click on different objects and send the knight towards whatever object I click on. The knight does NOT move, though the object I click on registers a click (all objects have colliders). Is Raycast the most appropriate way to do this? Checking another users question similar to mine, (how to move one object to another objects position) they seem to use a method similar to "Vector3.MoveTowards". EDIT Moving my code from "OnMouseDown" to "Update" solves that issue. but is there a reason why OnMouseDown won't work or even how to make it work? I was trying to limit my code from going into Update as that's called every frame. |
0 | JSON deserializing 'nested' Array Greetings! I'm working on a class that loads and parses .json files and returns information from the loaded .json, but I have problems reading the nested arrays of my .json files. Turning the serialized object public and looking at the Inspector, the 'Choises' array is not being read at all. It contains four objects, each contain a string and an integer correspondingly. using SimpleJSON using System using System.Collections using System.Collections.Generic using System.IO using UnityEngine public class JsonParser MonoBehaviour private string loadedJson public StoryData storyData Serializable public struct choice public string choiceText public int choicePointer Serializable public struct storyImage public string imagePath Serializable public struct storyText public string text Serializable public struct placeholderStory public string storyText public string storyImage public List lt choice gt choises Serializable public struct StoryData public placeholderStory placeholderStory public void LoadJsonFile(string filename) loadedJson File.ReadAllText(Application.dataPath filename) storyData JsonUtility.FromJson lt StoryData gt (loadedJson) public string GetChoiceText(int storyPosition, int choiceIndex) string choiceString storyData.placeholderStory storyPosition .choises choiceIndex .choiceText Debug.Log(choiceString) return choiceString public string GetStoryText(int storyPosition) string storyString storyData.placeholderStory storyPosition .storyText return storyString public string GetStoryImage(int storyPosition) string imageString storyData.placeholderStory storyPosition .storyImage return imageString |
0 | Unity rigidbody velocity In Unity, what is the correct way to move a game object by modifying the velocity of its rigidbody? I'm having some issues with stuttering movement, so I just want to make sure I understand the basic idea. Is the following correct for moving an object vertically down the screen? Should this result in smooth, stutter free movement? using UnityEngine public class MovementTest MonoBehaviour private Rigidbody2D rb SerializeField private float speedY 250 private void Awake() rb GetComponent lt Rigidbody2D gt () void FixedUpdate() rb.velocity new Vector2( 0, speedY Time.fixedDeltaTime ) |
0 | Implementing a group formation behavior I am trying to implement a group formation behavior where all the units in my group follow a leader and maintain their position throughout. So far I am able to move them, rotate and follow the leader. I have also implemented character separation and obstacle avoidance behaviors for all my units and the leader. However I want all the units to maintain the same relative position to the leader throughout the behavior ie say for example if one of the unit falls far behind the group due to an obstacle in its path, it should converge back to the main group to its initial relative position so that the formation of the group is not broken and stays the same throughout I have stored all my units in a list and offset them from the leader at the start of the game. But I want their offset position to be maintained throughout each update in the game. I am not able to do that. Below is my code so far public List lt GameObject gt followersList new List lt GameObject gt () void Start() for (int i 0 i lt followersList.Count i ) if(i 2 0) followersList i .transform.position new Vector3(gameObject.transform.position.x (2 i 2 ), gameObject.transform.position.y, gameObject.transform.position.z (2 (i 2 ))) else followersList i .transform.position new Vector3(gameObject.transform.position.x (2 i 2), gameObject.transform.position.y, gameObject.transform.position.z (2 (i 2 ))) private void VShapeFlockWander() Followers GameObject.FindGameObjectsWithTag("follower") Wander(gameObject) foreach (GameObject Follower in Followers) followerDirection (gameObject.transform.position Follower.transform.position).normalized Vector3 normal CheckFollowerCollisionAvoidance(Follower) Vector3 followerSepVector CheckFollowerSeparation(Follower) followerSepVector.y 0 followerDirection (normal followerSepVector) Quaternion rot Quaternion.LookRotation(followerDirection) Follower.transform.rotation Quaternion.Slerp(Follower.transform.rotation, rot, Time.deltaTime 3.0f) Follower.transform.position (Follower.transform.forward Time.deltaTime acceleration) if (acceleration lt vShapeWanderSpeed) acceleration 0.01f in the code above all the followers represent the units and the gameObject is the target leader to follow. All the other behaviors like separation and collision avoidance are working fine. Only thing I want to achieve now is for all the followers to maintain their relative position to the leader throughout. I tried using a Dictionary for each follower as key and its initial difference to the target as the value. Then somehow use that difference factor and make them move in a stable formation but I cannot get it to work either |
0 | Is there a way to display navmesh agent path in Unity? I'm currently making a prototype for a game I plan to develop. As far as I did, I managed to set up the navigation mesh and my navmeshagents. I would like to display the path they are following when setDestination() is fired. I did some researches but didn't find anything about it. EDIT 1 So I instantiate an empty object with a LineRenderer and I have a line bewteen my agent and the destination. Still I've not all the points when the path has to avoid an obstacle. Furthermore, I wonder if the agent.path does reflect the real path that the agent take as I noticed that it actually follow a "smoothier" path. Here is the code so far GameObject container new GameObject() container.transform.parent agent.gameObject.transform LineRenderer ligne container.AddComponent lt LineRenderer gt () ligne.SetColors(Color.white,Color.white) ligne.SetWidth(0.1f,0.1f) Get def material ligne.gameObject.renderer.material.color Color.white ligne.gameObject.renderer.material.shader Shader.Find("Sprites Default") ligne.gameObject.AddComponent lt LineScript gt () ligne.SetVertexCount(agent.path.corners.Length 1) int i 0 foreach(Vector3 v in p.corners) ligne.SetPosition(i,v) Debug.Log("position agent" g.transform.position) Debug.Log("position corner " v) i ligne.SetPosition(p.corners.Length,agent.destination) ligne.gameObject.tag "ligne" So How can I get the real coordinates my agent is going to walk throught ? |
0 | MotionBuilder Actor attached to Mocap moves fluently, but Character using Actor as source jitters and has joints occasionally pop out I'm trying to get a MotionBuilder animation to work in Unity on my custom character. I've downloaded Motionbuilder FBX mocap files with Actors already attached from http dancedb.eu main performances The thing is that when I put the Actor as the Input source for my own (Characterized) character model and hit play on MotionBuilder, my model follows the animation 80 correctly but for the other 20 my character jitters and shakes and occasionally even quot breaks a limb quot when a joint randomly pops out of its place for a second. Does anyone have suggestions on how to get the animation smoother for my Character? |
0 | Random Object in Array I am using Unity. I have created eight different types of objects, stored in an array, and I am displaying them on the scene in a grid pattern with random order. The first four objects in the array are red. The player needs to destroy all four red objects to go to the next level. The code I've writted so far uses the Random.Range method, which chooses objects completely randomly. Sometimes it generates a grid that doesn't contain four red objects, so my player can't destroy them and proceed to the next level. How do I randomly generate this grid so that it is guaranteed to have exactly four red objects? Here is my code. public int gridWidth 0 public int gridHeight 0 public GameObject facePrefab new GameObject 8 void Awake() gridHeight Random.Range (3, 5) CreateGrid(gridWidth,gridHeight) void CreateGrid(int numX, int numY) for (int x 0 x lt gridHeight x ) for (int y 0 y lt gridWidth y ) GameObject go Instantiate (facePrefab Random.Range(0,facePrefab.Length) ) as GameObject |
0 | How can I render from a buffer that exists and was created on on the GPU? I'm looking for a unity API or function call to allow me to do the following ... I wrote some really complex functions that are compute shaders. These compute shaders manage a huge compute buffer containing voxel information. I then take portions of (or the entire) voxel buffer in another compute shader and produce a vertex buffer. All of this is done on the GPU with only compute shader calls from the CPU. Now I want to render that vertex buffer but I must be looking in the wrong place because I can't find any information on how this is done within unity despite there being other examples on how to do this using raw DX or openGL approaches. Can anyone point me in the right direction to determine how I can render using a specified shader a buffer already in graphics RAM (and ideally give it some textures too)? |
0 | Command pattern for network games I am currently programming a multiplayer game. The basic idea is that the game uses Command Pattern for any actions that happens in the game. If the player right clicks to move then a command is issued to the selected object to move to the location. I implemented gRPC to include multiplayer. Here is my problem, when the player right clicks on the ground I send a gRPC call with that command then the server acknowledges the commands and sends it back to all the clients, the client then processes the command and everything goes well. Now if the player enters the game while a command is underway the client never received that command so its never process on the client. What would be a good way to fix this problem without sending the info of all the actors (x,y,z) and what they are doing at each server ticks? Thanks! |
0 | ColorMaterial AmbientAndDiffuse equivalent for CG HLSL I have this shader written on shaderlab, which replaces Ambient and Diffuse values of the material, because I need to tweak vertices colors from the script. Shader "VertexSimple" Properties MainTex ("Base (RGB)", 2D) "white" SubShader Pass ColorMaterial AmbientAndDiffuse Lighting Off SetTexture MainTex Combine texture primary Fallback "VertexLit" I need to write an equivalent of this shader on CG HLSL to do some other routines in it. Ideally it should be vertex pixel shaders, not surface one. How can I do this? |
0 | Should I downgrade my Unity project to the latest LTS version? I created my Unity project with a 2020 version and now I'm using 2020.2.0f1. Recently, I realized that using the latest LTS version is the best choice for games that are in production or about to ship. I tried downgrading to the latest LTS (2019.4.18f1) but since Unity doesn't support downgrading, all my objects disappeared and I got a lot of weird errors in console. My question is Should I continue developing the game with the version that I'm using right now or downgrade to the latest LTS version? |
0 | Why does my custom network Manager disable the main one Whenever I add a custom Network Manager to add functionality to and override it's functions, the main NetworkManager got disabled so I could not see the NetworkManager HUD or start matches. It there a way around that? (EDIT) Thanks for the response It's not just the HUD that's the issue. The Networking is disabled entirely. Can I change this through a custom HUD? |
0 | How to create a 2d jelly soft blob body? I'm a developer looking into game development. I have an idea that requires a 'character' that needs a jelly like body. I've found this video which really demonstrates what I want. I've looked around and there are libraries assets that do this (like Jelly Sprites) but none state how they do it, and that's what I'm interrested in. What I've read so far is that a way of doing it is using multiple rigid bodies joined with joints that don't collide with each other. Witht he common sidenote that it might not perform that well. I'm hoping anyone has any pointers or tutorials that explain the concepts of jelly soft blob bodies. Any pointers towards achieving the effect shown in the video would be awesome. |
0 | How to calculate 1st, 2nd, 3rd place and draw conditions in local multiplayer game? I have a local multiplayer game with an end of round screen that pops up after each round. I'm trying to figure out the logic to calculate the 1st, 2nd, 3rd place from a maximum of 4 players. I also want draw tie conditions. It's possible for 2 or 3 players to get the same score. The score is just an int for each player. I've been struggling with this for a while... Any help appreciated, even if its just some pseudo code to point me in the right direction. Also, I'd like to avoid using Linq if possible, as I've heard it doesn't play nice with Unity. Thanks Edit Below is what I've managed to come up with for determining the draw conditions. Doesn't seem to hold up in all cases though... Surely there's a simpler approach? PlayerScore orderedScores m scores.OrderByDescending(ps gt ps.score).Take(4).ToArray() 1stPlacePlayers.Add(orderedScores 0 .playerNumber) if (orderedScores 0 .score orderedScores 1 .score) 2 player draw 1st place 1stPlacePlayers.Add(orderedScores 1 .playerNumber) if(orderedScores 0 .score orderedScores 2 .score) 3 player draw 1st place 1stPlacePlayers.Add(orderedScores 2 .playerNumber) if(orderedScores 0 .score orderedScores 3 .score) 4 player draw 1st place 1stPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 1 .score orderedScores 2 .score) 2 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 2 .playerNumber) if (orderedScores 1 .score orderedScores 3 .score) 3 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 2 .score orderedScores 3 .score) 2 player draw 3rd place 3rdPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 1 .score orderedScores 2 .score) 2 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 2 .playerNumber) if (orderedScores 1 .score orderedScores 3 .score) 3 player draw 2nd place 2ndPlacePlayers.Add(orderedScores 3 .playerNumber) else if (orderedScores 2 .score orderedScores 3 .score) 2 player draw 3rd place 3rdPlacePlayers.Add(orderedScores 3 .playerNumber) |
0 | How to restrict the players movement win relation to screen bounds in Unity? (Without colliders) I am really enjoying making the switch to Unity. But here I have found one of those rare moments where it appears to make things more difficult (at least it is for me as I am crap at understanding the actual manual) Basically my 'player' is a space ship. It starts life at 0,0,0 world coordinates and I have been doing all the movement based off of that. (ie. Add force X to move left or right, and there is a constant Z speed which is done via rb.transform.Translate().) I want to restrict the movement on the X Axis, so in Libgdx id use something like if (player.position.x lt 0) player.position.x 0 if (player.position.x gt viewport.getX()) player.position.x viewport.getX() The thing is that wont work for me in Unity for several reasons (1. I dont know much about the viewport as I didnt create it. 2. the player.position is being affected by the rigidbody forces. AND i am working in world coordinates with the players position). As I said, the player is constantly moving forward on Z axis, so making colliders doesnt seem like the right choice for me. I'm pretty sure Unity devs would of put this in Unity v0.001 but I just cannot for the life of me find how to actually do it. (Any info I can find seems from like 2011 and also is pretty badly written code making this simple matter takes dozens of lines of code and some methods I'm hoping there is a Unity method already made, like player.transform.ScreenPosition or something but yeah I cannot find it!? Any help would be massively appreciated as always. |
0 | Exporting scene during gameplay to FBX In Unity is there a way to add a menu button during gameplay that allows the player to export the current scene as an fbx file? My googling and research shows that its possible to do this while developing the game but wondering if there is a way to add this functionality for the gameplay itself. Any suggestions on how if this can be done? |
0 | How can I make my tiles fall smoothly? I'm working on a Tile Based game and I can't figure out how to make my tiles fall down smoothly like in candy crush. All column tiles fall down at the same time. And spawn new like how many tile place if null. What I want Update 25.12.2015 But the my code works like this Update 26.12.2015 Hello Again, World Scale (x,y) World Scale OLD (10,10) World Scale NEW (10,11) Y 11 Tiles type Empty Now, when i click the random place like (5,7),above all blocks down to block.transform.pozition new Vector3(0, 1,0) It's working. But again, when i click same place (5,7) not working... I changed Y scale 10 to 11. Because, when i clicked tile, the tile will return to Y 11 position and fall down, how many tile place null. When Tiles state quot fallling down quot , the space between two blocks distance not more quot 0.01 quot . I do not know how to do. But I approached. I need to more improve this. Thanks... Pseudo code When I click the (4,7) coord, the tiles, tile(4,8) is smooth down the coord(4,7) tile(4,9) is smooth down the coord(4,8) tile(4,9) is generate new tile. What I have (Code not working properly ( ) World.Height 10 World.Widht 10 Tile X and Y get, protected set public void ColumnDown(int x , int yStart) if (IsColumnFull(x)) return for (int y yStart y lt World.Height y ) Yeni tile spawnla if (y 1 gt World.Height) continue Tile tile World.GetTileAt(x, y) Tile tile2 World.GetTileAt(x, y 1) GameObject go Tile GameObject.Find( quot Tile ( quot x quot , quot y quot ) quot ) GameObject go Tile2 GameObject.Find( quot Tile ( quot x quot , quot (y 1) quot ) quot ) if (tile ! null) if (go Tile null amp amp go Tile2 null) Debug.Log( quot go Tile NULL quot ) continue tile2 tile go Tile2.transform.position new Vector3(0, 1, 0) go Tile.name quot Tile ( quot x quot , quot (y 1) quot ) quot go Tile2.name quot Tile ( quot x quot , quot (y) quot ) quot |
0 | Not able to move quad wheel robot I am trying to move QWAD wheel robot, I have grouped the wheels separately and added wheels colliders for each wheel. The problem is that the wheels are moving but the robot is stationary. I have been stuck with this problem from many days. I am very new to unity3D and C scripting. At first I tried the concept of moving rigid body using car model and it is working perfectly fine. When I applied the same logic to QWAD wheel ROBOT is not woking as expeted, kindly help me out. Please find the code below using System.Collections using System.Collections.Generic using UnityEngine public class RoboMovemnt MonoBehaviour void Start() rb GetComponent lt Rigidbody gt () public void GetInput() m horizontalInput Input.GetAxis("Horizontal") m verticalInput Input.GetAxis("Vertical") private void Steer() m steeringAngle maxSteerAngle m horizontalInput FR Wheelwc.steerAngle m steeringAngle FL Wheelwc.steerAngle m steeringAngle private void Accelerate() RR Wheelwc.motorTorque m verticalInput motorForce RL Wheelwc.motorTorque m verticalInput motorForce if (m verticalInput 0) RL Wheelwc.brakeTorque brakeTorque RR Wheelwc.brakeTorque brakeTorque private void UpdateWheelPoses() UpdateWheelPose(FR Wheelwc, FR WheelT) UpdateWheelPose(FL Wheelwc, FL WheelT) UpdateWheelPose(RR Wheelwc, RR WheelT) UpdateWheelPose(RL Wheelwc, RL WheelT) private void UpdateWheelPose(WheelCollider collider ,Transform transform) Vector3 pos transform.position Quaternion quat transform.rotation collider.GetWorldPose(out pos, out quat) transform.position pos transform.rotation quat void HandBrake() if (Input.GetKey(KeyCode.Space)) IsBrake true else IsBrake false if(IsBrake true) RL Wheelwc.brakeTorque brakeTorque RR Wheelwc.brakeTorque brakeTorque RL Wheelwc.motorTorque 0 RR Wheelwc.motorTorque 0 else RL Wheelwc.brakeTorque 0 RR Wheelwc.brakeTorque 0 private void FixedUpdate() GetInput() Steer() Accelerate() UpdateWheelPoses() HandBrake() private float m horizontalInput private float m verticalInput private float m steeringAngle private Rigidbody rb private int Velocity public WheelCollider FR Wheelwc, FL Wheelwc, RR Wheelwc, RL Wheelwc public Transform FR WheelT, FL WheelT, RR WheelT, RL WheelT public float maxSteerAngle 30 public float motorForce 500 public bool IsBrake false public float brakeTorque 50000f |
0 | Unity Initializing class of a script not working I have been trying to find a solution for the last couple of hours so please hear me out. At first I got a NullReferenceException, which I resolved(?) by initializing the class first (This is my problem! I can't seem to initialize my class sucessfully). However, here are my next errors. I tried using the new keyword, which resulted in You are trying to create a MonoBehaviour using the 'new' keyword. Next I tried GetComponent lt gt (), which resulted in a CS0120, that I didn't know how to fix. The AddComponent lt gt (), resulted in a CS0103 The name AddComponent does not exist in the current context. What I tried next was GameObject.AddComponent lt gt (), which threw a CS0120, and gameObject.Addcomponent lt gt () which threw a CS0236. Here is my code for the class I am trying to initialize if it should be needed public class Dialogue MonoBehaviour public TextMeshProUGUI textDisplay public string sentences private int index public float typingSpeed public GameObject continueButton void Update() if (textDisplay.text sentences index ) continueButton.SetActive(true) public IEnumerator Type() foreach (char letter in sentences index .ToCharArray()) textDisplay.text letter yield return new WaitForSeconds(0.01f) public void NextSentence() continueButton.SetActive(false) if (index lt sentences.Length 1) index textDisplay.text "" StartCoroutine(Type()) else textDisplay.text "" continueButton.SetActive(false) Here is from where I tried to initialize public class Mace MonoBehaviour Dialogue dialogue gameObject.AddComponent lt Dialogue gt () private void OnTriggerEnter2D(Collider2D otherCollider) if (otherCollider.CompareTag("Player")) StartCoroutine(dialogue.Type()) |
0 | Networking assigning IDs to entities Maybe I'm asking dumb question, but this problems bothers me... So I have my networked game in Unity (client), and server written in C (without Unity). I Use ENet library for networking. Most of networked components are written by myself (lobby, components etc.). Server doesn't know about Unity entities like players, obstacles etc. In most cases I send message ("hide object with id 4") to the server, and server pass that message to other clients where they applied message information. What my problem is, how to assign proper IDs to networked objects, that will be the same across all players? What I do is that On all clients I get all components with specific network component (e.g. NetworkRigidbody) I sort all of objects using special comparer which compares based on component name with all parents appended to it ID is just an index in sorted array Above algorithm works, but I have a feeling that in normal games that problem is handled in other manner. I searched over Mirror, MLAPI and other libraries source code and I couldn't find how entity id is generated, especially when server is not Unity application. |
0 | Custom Unity launcher localization I would like to localize Unity launcher using own texts. At the very least I would like to change "play!", "quit", "Graphics" and "Input" to own arbitrary labels. How can I achieve that? |
0 | Unity Tilemaps Best practices I'm pretty new to Unity and I just finished some courses and tutorial found in the official documentation. I'm now in the process to apply what I learned so far using different assets from the ones provided with the tutorial, to see if I understood all the material. I'm trying to build a simple top down game with some free asset I found online. My tile palette is composed, among others, of tiles like these Now, in order to create something like this sorry for the quality, I recreated it in gimp since I'm not on the computer where I have Unity now I had to create three Tilemaps under the same Grid. The botton tilemap contains the grass (sort order 2), the middle one contains the fence (sort order 1) and the top one contains the house (sort order 0). My first question is given the tileset I have, is this the most efficient way to obtain what I needed? After having solved this problem I wanted to add a collider to the fence and to the house, but since they are on two different tilemaps I cannot use a composite collider to optimize the collider's layout. Is there another way to do this in a more efficient way? Instead of using tiles for quot interactable objects quot , should I use quot proper quot game objects instead? |
0 | What's the difference between Mathf.Lerp and Mathf.SmoothDamp I want to smoothly go from one value to a new one (moving a slider or changing color). I tried using both functions and they all basically give the same result. What is the difference between them and which one should I use? How I used SmoothDamp Show the HUD private IEnumerator ShowHUD() var HUDCanvasGroup GameObject.FindWithTag("HUD").GetComponent lt CanvasGroup gt () var alphaValue 1f var velocity 0f var time 0.30f yield return new WaitForSeconds(1.5f) Gradually fade in the canvas while (!Mathf.Approximately(HUDCanvasGroup.alpha, alphaValue)) HUDCanvasGroup.alpha Mathf.SmoothDamp(HUDCanvasGroup.alpha, alphaValue, ref velocity, time) yield return null HUDCanvasGroup.alpha 1 Since float is not accurate, manually set the alpha to 1 after HUDCanvasGroup.interactable true var blur GameObject.FindWithTag("BlurryCamera").GetComponent lt BlurOptimized gt () blur.enabled true How I used Lerp public static IEnumerator Dim() while (t lt 1) t Time.deltaTime 0.4f dimRend.material.color Color.Lerp(undimColor, dimColor, t) yield return null |
0 | In Unity, how do I correctly implement the singleton pattern? I have seen several videos and tutorials for creating singleton objects in Unity, mainly for a GameManager, that appear to use different approaches to instantiating and validating a singleton. Is there a correct, or rather, preferred approach to this? The two main examples I have encountered are First public class GameManager private static GameManager instance public static GameManager Instance get if( instance null) instance GameObject.FindObjectOfType lt GameManager gt () return instance void Awake() DontDestroyOnLoad(gameObject) Second public class GameManager private static GameManager instance public static GameManager Instance get if( instance null) instance new GameObject("Game Manager") instance.AddComponent lt GameManager gt () return instance void Awake() instance this The main difference I can see between the two is The first approach will attempt to navigate the game object stack to find an instance of the GameManager which even though this only happens (or should only happen) once seems like it could be very unoptimised as scenes grow in size during development. Also, the first approach marks the object to not be deleted when the application changes scene, which ensures that the object is persisted between scenes. The second approach doesn't appear to adhere to this. The second approach seems odd as in the case where the instance is null in the getter, it will create a new GameObject and assign a GameManger component to it. However, this cannot run without first having this GameManager component already attached to an object in the scene, so this is causing me some confusion. Are there any other approaches that would be recommended, or a hybrid of the two above? There are plenty of videos and tutorials regarding singletons but they all differ so much it is hard to drawn any comparisons between the two and thus, a conclusion as to which one is the best preferred approach. |
0 | Terrain (mesh) textures in Unity blurry? I've created a 3D mesh in blender which will be used as a terrain in Unity. Additionaly, I created a 900x900 texture which I'd like to apply as material to the mesh. However, unlike with the normal Unity terrain, the material is only blurry unrecognizable, not matter how many times I repeat the texture what import settings I set for the texture. Some googling brought up that it may have to do something with the shader, but I tried many with no results. current result texture |
0 | How would I use an object from another animation in Unity? So I have two different .blend files with two different animations. Let's call my aiming with a gun animation animation A, and my other .blend file with idle, run, and jump animations animation B. If I wanted to play the aiming clip from animation A with the Animation B animator, it just looks like my character wants to shake hands, since the gun doesn't appear in the animation. The aiming animation works if I play animation A with animation A's animator. How would I use the gun object from animation A when playing animation A in animation B's animator? Here is an image of what the animation looks like in the import settings (what i want) and in the actual game (what is happening which I don't want.) The top image is what I want and the bottom image is what is happening. Thanks in advance. |
0 | How to detect a pinch in Unity? How do I detect a pinch motion on Unity for an android or Iphone? I need to also know whether the player pinches a certain character or not. How do i do that? |
0 | How can I create a mesh of triangles made from the vertices of a polygon and contained within that polygon? I'm trying to programatically generate a mesh, given the vertices of a polygon, which is contained within that polygon. For example, starting with these points I would want to generate a mesh similar to this My first port of call would be a Delaunay triangulation, but having implemented this, I came up against the problem that this was not contained within the polygon, i.e. it produced a mesh like this My question then is, is there either an algorithm which produces the desired result rather than the Delaunay result (because I can't find one online), or a modification that I can make to the Delaunay triangulation algorithm that will fix this? I'm using the Bowyer Watson algorithm, by the way. Thank you! |
0 | Unity Transforming horizontal distance between two spriteRenderers to set UnityEngine.UI.Button width to this distance In my Unity scene, I have a couple of spriteRenderers and a UnityEngine.UI.Button called thisButton. The spriteRenderers are spread horizontally across my scene. I want to change the button width to span from the leftmost spriteRenderer to the rightmost spriteRenderer. To do this, I have subtracted the x Coordinate of the rightmost spriteRenderer (fRightEndingPosition) from the x Coordinate of the leftmost spriteRenderer (fLeftStartingPosition). float fLeftStartingPosition leftmostSpriteRenderer.transform.position.x float fRightEndingPosition rightmostSpriteRenderer.transform.position.x float fButtonTargetWidth fRightEndingPosition fLeftStartingPosition Then, I try to set the width of thisButton to the value of fButtonTargetWidth by doing RectTransform buttonSize thisButton.GetComponent lt RectTransform gt () buttonSize.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fButtonTargetWidth) However, when I try to use this as the width of my button, the result is not correct. I am pretty sure this has something to do with different types of coordinates being used for the spriteRenderers and the button (world, screen, viewport, etc.), but I haven't been able to figure this out on my own. In one specific example fLeftStartingPosition is 1.1, and fRightEndingPosition is 1.1. In my scene, a button that spans this distance has a width of roundabout 40 on its RectTransform. So clearly, setting the width of this RectTransform (buttonSize) to fButtonTargetWidth (2.2) in code results in a button that is way to narrow. In fact, after setting it's width to 2.2, it is not visible at all. How do I transform this distance of 2.2 to the desired width of roundabout 40, in a way that this distance would be transformed correctly, no matter what the actual value of fButtonTargetWidth is? |
0 | Why does Unity editor freeze up if left unfocused for a while? If Unity editor loses focus for too long (such as because I'm tabbed out into my browser or Blender), then I find that it needs about 15 30 seconds until I can interact with it again when it gets focus again. It seems like it is paused. Is this a bug or my fault? |
0 | Can a MonoBehaviour be a private inner class? I want to use a private inner class MonoBehaviour as part of the internal implementation of a class (also a MonoBehaviour). Reduced to the essentials public class OuterClass MonoBehaviour public void SomeMethod(GameObject go) go.AddComponent lt InnerClass gt () private class InnerClass MonoBehaviour This appears to be all working absolutely fine, with no errors or warnings. But it also appears to violate the statement in the Unity documentation that The class name and file name must be the same to enable the script component to be attached to a GameObject. Is this a problematic violation of that rule? If so, what are the problems? I am aware that it means the script is not visible in the Editor, but that's exactly what I want it should never be added by anything other than its enclosing class. |
0 | How to prevent a duplicated shadow? It's a blob shadow which is built in Unity's standard asset package. As you see in the figure below, a shadow that is created by the Unity Projector is duplicated at the floor below. How can I prevent this duplicated shadow? |
0 | How can I create a "rain drops on camera lense" effect with the HDRP? I did follow this tutorial https www.youtube.com watch?v OG7zyogrUTs amp t 115s but I did not made it cause I am using HDRP and they are not using HDRP so the problem is I can't use the normal materials being in HDRP mode help me if there is any way to do so or if there is another good video please. In picture 1 I want these white particles on camera lens looks like the second picture I want water texture on these white particles. |
0 | Restrict render in Blender is not working I click "Restrict renderability", so that everything except the item I want to export is grayed out. However, it still exports lights and everything when I import it into Unity. How can I fix this? |
0 | Unity3D Making heavy calculation on separate thread So, I've created a program with Kinect as its input. As you know, Kinect will send the data 30 frame per second. I have a model that will mimic Kinect's input motion, so on Update() I read the motion from Kinect. The problem is, on Update(), I've done a heavy computational algorithm. It makes the system lag and freezing. I've tried to do the calculation every 60 frames instead of each frame, but the system still got lag. void Update() ... GET DATA FROM KINECT frame new SkeletonRecorded() frame.root.rotation skeletons kinect2SensorID, playerID .root.rotation ... frame.rightShoulder.position skeletons kinect2SensorID, playerID .rightShoulder.position frames.Add(frame) if (frames.Count gt 60) CALLING THE CALCULATION METHOD (Here is the heavy part begin) comparatorClass.GetSkeletonData(frames) frames.Clear() The above code is just small parts of the Update() method (I cut it short for convenience). So, how should I call the GetSkeletonData() method without making the interface lag? |
0 | Specular intensity not imported from Blender into Unity For my current project I'm using diffuse materials for my models in Blender but I do not want any Specular Intensity so I've set that to 0. Yet in Unity there is still a specular highlight and the material has a Smoothness of 0.5. Does Unity actually read Specular Intensity or am I missing some crucial detail? I haven't been able to find any details on what the .blend import actually reads and I can see a setting called Glossiness in the .mat files created by Unity is set to 0.5. |
0 | Input events slow on unity Update function I have this running on the Update() on Unity. I am trying to create a page swipe feature on my game, but the problem is there is a half second delay when printing "dragging" to "end drag" when I release the mouse. Does anyone have a method that will register input events faster? void Update() if(isDragOn) if(Input.GetMouseButton(0)) print ("dragging") moveContainers((Input.mousePosition.x mouseLastPosition) 0.01f) mouseLastPosition Input.mousePosition.x else if(Input.GetMouseButtonUp(0)) print ("end drag") isDragMoved false isDragOn false endDrag() else if(Input.touchCount gt 0) if(Input.GetTouch(0).phase TouchPhase.Moved) moveContainers(Input.GetTouch(0).deltaPosition.x) else if(Input.GetTouch(0).phase TouchPhase.Ended) isDragMoved false isDragOn false endDrag() |
0 | Project transfer, will re importing all my models damage my project at all? Recently I had to transfer my Unity game project to another computer and downloaded the same version of Unity I was using for my 3D project and checked that all the files and folders were in the same place and everything. When I start up the game though my models have vanished and in the hierarchy it just says missing prefab instead of telling me what it was, like it used to if I'd move a model to another folder or something like that. It shows all my files there and I was about to reimport them all but I got a warning that said "Rebuilding assets is only if your project has been corrupted due to an internal Unity bug. It can take several hours to complete, depending on the size of your project. Please submit a bug report detailing the steps leading up to here." I am sure that re importing all my models will fix this but I want to ask if this will have any negative effects on my project or possibly damage anything? This game is extremely important to me and I've been working on it for the past 3 years(being self taught which is why it's taken so long and I'm still learning) Thank you guys in advanced! D |
0 | How can I create a random deck of 7 cards every time they are all used? I'm trying to create a Tetris like game in C (Unity) and I've run into quite a problem on how I can generate 7 cards (tetrominoes) of which none are the same and when I run out of cards, I regenerate more. I can kind of see how I could do the regeneration part but I'm very unsure on getting 7 cards for which none are the same. |
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 | Splitting a prefab into two These hands are in a single prefab. I want to split this into two so that I can make bones for each of them separately and use them with leap motion. How can make each of these hands as a single prefab? Also, I'm using Unity 2018. |
0 | Wait until a method finish I'm using Firebase Realtime Database and I'm trying to compare if a name is available to other user. The problem is the method finish before the Firebase's method finish its execution. Here is the code private bool IsNameAvailable (string nick) bool available false FirebaseDatabase.DefaultInstance.GetReference ("users").OrderByChild ("name").EqualTo (nick).GetValueAsync ().ContinueWith (task gt if (task.IsFaulted) Debug.LogError ("A error encountered " task.Exception) else if (task.IsCanceled) Debug.LogError ("Canceled ...") else if (task.IsCompleted) DataSnapshot snapshot task.Result available (snapshot.GetValue (true) null) ) return available This line executed before the Firebase's method end. What can i do?? Thanks in advance. |
0 | How to write depth texture and read values from it I am new in Unity and specializing in another field. But now I have to rapidly study it for a new project. I will be very thankful if anyone explain me how to read values of the depth buffer. I wrote a shader, which creates depth image Shader quot Custom MyDepthShader quot Properties MainTex ( quot Texture quot , 2D) quot white quot SubShader No culling or depth Cull Off ZWrite Off ZTest Always Pass CGPROGRAM pragma vertex vert compile function vert as vertex shader pragma fragment frag compile function frag as fragment shader include quot UnityCG.cginc quot struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION v2f vert (appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv v.uv return o sampler2D MainTex sampler2D CameraDepthTexture fixed4 frag (v2f i) SV Target float depth tex2D( CameraDepthTexture, i.uv).r depth Linear01Depth(depth) depth depth ProjectionParams.z return depth ENDCG Now I need to get depth information into a texture and save float values of this texture to for example txt file for further processing. I didn't found yet answer to this question after two days of googling and reading guides. For testing this shader I am using OnImageRender(RT src, RT dst, material). |
0 | Why can't I rotate anything to be "more than 360 degrees or less than 0 degrees"? I've been trying to make an animation in Unity, but most assets already come bundled with everything facing at 0 degrees, not to say it's a bad thing. However, the problem I'm facing is that the animation keyframes aren't playing out correctly. When this is done with raw measurements (simply dragging the XYZ rotations), negative and greater than 360 degree angles are taken account. But then again Unity could be simply remapping them, whcih is not the case. For example, the prop robotArm prefab, found within Unity's Robot Factory asset pack has a rotator script that simply rotates the whole thing along the Y axis. void OnFixedUpdate() transform.Rotate (new Vector3(0, rotateSpeed Time.deltaTime,0)) Meaning that after slightly more than a full revolution, the Y rotation value should be more than 360 degrees, which it does end up becoming... Eventually. Thinking that was possible, I tried to mimic this behavior by making the arm rotate 720 degrees (twice) in an animation file (this is not using the rotator.cs script attached to the body in the example above). Instead, all I ended up was the arm's body staying still as 720 is the same as... 0 degrees in rotation changes. So, I tried a second experiment trying to rotate from 359 degrees to 1 degree (or 1 to 1 degree). Just like above, it didn't go to plan. When the animation is run, it simply runs from 359, through every angle in between before reaching 1, instead of 359, 360 (0) and 361 (1). If you don't get what I mean, see the diagram below. So, I was wondering, is there a way to allow for such rotation to be defined in an animation curve? Every time I try doing it, any value greater than 360 (or lesser than 0) is replaced by its co terminal counterpart that's between 0 and 359.999999...999. |
0 | Spawning random items to drop from the top of the screen I'm wondering how to make specific random objects drop. In my case, from the top of the screen. I have 16 objects, named recycle items 0 through recycle items 15. IEnumerator CreateRoutine() while (true) yield return new WaitForSeconds(3) CreateItems0() private void CreateItems0() Vector3 pos Camera.main.ViewportToWorldPoint(new Vector3(UnityEngine.Random.Range(0.0f,1.0f),1.1f,0)) pos.z 0.0f Instantiate(recycle items 0, pos, Quaternion.identity) |
0 | Unity Import a mesh that only has vertex and edge data but no faces I am working on a game that requires meshes that only have edges and vertices but no faces. In blender, you can make a mesh with only edges and vertices, but if you export it to FBX or OBJ, once it is imported into Unity, the resulting prefab has no mesh data linked to it. The prefab has no MeshFilter. It's as if I imported an mesh with absolutely no mesh data. For example, if I create a plane in Blender and then delete the face but leave the edges and vertices, and then export as OBJ, I can open the OBJ in a file editor. This is a square with no faces Blender v2.78 (sub 0) OBJ File '' www.blender.org mtllib egdes.mtl o Plane v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 v 1.000000 0.000000 1.000000 l 3 1 l 1 2 l 2 4 l 4 3 So it appears that OBJ actually does export with the correct mesh data, however, it seems that Unity does not know how to import an OBJ if there are no faces. Does anyone know if anyone has come up with a solution to this problem yet? If not, I guess I'll just have to write my own parser. If that's the case, does anyone know if there is a way to extend or override Unity's built in OBJ parser? |
0 | How to find intersections using MapBox Unity SDK I'm currently using MapBox's Untiy SDK, which allows me to render 3D Buildings and roads. I want to place a gameobject at each intersection in an area. But, I'm having trouble finding a good way to do that. The roads are gameobjects attached to a quot Tile quot gameobect. The roads have a local position 0,0,0 with meshes on them that dictate their rendered position. A long road can cross multiple tiles, and thus the same quot road quot may exist as two or more gameobjects on two or more tiles. The Mesh itself is rectangular prism extruded from some line data by Mapbox. I have tried to use colliders with no success. For one, in order to get points of intersections between two colliders, they need to have rigidbodies attached to them and it's too expensive to do that, since there are hundreds of roads. Furthermore, many of the meshes have bad verts in them, which wont allow mesh colliders to work anyway, and box colliders wont work for non straight roads. Some road meshes are sprawling, twisting, and winding and could quot collide quot with a number of roads without actually touching them. I am not above brute force looping through every mesh's vertex in every tile to detect intersections, but I am as of yet unsure of the best way to do this or if it is necessary. I am also not sure if MapBox has some hidden feature for this the way Google Maps Unity SDK allows for access to the road lattice and intersections. If I could get some info about the line that represents the road, it would be easy to tell if roads overlap. The best way I can figure is to loop through the verts on a road to determine if the lines between verts overlap that of the roads within the same time, but am not sure if that is the best course of action |
0 | Spawning prefab when other prefab appears Im trying to make a bottle spawn when it is broken. This is the code that makes that public class romperobjetos MonoBehaviour public GameObject BrokenBottle public float breakVelocity 5f public GameObject NoBrokenBottle public bool rompible false public Vector3 oldPosition public Quaternion oldRotation public bool botellarota false public void Start() Use this for initialization public void Update() Debug.Log(NoBrokenBottle.GetComponent lt Rigidbody gt ().velocity.magnitude) if (NoBrokenBottle.GetComponent lt Rigidbody gt ().velocity.magnitude gt breakVelocity) rompible true else rompible false public void OnTriggerEnter(Collider other) if ((other.gameObject.name "Plane") amp amp (rompible)) oldPosition NoBrokenBottle.transform.position oldRotation NoBrokenBottle.transform.rotation Debug.Log("vamos bien") BreakBox() public void BreakBox() Instantiate(BrokenBottle, oldPosition, oldRotation) Debug.Log("se rompe") NoBrokenBottle.SetActive(false) botellarota !botellarota The broken bottle prefab has a boolean variable that is true when it appears, but the unbroken bottle doesn't instantiate. This is the script for the spawn public class SpawnBotellas MonoBehaviour public Transform spawnPoints public GameObject whatToSpawnPrefab public GameObject whatToSpawnClone public bool botella1rota false Use this for initialization void SpawnAlgo() whatToSpawnClone 0 Instantiate(whatToSpawnPrefab 0 , spawnPoints 0 .transform.position, Quaternion.Euler(0, 0, 0)) void Update() botella1 if (GameObject.Find("alidobas blanco roto").GetComponent lt alidobasrota gt ().alidobasblanco) Debug.Log("asdkj") whatToSpawnClone 0 Instantiate(whatToSpawnPrefab 0 , spawnPoints 0 .transform.position, Quaternion.Euler(90, 0, 0)) as GameObject Sorry for my bad English and thanks. |
0 | How do I get current emission intensity of a material in code? I'm unable to find how can I get current intensity level of emission in Unity. Is there some kind of method that can return its value? I need it to complete my algorithm's formula current color (intensity 10) 20 |
0 | UI Bug After UI has interaction I am making a 3rd person game for pc. Space, of course, makes the player jump in game. For some reason if I interact with my menu at all and then press space it will open my menu back up. This doesn't happen if I don't interact with the UI first though. I don't know if this is a bug or what but my code does not contain anything that would take input from the keyboard in general so the space bar interacting with it doesn't make sense. Has anyone seen this issue before? |
0 | Animator.SetBool am I supposed to call it only when its value changes? I've searched around the web for a while, but didn't manage to find anything about it. Despite using Animator in several projects so far, I've never been in this exact situation, so I'm unsure what to do. Does calling Animator.SetBool have any performance issue, so that I'd better call it only when its value has changed, or when its value doesn't change it's so quick that I can call it every frame? Keep in mind that, due to the nature of this question, I don't care if it's slow when I change its value, I only care if it's slow when it's false and I call it to set it to false again (same thing for true ofc). |
0 | Sort Textures by name before looping through them im using a system to get textures from the device persistent data path and assign them to an array in order to show them in the game scene. So far everything works as expected, images are getting pulled into the array and are selected based on the level index. My issue is that on some android devices each time the image is loaded its either random or its a different image than it should be. public void LoadTextureArray(string dirname) var fileNames Directory.GetFiles(Application.persistentDataPath quot quot dirname quot quot , quot .jpg quot ) source new Texture2D fileNames.Length int index 0 foreach (var fileName in fileNames) source index LoadTextureFromPath(fileName) source index .name fileName index public Texture2D LoadTextureFromPath(string path) if (string.IsNullOrEmpty(path)) Debug.LogError( quot Texture path is null or empty quot ) return null if (!File.Exists(path)) Debug.LogError( quot File not found path quot ) return null byte bytes File.ReadAllBytes(path) Texture2D texture new Texture2D(2048, 2048, TextureFormat.RGB24, false) texture.LoadImage(bytes) Debug.Log( quot success quot ) return texture and i assign them based on another variable with this code here if (LevelSystemManager.Instance.CurrentLevel lt source.Length) selectedText source LevelSystemManager.Instance.CurrentLevel DifficultySet() Debug.Log( quot selected Texture Name is quot selectedText.name) The LoadTextureArray function is called on Awake and on Start i do the assignment based on that index. Now in both Unity editor and my phone everything works fine and no matter how many times i load the level its the same image. Whereas on my wifes it either skips a couple of images from the array (displaying the 5th for instance as index 1) or everytime i open the level i see a different one! Thank you! Edit it seems my problem is that i need to sort them out before assigning them to that array so any help would be appreciated! |
0 | How to implement a button when the player is in the trigger I have implemented this code and it works but i wanna make this work only if i enter the trigger and press the UI button. Right now it is changing scene automatically so, i want to press the button and then change scene. I know how to do this for PC game but not on Android game. I hope you can give me a hand. Script public class ButtonScript MonoBehaviour public Button btn private bool door false public bool hasCollided false public void Update () if(door true) SceneManager.LoadScene("InventoryScene") SceneManager.LoadScene ("Scene1AToBathW") Application.LoadLevel("Courtyard1F") gameObject.transform.position new Vector3(x,y,z) public void OnTriggerEnter(Collider other) if(other.tag "Player") btn.gameObject.Setactive(true) door true hasCollided true public void OnTriggerExit(Collider other) if(other.tag "Player") btn.gameObject.Setactive(true) door false hasCollided false |
0 | Shaderlab and Cg API reference I am looking for definitive information on Shaderlab's API and the Cg language. The documentation I have found so far has been by way of example programs rather than a definition of APIs. Also, searching for a specific API term such as Sampler2D didn't turn up anything definitive. What reference documentation is available or possibly documentation of precursors to Shaderlab and Cg? |
0 | Why does ForceMode.VelocityChange work but not Rigidbody.velocity ... in script? I have a FPS movement script that I created that has a jump function that looks like this public void Jump() if (jumpAble amp amp grounded) jumpAble false gameObject.GetComponent lt Rigidbody gt ().velocity (Vector3.up jumpForce Time.deltaTime) For some reason, this does not make the player jump. However, replacing the .velocity ... to gameObject.GetComponent lt Rigidbody gt ().AddForce(Vector3.up jumpForce Time.deltaTime, ForceMode.VelocityChange) makes the player jump. Why is this? I'm under the impression that the two are essentially the same thing, but is there a slight difference? Also, not sure if it affects the function, but this is the whole script public class Player Movement MonoBehaviour public Transform camera public Transform groundCheck public float groundDistance 0.4f public LayerMask groundMask public bool grounded public GameObject joystick public bool isWalking false public bool isRunning false public float walkForce 12f public float runForce 30f public float jumpForce public bool jumpAble true public GameObject playerRotationHandler public float cameraTouchSensitivity public Animator animator Update is called once per frame void Update() grounded Physics.CheckSphere(groundCheck.position, groundDistance, groundMask) if (grounded) jumpAble true Vector3 direction joystick.GetComponent lt Joystick gt ().inputDirection.x transform.right joystick.GetComponent lt Joystick gt ().inputDirection.y transform.forward if (isRunning) gameObject.GetComponent lt Rigidbody gt ().velocity (direction runForce Time.deltaTime) else if (isWalking) gameObject.GetComponent lt Rigidbody gt ().velocity (direction walkForce Time.deltaTime) else gameObject.GetComponent lt Rigidbody gt ().velocity Vector3.zero public void Jump() if (jumpAble amp amp grounded) jumpAble false gameObject.GetComponent lt Rigidbody gt ().velocity (Vector3.up jumpForce Time.deltaTime) gameObject.GetComponent lt Rigidbody gt ().AddForce (Vector3.up jumpForce Time.deltaTime, ForceMode.VelocityChange) public void Rotate(float xMoveValue, float yMoveValue) float xRotation Mathf.Atan2(yMoveValue, cameraTouchSensitivity) Mathf.Rad2Deg float yRotation Mathf.Atan2(xMoveValue, cameraTouchSensitivity) Mathf.Rad2Deg playerRotationHandler.transform.Rotate(xRotation, 0, 0) transform.Rotate(0, yRotation, 0, Space.World) if (playerRotationHandler.transform.localEulerAngles.x lt 300 amp amp playerRotationHandler.transform.localEulerAngles.x gt 60) if (xRotation lt 0) playerRotationHandler.transform.localEulerAngles new Vector3(300, playerRotationHandler.transform.localEulerAngles.y, 0) if (xRotation gt 0) playerRotationHandler.transform.localEulerAngles new Vector3(60, playerRotationHandler.transform.localEulerAngles.y, 0) |
0 | How to reset scene (stage1) when selecting it from Level stagemain menu Good day I have a problem when the player finish stage 1 the screen look like this Then going back to selecting level When I try to play the stage 1 again. I want to reset the stage 1 so i can play it again. I only use Scene.LoadScene("stage1") in main menu to go to stage1 and Scene.LoadScene("mainmenu") to back to main menu |
0 | Unity, Pixel Perfect and Scaling I am totally stuck on with pixel perfectness of the game. I have tried a few pixel perfect camera assets, but they have lots of issues considering scalability. is it normal that these cameras zoom in and out, instead of scaling the camera screen when using different resolutions for the game. Because this is a huge problem for me, cause i need to make a game for aspect ratio of 16 10, and every resolution that has the same aspect ratio is needed to scale it correctly keeping the pixel perfectness. The ortographic camera size is dependent of screen width (width PPU 2) So it always zooms in or out with different resolutions. Question is Is there a way to make it scale the game sprites instead of zooming the view? |
0 | How can I move number of objects between two points with random speed? In the Hierarchy I have a Cube and the script is attached to the cube. And I also have in the Hierarchy two spheres as waypoints. public class WP MonoBehaviour public Transform waypoints public float movingSpeed GameObject allLines GameObject duplicatedPrefabs private void Start() allLines GameObject.FindGameObjectsWithTag("FrameLine") DuplicatePrefabEffects(allLines.Length) duplicatedPrefabs GameObject.FindGameObjectsWithTag("Duplicated Prefab") private void DuplicatePrefabEffects(int duplicationNumber) for (int i 0 i lt duplicationNumber i ) var go Instantiate(prefabEffect) go.tag "Duplicated Prefab" go.name "Duplicated Prefab" private void MoveDuplicated() for (int i 0 i lt duplicatedPrefabs.Length i ) duplicatedPrefabs i .transform.position Vector3.Lerp(pointA.position, pointB.position, movingSpeed Time.deltaTime) void Update() MoveDuplicated() The duplicatedPrefabs are moving very very fast no matter what value I put for movingSpeed and then they are all stuck in the second waypoint and seems like moving on very specific small area on the second waypoint. What I want to do is to move them smooth slowly between the two waypoints and with random speed range from each object. For example one will move at speed 1 the other on speed 20 third on speed 2. |
0 | Clone gameobject on drag without having to click a second time I have a standard Cube gameObject (with a BoxCollider and my CubeController.cs script) in my scene and I want to be able to click and drag on it to instantiate a new cube prefab (with a BoxCollider and my DragController.cs script) which then follows the mouse. I have it nearly working but when the new cube prefab is instantiated at the same position as the clicked cube (but 10 bigger) you have to then click the new instantiated object again to begin dragging it. I have a debug line printing 'Prefab created' in DragController.cs so the prefab must be sensing that the mouse button is still down. How can I do it so you click the original cube then the new prefab is created and draggable without having to click again? CubeController.cs placed on original Cube gameobject using UnityEngine public class CubeController MonoBehaviour RaycastHit hitInfo Ray ray public GameObject CubePrefab private bool canCreate true Update is called once per frame void Update() if (Input.GetMouseButtonDown(0)) ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hitInfo)) GameObject objectHit hitInfo.transform.gameObject if (objectHit.tag "Cube") createCubePrefab() void createCubePrefab() if (canCreate) canCreate false GameObject newCube Instantiate(CubePrefab, hitInfo.transform.position, Quaternion.identity) newCube.transform.localScale new Vector3(1.1f, 1.1f, 1.1f) DragController.cs placed on Cube prefab that is going to be instantiated using UnityEngine public class DragController MonoBehaviour private Vector3 screenPoint private Vector3 offset Start is called before the first frame update void Start() if (Input.GetMouseButtonDown(0)) Debug.Log("Prefab created") void OnMouseDown() screenPoint Camera.main.WorldToScreenPoint(gameObject.transform.position) offset gameObject.transform.position Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)) void OnMouseDrag() Vector3 cursorPoint new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z) Vector3 cursorPosition Camera.main.ScreenToWorldPoint(cursorPoint) offset transform.position cursorPosition |
0 | GUI.DrawTexture problem in Unity I'm having a problem with GUI.DrawTexture() and I'm looking an alternative function to draw 2D Texture Images. The problem I have is that my textures draw above all other objects and when my camera moves, the images move with the camera, keeping their relative position inline with the cameras position. using System.Collections.Generic using System.Drawing using System.Drawing.Imaging using UnityEngine public class AnimatedGifDrawer MonoBehaviour public string loadingGifPath public float speed 1 public Vector2 drawPosition List lt Texture2D gt gifFrames new List lt Texture2D gt () void Awake() var gifImage Image.FromFile(loadingGifPath) var dimension new FrameDimension(gifImage.FrameDimensionsList 0 ) int frameCount gifImage.GetFrameCount(dimension) for (int i 0 i lt frameCount i ) gifImage.SelectActiveFrame(dimension, i) var frame new Bitmap(gifImage.Width, gifImage.Height) System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, Point.Empty) var frameTexture new Texture2D(frame.Width, frame.Height) for (int x 0 x lt frame.Width x ) for (int y 0 y lt frame.Height y ) System.Drawing.Color sourceColor frame.GetPixel(x, y) frameTexture.SetPixel(frame.Width 1 x, y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)) for some reason, x is flipped frameTexture.Apply() frameTexture.LoadImage. gifFrames.Add(frameTexture) void OnGUI() GUI.DrawTexture(new Rect(drawPosition.x, drawPosition.y, gifFrames 0 .width, gifFrames 0 .height), gifFrames (int)(Time.frameCount speed) gifFrames.Count ) The code above is designed to draw animated GIFs using System.Drawing.dll in Unity |
0 | Why the canvas text is gray and not really white? This script change the text color to white using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DisplayInfo MonoBehaviour public string myString public Text myText public float fadeTime public bool displayInfo false Use this for initialization void Start() if (myText null) Debug.LogError(myText " Is null please add Text component !") if (myString "") Debug.LogWarning(myString " Is empty, No text will be display.") myText.color Color.clear Update is called once per frame void Update() FadeText() void FadeText() if (displayInfo) myText.text myString myText.color Color.Lerp(myText.color, Color.white, fadeTime Time.deltaTime) else myText.color Color.Lerp(myText.color, Color.clear, fadeTime Time.deltaTime) This is the script i'm using with the DisplayInfo using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class DetectInteractable MonoBehaviour public Camera cam public float distanceToSee public string objectHit public Image image public bool interactableObject false public DisplayInfo displayInfo public Canvas canvas private RaycastHit whatObjectHit private void Update() Debug.DrawRay(cam.transform.position, cam.transform.forward distanceToSee, Color.magenta) if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee)) if (whatObjectHit.collider.gameObject.tag "Interactable") image.color Color.red objectHit whatObjectHit.collider.gameObject.name interactableObject true displayInfo whatObjectHit.collider.gameObject.GetComponent lt DisplayInfo gt () displayInfo.displayInfo true else image.color Color.white if (displayInfo ! null) displayInfo.displayInfo false else image.color Color.white if (displayInfo ! null) displayInfo.displayInfo false When it's "Interactable" then i display the info about this object. The DetectInteractable is attached to the Player (FPSController) in the hierarchy And on each "Interactable" item i attach the script DisplayInfo For example the door And this is the editor screenshot before running the game Display Infomration is Canvas. The Text i set it's color to white in the inspector. But when running the game the text i see on objects is gray and i see that on the inspector the white is becoming gray On the game view window there is a text Security Door in fray it's hard to see it. It should be in white and bright enough to see it clear |
0 | Why does my Outlined Diffuse 3 shader seem "detached" at a distance? I'm using the Outlined Diffuse 3 shader from Unity and I'm having a problem with it the outline looks great when the camera is near the object, but at a distance, it looks detached. From nearby (looks good) From afar (looks bad see the shelf and books) How can I fix this graphical anomaly? |
0 | How can I make outline shader like "Life is Strange"? I want to make sketch shader like life strange. shader has two part 1.animated dashed line 2.noisy outline I like to know how can I make noisy outline? see outline of objects First I tried to make outline by copying of incoming vertex data and scaled according to normal direction then Cull Back.but I think it's something like Image effect because outline sometimes move inside of object. anyway I will appreciate if someone help me to Implement this shader ) What I tried I used edge detection and animate it by vertex shader but this isn't good like above gifs. |
0 | Why in the dialogue system it's showing in the conversation only 2 sentences and not the whole 3 sentences? The first script the manager is attached to new empty gameobject I want the conversation to start automatic when running the game so i'm calling the method TriggerDialogue in the manager using System.Collections using System.Collections.Generic using UnityEngine public class DialogueManager MonoBehaviour public DialogueTrigger dialoguetrigger private Queue lt string gt sentences Use this for initialization void Start () sentences new Queue lt string gt () dialoguetrigger.TriggerDialogue() DisplayNextSentence() public void StartDialogue(Dialogue dialogue) Debug.Log("Starting conversation with " dialogue.name) sentences.Clear() foreach(string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() public void DisplayNextSentence() if (sentences.Count 0) EndDialogue() return string sentence sentences.Dequeue() Debug.Log(sentence) void EndDialogue() Debug.Log("End of conversation.") Next the DialogueTrigger using System.Collections using System.Collections.Generic using UnityEngine public class DialogueTrigger MonoBehaviour public Dialogue dialogue public void TriggerDialogue() FindObjectOfType lt DialogueManager gt ().StartDialogue(dialogue) Last the Dialogue using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class Dialogue public string name TextArea(3, 10) public string sentences In the editor I filled the all 3 TextAreas each one with a sentence. Hello world Hi everyone I have woke up When running the game it's showing only to the Hi everyone it's not showing the I have woke up. And it also not showing the "End of conversation." in the log. |
0 | Ignore UI elements when clicking to move I have a click to move character that uses a Nav Mesh Agent and I want to ignore clicks that are made on UI elements. For example, I don't want clicking around in my inventory to move my player to the target under the inventory. The relevant part of the move script is very simple. if (Input.GetMouseButton(0) amp amp !playerHealth.isDead) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) navMeshAgent.destination hit.point I would think that this is a common question raised among beginner developers or that it would be covered in beginner courses, but I can't seem to find the info I'm looking for when Googling around, so I'll ask it here. So how do I get my Nav Mesh Agent to ignore clicks made on a particular UI element? How about ignoring clicks made to any and all UI elements? Thanks. |
0 | Limit a scrollbar's OnValueChanged to full step intervals only So I have done some research on the matter but I can't find anything. I created a UI scrollbar and asigned 10 steps to it.Then I noticed that the values of the scrollbar does not change in reference of the handle's steps but in reference of the pointer's position(like a slider).That seriously slows down the performance since it has a lot more to process "onValueChanged" and it is unnecessary for what I am trying to achieve. The values of the steps should go step 1 0.1(1),step 2 0.2(2) etc.I need to get these values and nothing in between or the step that the handle is currently on. How can I do that ? |
0 | How to transition between "rooms" virtual cameras on a button press? I'm trying to make a game that navigates like the example here I'd like it so that after combat, the player can push the button corresponding with an exit (left, right, up, down) and navigate like in this game. Also I eventually hope to randomize each run of the game so it would hopefully have some flexibility outside of being hard baked. I've seen examples of it being done with a player object and a collider, but the player won't actually be moving their character. I like this style of navigation because I think it still provides the joy of exploration for the player, but is more friendly of a navigation system for a novice like me. How would I implement something like this? |
0 | How do I load Player position as new gameobject? I want to make game like time travel, the player has the ability to go to the future by limited time, for that, I want to add some game mechanic like save the player position. Additional information ignore the red text. When pressing the button the player will create a new platform and immediately teleport to the original position. After the player teleported, the player will save the new platform as the new teleport position. after 2 seconds or pressing a button. the new platform will disappear and the player will return to the platform position. I have this playerController Script and I already implement the save position, but I don't know how to make it like what I explain. public Rigidbody2D theRB public float speedMovement public GameObject prefabGameObject Space(10) private BoxCollider2D boxCollider2D SerializeField private LayerMask GroundMask public float jumpVelocity Space(10) public float past public float future Space(10) public float hor Start is called before the first frame update void Start() theRB gameObject.GetComponent lt Rigidbody2D gt () boxCollider2D transform.GetComponent lt BoxCollider2D gt () Update is called once per frame void Update() PlayerPosSaveLoad() PlayerMovement() PlayerJump() public void PlayerMovement() hor Input.GetAxis( quot Horizontal quot ) if (hor gt 0 hor lt 0) theRB.velocity new Vector2(hor speedMovement Time.deltaTime, theRB.velocity.y) if (hor gt 0) transform.localScale new Vector2(1f, transform.localScale.y) Animation Debug.Log( quot ToTheright quot ) else transform.localScale new Vector2( 1f, transform.localScale.y) Animation Debug.Log( quot ToTheLeft quot ) public void PlayerJump() animation if (isGrounded() amp amp Input.GetKeyDown(KeyCode.Space)) theRB.velocity Vector2.up jumpVelocity public bool isGrounded() float extraHeighText .1f RaycastHit2D raycast2d Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.down, boxCollider2D.bounds.extents.y extraHeighText, GroundMask) Color raycolor if (raycast2d.collider ! null) raycolor Color.green else raycolor Color.red Debug.DrawRay(boxCollider2D.bounds.center, Vector2.down (boxCollider2D.bounds.extents.y extraHeighText), raycolor) return raycast2d.collider ! null SerializeField private Vector2 saveThisPosition public void PlayerPosSaveLoad() if (Input.GetKeyDown(KeyCode.E)) saveThisPosition transform.position SpawnGameObject() if (Input.GetKeyDown(KeyCode.Q)) SwitchWithsavedPosition() Destroy(prefabGameObject) private void SwitchWithsavedPosition() Vector2 temp transform.position transform.position saveThisPosition prefabGameObject.transform.position temp public void SpawnGameObject() Instantiate(prefabGameObject, transform.position, transform.rotation) And this is the Camera Script because connected with the player. lang cs public Transform Player Start is called before the first frame update void Start() Update is called once per frame void Update() transform.position new Vector3(Mathf.Clamp(Player.position.x, 7.3f, 7.3f), Mathf.Clamp(Player.position.y, 1f, 2f), transform.position.z) |
0 | Unity adding objects through script to scrollview (SetParent) Objects overlap I need to add X objects to a scrollview. I do it like this GameObject statsObject Instantiate(instance.statsObjectPrefab) statsObject.transform.SetParent(statsParent.transform) statsParent is the content container if the scrollview. Scrollview Viewport Content This is statsParent In the pause I see that then objects are added successfully, but they all overlap and no scrollbar is visible. The content has a content size fitter and a vertical layout group, but I tried now all settings and the result is always the same. I use Unity 2019.2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.