_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | Right way to dispose of a WWW IEnumerator after it has completed Unity What is the quot right quot way to dispose of an Ienumerator coroutine after it has completed? |
0 | Lightning not hitting an object? I was following this tutorial, but the lightning is not hitting the other object as the video shows. private LineRenderer lRend private Vector3 points new Vector3 5 private readonly int point Begin 0 private readonly int point Middle Left 1 private readonly int point Center 2 private readonly int point Middle Right 3 private readonly int point End 4 public Transform line private readonly float randomPosOffset 0.3f private readonly float randomWithOffsetMax 2f private readonly float randomWithOffsetMin 1f private readonly WaitForSeconds customFrame new WaitForSeconds(0.05f) void Start () lRend GetComponent lt LineRenderer gt () StartCoroutine(Beam()) private IEnumerator Beam() yield return customFrame points point Begin transform.position points point End line.position CalculateMiddle() lRend.SetPositions(points) lRend.SetWidth(RandomWidthOffset(), RandomWidthOffset()) StartCoroutine(Beam()) private float RandomWidthOffset() return Random.Range(randomWithOffsetMin, randomWithOffsetMax) private void CalculateMiddle() Vector3 center GetMiddleWithRandomness(transform.position, line.position) points point Center center points point Middle Left GetMiddleWithRandomness(transform.position, center) points point Middle Right GetMiddleWithRandomness(center, line.position) private Vector3 GetMiddleWithRandomness (Vector3 point1, Vector3 point2) float x (point1.x point2.x) point Center float finalX Random.Range(x randomPosOffset, x randomPosOffset) float y (point1.y point2.y) point Center float finalY Random.Range(y randomPosOffset, y randomPosOffset) return new Vector3(finalX, finalY, 0) Everything is good except that the lightning is not hitting the other object. What am I missing? |
0 | Timer as part of a condition I am using a sensor as the input to my game. When a certain level of force is exerted on the sensor, for a certain amount of time, I want the next level to be reached. How would I do this? I have attached both the timer code and the game code, but I don't know how to use them together. Timer code using UnityEngine using System.Collections using UnityEngine.UI using UnityEngine.SceneManagement public class Timer MonoBehaviour public int timeLeft 5 public Text countdownText Use this for initialization void Start() StartCoroutine("LoseTime") Update is called once per frame void Update() countdownText.text ("Time Left " timeLeft) if (timeLeft lt 0) StopCoroutine("LoseTime") countdownText.text "Times Up!" Invoke("ChangeLevel", 0.1f) IEnumerator LoseTime() while (true) yield return new WaitForSeconds(1) timeLeft void ChangeLevel() SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex 1) Game code using System.Collections using System.Collections.Generic using UnityEngine using System.IO.Ports public class arduino MonoBehaviour SerialPort sp new SerialPort(" . COM6", 9600) Com port and the baud rate of the arduino Material m Material GameObject Sphere void Awake() Sphere GameObject.FindWithTag ("Player") m Material GameObject.FindWithTag ("Player").GetComponent lt Renderer gt ().material void Start () if (!sp.IsOpen) If the serial port is not open sp.Open() Open sp.ReadTimeout 250 Timeout for reading Update is called once per frame void Update () if (sp.IsOpen) Check to see if the serial port is open try string portreading sp.ReadLine() get the string output of the serial port float amount int.Parse(portreading) if ((amount gt 10f) amp amp (amount lt 100f)) m Material.color Color.grey Sphere.transform.position (new Vector3(0f, amount 0.1f, 0f)) if ((amount gt 101f) amp amp (amount lt 150f)) m Material.color Color.blue Sphere.transform.position (new Vector3(0f, amount 0.1f, 0f)) if ((amount gt 151f) amp amp (amount lt 201f)) m Material.color Color.yellow Sphere.transform.position (new Vector3(0f, amount 0.1f, 0f)) if ((amount gt 201f)) m Material.color Color.red Sphere.transform.position (new Vector3(0f, amount 0.1f, 0f)) catch (System.Exception) |
0 | Character Action Sprite Framelength of Late 90's Something, Industry Standards of that Era? I'm making a 3d character that emulates a sprite. The game as a whole emulates the feel of a classic RPG game. Old games like Ultima Online, or Diablo...or similar late 90's generation... For an average run sequence, they must have had general targets for "smoothness". I'm curious if there was an old industry standard of that time for "sprite frames for this action" in game design. Example. A walk sequence in Diablo. How many frames would they have targeted in those years? I'm looking for a general guideline to emulate "that cool 90's RPG". I'd love some advice. If there was no such standard, and designers of old were as hacky as they tended to be, I'll also take a good educated opinion on the matter. |
0 | Unity 2D UI Scrollview Stretch settings not staying So I'm trying to make a Scrollviewer and inside that will be aload of boxes stacked on top of each other (the boxes have information in them like the boxes in this screenshot here but they will always be the same size). My problem is that whenever (in Unity's UI) I set where the Text UIs (in game) should be, they will revert to some random place whenever I start the game. For example I set the X 0 Y 50, start the game changes are made and it looks right. But when I exit game mode the X Some random number between 0 1000 Y Also the same, some random number between 0 100. Anyone know why this is happening? |
0 | Aim prediction along a parabola How to make a Tower Defence Mortar aim accurately I am building a very basic tower defence game in Unity3D where one tower is your standard long range mortar artillery. I want the projectile it fires to follow a parabola curve to make its movement seem like a mortar. This movement is not dependant on any physics (as I can make a projectile follow a curve but I could implement the Unity3D physics if the method used would benefit from it. My question is What technique should I use to ensure the projectile hits the locked unit whilst taking into account that the unit is moving along a possibly non linear path (defined with my A implementation.) I have not implemented any code as of yet as I wanted to consult the masses for any wisdom you can provide! My initial idea was to fix the time the projectile would take along its parabola curve (regardless of distance) and try and track the position the unit would be at after this time delay. Is this along the right lines or are there alternative methods to consider when aiming a projectile that follows a curved path instead of a linear one? Thank you for your time. |
0 | My FollowPlayer script runs AWAY from the player? With the script I'm using, it would make whatever model it was attached to, follow the player when they were close enough. Even though I have NOT updated to the newer version of Unity, the script isn't working how it used to. While it does make the model face towards the player, it no longer follows chases then and I have a suspicion that it may be because I am using rigidbody for the player controls instead of character controller (due to Character Controller no longer working after the latest Unity, which I did NOT update to) Below is a copy of the script I'm using, which is super simple using System.Collections using System.Collections.Generic using UnityEngine public class FollowPlayer MonoBehaviour The target player public Transform Player At what distance will the enemy walk towards the player? public float walkingDistance 10.0f In what time will the enemy complete the journey between its position and the players position public float smoothTime 10.0f Vector3 used to store the velocity of the enemy private Vector3 smoothVelocity Vector3.zero Call every frame void Update() Look at the player transform.LookAt(Player) Calculate distance between player float distance Vector3.Distance(transform.position, Player.position) If the distance is smaller than the walkingDistance if (distance lt walkingDistance) Move the enemy towards the player with smoothdamp transform.position Vector3.SmoothDamp( transform.position, Player.position, ref smoothVelocity, smoothTime) Any ideas why the model isn't chasing the player? I keep changing the settings to see if it's anything silly like that, but no matter what I put it, or what I do, the model just wants to stare but not follow or chase the player Here's a screenshot of the hierarchy And the player model does have the player tag. No matter what values I put into the inspector for the FollowPlayer script, the model with the attached script will not move towards the player. UPDATE I figured out it was because the model with the script attached didn't have a rigidbody component. The problem now is, the model runs away from the player. |
0 | Unity in c errors with "the type does not contain a constructor that takes 0 arguments" This is the problematic line datosAguardar datos new datosAguardar () Here is my code public class estadoJuego MonoBehaviour public int puntuacionMaxima 0 public static estadoJuego estadojuego private string rutaArchivo void Awake () rutaArchivo Application.persistentDataPath " datos.dat" if (estadojuego null) estadojuego this DontDestroyOnLoad (gameObject) else if (estadojuego ! this) Destroy (gameObject) Use this for initialization void Start () cargar () Update is called once per frame void Update () public void guardar () BinaryFormatter bf new BinaryFormatter () FileStream file File.Create (rutaArchivo) datosAguardar datos new datosAguardar () datos.puntuacionMaxima puntuacionMaxima bf.Serialize (file, datos) file.Close () void cargar () if (File.Exists (rutaArchivo)) BinaryFormatter bf new BinaryFormatter () FileStream file File.Open (rutaArchivo,FileMode.Open) datosAguardar datos (datosAguardar)bf.Deserialize (file) puntuacionMaxima datos.puntuacionMaxima file.Close () else puntuacionMaxima 0 Serializable definiendo la clase class datosAguardar ISerializable propiedades de la clase public int puntuacionMaxima metodo de la clase constructor de la clase public datosAguardar (int puntuacionMaxima) base (puntuacionMaxima) this.puntuacionMaxima puntuacionMaxima This is the constructor Serializable definiendo la clase class datosAguardar ISerializable propiedades de la clase public int puntuacionMaxima metodo de la clase constructor de la clase public datosAguardar (int puntuacionMaxima) base (puntuacionMaxima) this.puntuacionMaxima puntuacionMaxima |
0 | How can I replicate Quantum Break's distortion particle effect? Quantum Break has this fantastic particle effect, it's a distortion effect like broken glass. I want know how I can replicate this effect? You can see it below, and a full video is available on YouTube |
0 | Transparent image changing color to very light when used on light background in Unity I'm trying to use this transparent image (transparent brown, with a transparent white shadow) over this background in Unity UI. But the end result is not similar to what I see in photoshop at all. What I expect and what I have inPhotoshop What I get in Unity How can I fix this? |
0 | In Unity (2017) is there a way to set the buttons used by Input.GetAxis() programatically? The buttons used for keyboard axis inputs can be set manually via Negative and Positive Button fields for the axis at Edit Project Settings Input Manager. However I'd like to make this a user configurable option which I think means needing to set the button values from a script. I've been looking for a method along the lines of Input.SetAxis("Vertical").positveButton But so far I'm striking out. Is there a way to do this? |
0 | Optimizing data structure for my text adventure? In my text adventure I'm making, I store the story data in a hashtable (I'm using unity's javascript unity script since I'm more comfortable with the syntax than C ). The problem is, the way I structure the hashtable means that it gets incredibly bloated very quickly (I've used the same structure in all of my text adventures across multiple languages. It quickly grows to nearly 1k lines long) which makes it hard to edit in the future (especially if I need to go back to edit certain parts later on) Here's the hashtable as it's currently structured public static var story "0" "text" "", "choices" "response1" "text" "", "nextPart" "1" , "response2" "text" "", "nextPart" "2" , "response3" "text" "", "nextPart" "3" , "1" "text" "", "lastPart" "0" , "2" "text" "", "lastPart" "0" If anyone could help me optimize the structure of the hashtable that'll make it so it's more easier for me to edit it in the future, that would be great Quick information for parts that may not be self explanatory "lastPart" indicates to the hashtable parser that the player has died and the number refers to the part where they chose the response choice. "nextPart" refers to the part of the story the response leads to. |
0 | Reading from Streaming Assets in WebGL I'm trying to set up my Unity game for WebGL, but I quickly found out that you can't access your streaming assets as you would in a standalone build. For example, I have a code snippet below of how I load in all of my game's text for localization (i.e. get english translations of all text in my UI). public void LoadLocalizedText(string fileName) localizedText new Dictionary lt string, string gt () StreamingAssetsPath will always be known to unity, regardless of hardware string filePath Path.Combine(Application.streamingAssetsPath, fileName) if (File.Exists(filePath)) string dataAsJson File.ReadAllText(filePath) deserialize text from text to a LocalizationData object LocalizationData loadedData JsonUtility.FromJson lt LocalizationData gt (dataAsJson) for(int i 0 i lt loadedData.texts.Length i ) localizedText.Add(loadedData.texts i .key, loadedData.texts i .value) else ideally would handle this more gracefully, than just throwing an error (e.g. a pop up) Debug.LogError( quot Cannot find file quot ) isReady true I've been looking at online examples, and there's a lot of obsolete examples regarding the use of unity's WWW class and php. From what I understand the UnityWebRequest is now the way to go, but I'm confused how to use it with regards to the example above. I'm also trying to figure out how to connect to my SQLite database which is also stored in streamingAssets. public SqliteHelper(string databaseFileName) if (Application.platform RuntimePlatform.WebGLPlayer) ???????? else tag databaseFileName quot t quot string dbPath Path.Combine(Application.streamingAssetsPath, databaseFileName) if (System.IO.File.Exists(dbPath)) dbConnectionString quot URI file quot dbPath else Debug.Log ( quot ERROR the file DB named quot databaseFileName quot doesn't exist anywhere quot ) Now that I can't just open an SqliteConnection, I have no idea if there's a c only solution, or if I have to learn php as suggested from tutorials such as this one. If someone could walk me through how to solve either of these problems I would greatly appreciate it. |
0 | Can running unity of a system with nvidia graphics card speed up the simulation? I have a nvidia GTX 1080 graphics card in my computer, I don't know if unity by default makes use of GPU. Does having a GPU helps to speed up unity simulations. |
0 | Smooth Scene transitions with SceneManager and additive scene in Unity I'm trying to work with the new SceneManager class with Unity, I'd like to have smooth transitions between scenes. Currently I suppose that the only way to do those transitions is to manually implement them on the scene objects leveraging on the fact that scenes can be loaded additively. In pseudo code I image something like for gameObject in previousSceneGameObjects gameObject.animateSceneExit() endFor for gameObject in nextSceneGameObjects gameObject.animateSceneEnter() endFor I feel that there is something I'm missing P which is the best approach that you'd suggest? Is it my approach valid? |
0 | Serializing nested ScriptableObjects with runtime changes I'm making an effort to use ScriptableObjects more in my game architecture, after watching a fantastic Unity Unite talk on the subject. The central idea is to use ScriptableObjects, during runtime, as a kind of pluggable, mutable global data container. It's intended to replace things like the singleton pattern in a more testable, less tightly coupled way. I'm not going to go into detail on the arguments in favor of this, but I do definitely recommend watching the talk. When using this pattern, you'll probably run into data container style ScriptableObjects that you want to persist between play sessions. The problem I'm running into is that, when Unity's serializer is run on a ScriptableObject that references other ScriptableObjects, and those referenced ScriptableObjects have changed during runtime, the serializer ignores the changes on those sub SOs. Is there a good way to serialize nested SOs containing data that changes during runtime? For some examples more in depth background In the game I'm working on, I'm emulating a file system that multiple otherwise independent game objects are interested in. It looks somewhat like this public abstract class FilesystemObject ScriptableObject public string FileName CreateAssetMenu(fileName quot NewDirectory.asset quot , menuName quot Directory quot ) public class FilesystemDirectory FilesystemObject public List lt FilesystemObject gt Contents CreateAssetMenu(fileName quot NewTextFile.asset quot , menuName quot Directory quot ) public class FilesystemTextFile FilesystemObject public string Contents In my project directory, I have a FilesystemDirectory asset file named FSRoot.asset that represents the root directory of the filesystem. It's populated with all the files that need to exist when the player first launches the game. If a MonoBehaviour wants to read or write to this filesystem (say, an in game text editor), all I have to do is expose a FilesystemDirectory field to Unity's serializer, and then hook FSRoot up to that field using the inspector. Then, during runtime, if the player creates, edits, or deletes any filesystem data, those manipulations are done directly on the FSRoot object. Any other MonoBehaviour with the same reference to FSRoot sees the same mutated data, since those changes persist in memory. However, unless you're in the editor, those changes do not persist between sessions. You have to serialize and deserialize the data manually for that. However, when I serialize FSRoot using Unity's JsonUtility, it only captures changes that have happened to FSRoot directly, and not any changes in subdirectories files inside FSRoot. Any files that were authored in edit time are completely unchanged. |
0 | A two player game with a split screen In the antique game spy vs. spy, two players play on a single computer. The screen is split, with each half showing the viewpoint of one player. Is it possible to create such an effect in Unity? The main problem is that Camera.main is a global variable, so it is not clear how to have two cameras. |
0 | Why transform.Rotate(X,0,Z) rotates also Y? In my game I'm trying to rotate a turret. I'm using the classic pattern float h Input.GetAxis ("Horizontal") float v Input.GetAxis ("Vertical") if (h ! 0 v! 0) rb.transform.Rotate (new Vector3(v, 0, h)) The problem is that if I move in vertical axis also Y axis rotates. Why? How can I achieve a rotation that rotates only the X and Z axis and not the Y axis? |
0 | Raycast not hitting a collider I have the following simple raycast from a capsule on a cube bool hit Physics.Raycast (transform.position, Vector3.down, jumpSettings.groundJumpDistanceCheck, jumpSettings.layerMask) print(hit) When my layerMask is 8 (terrain), I have set my layer on my cube and my groundJumpDistanceCheck is 2. Then my hit is false. When my groundJumpDistanceCheck is set to Infinity. Then my hit is still false. However when I remove the distance parameter bool hit Physics.Raycast (transform.position, Vector3.down, jumpSettings.groundJumpDistanceCheck, jumpSettings.layerMask) print(hit) Then hit returns true. This is odd for me, as far as I know when you exclude the distance parameter it's supposed to be Infinity by default. But when I explicitly give Infinity as the distance, it returns false. I have also used the following code in an attempt to debug my issue, using the desired distance 2f Debug.DrawRay(transform.position, Vector3.down jumpSettings.groundJumpDistanceCheck, Color.red, 60f) As you can see, the ray does intercept the cube. I need the reycast to return true with a distance of 2f. |
0 | Unity3d physics stability with low fixed timestep I'm developing a vehicle simulator game for mobile platforms. This vehicle has some hydraulic arms. I use hinge joints and configurable joints. There can be collisions to walls etc. When I set a low Fixed Timestep (more fixed updates, less performance) like 0.001 it runs smoothly on editor and it handles the collisions well. But on the target mobile device, the performance drops to 2 3 FPS! So 0.001 (1000 fixed updates per second) is not an option. When I change the Fixed Timestep to its default 0.02 value or 0.01, performance becomes acceptable on mobile. But when collisions occur, the vehicle is torn apart and everything flies away at a high velocity as if there was an explosion. How can I achieve stable physics with 0.02 Fixed Timestep? Note I don't set the velocity or transform position. I move the vehicle by applying torque to the wheels. Update 1 The problem happens when the vehicle hits an obstacle that has a collider but doesn't have a rigidbody. |
0 | How to change AddForce code to MovePosition or SetVelocity? Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1f) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized targetPosition (camF vec.y camR vec.x) MoveSpeed Vector2 targetVelocity (targetPosition transform.position) Time.deltaTime rb.AddForce(targetPosition rb.velocity, ForceMode.VelocityChange) My problem is my character doesn't affects by the gravity when i changed my code from transform.position to rb.AddForce. I searched online and even asked here how to calculate gravity and add it to my character, nobody knew, so i think if i can change this code to rb.MovePosition or rb.SetVelocity maybe it does affects by the gravity? |
0 | How to have an AI controlled GameObject naively avoid another one? I have an idea of an AI controlled game which the gameobject will follow a path but it will change its path if I put another gameobject in front of it. For instance, if the moving game object is moving horizontally, and I put a static game object on its path, I want it to turn and continue its progression vertically just before it hits it. How can I achieve this? |
0 | How to arrange child objects in a grid i have a gameobject that have a group of plane meshes that created randomly as child every one of this planes have a "2f" offset in x axis between every plane what i wanna do is i wanna make the parent object arrangement the child objects on rows and columns even if one of this child deleted during the game or added so if i have 8 planes mesh it should look like that 2 rows and 4 columns like that but i don't know how to do that ? i know how to get child objects and making offset but i do't know how to get the format like that in the image i wanna to arrangement the planes meshes that i can acces from this for loop void Update() Transform children new Transform transform.childCount Debug.Log(transform.childCount) for (int i 0 i lt transform.childCount i ) children i transform.GetChild(i) |
0 | Glow effect shader for mesh generated at runtime I'm using the leap motion paint module and i would like the ribbons that are generated at runtime to have a glow effect, I tried editing the existing shader by adding a glow property but the colors did not change. I'm not experienced with shaders so any help would be much appreciated. EDIT I tried adding post processing effects for bloom amp glows, all the objects have a glow effect except the ones i'm generating at runtime.. Shader "LeapMotion TubeShader" Properties Color("Tint", Color) (1,1,1,1) Glossiness("Smoothness", Range(0,1)) 0.5 Metallic("Metallic", Range(0,1)) 0.0 Glow("Intensity", Range(0, 3)) 1 SubShader Tags "RenderType" "Opaque" "Glowable" "True" LOD 200 CGPROGRAM pragma surface surf Standard fullforwardshadows pragma target 3.0 struct Input float4 color COLOR half Glossiness half Metallic fixed4 Color half Glow void surf(Input IN, inout SurfaceOutputStandard o) o.Albedo ( Color Glow IN.color).rgb o.Metallic Metallic o.Smoothness Glossiness ENDCG FallBack "Diffuse" |
0 | Unity TextMeshPro bounds.size is wrong when hovering first time over gameobject I have this weird issue, which I am not able to fix. This is my third attempt and I need some help. Basically I have a hover element which spawns when I hover over a gameobject. The height of the element is determined by the amount of text (TextMeshProUGUI). The issue happens only when I hover first time, also not always (I have no clue how to reliably to reproduce it). Here is what happens (sec 10 ) https vimeo.com 449387131 I have tried to add these everywhere and different combinations LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() Canvas.ForceUpdateCanvases() txtMeshPro.ForceMeshUpdate() They dont seem to help. I assume the problem is here float bgHeight txtMeshPro.bounds.size.y 25 The bounds.size.y is wrong the first time I hover, but I have no clue why. Here is the whole code for spawning the GUI element public static void SpawnGeneralHoverElement(string descText, RectTransform hoverOverRect, float guiWidth) Canvas hoverCanvas instance.hoverElementGeneral.GetComponent lt Canvas gt () EnableCanvas(hoverCanvas) TextMeshProUGUI txtMeshPro hoverCanvas.GetComponentInChildren lt TextMeshProUGUI gt () RectTransform hoverElementRect hoverCanvas.GetComponentsInChildren lt RectTransform gt () 1 float scale hoverCanvas.GetComponent lt RectTransform gt ().localScale.x txtMeshPro.text descText Need this to be dynamic, if I change hover element size, it will still work float hoverElementWidth guiWidth Forces canvas update because of stackoverflow.com questions 55417905 why is textmeshpro not updating textbounds after setting text Canvas.ForceUpdateCanvases() LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() txtMeshPro.ForceMeshUpdate() Need this because otherwise the element spawns too far away on smaller resultions float spawnOffset (txtMeshPro.bounds.size.y hoverCanvas.GetComponent lt RectTransform gt ().localScale.x) (Screen.height 0.022f) float bgHeight txtMeshPro.bounds.size.y 25 hoverElementRect.position new Vector3(hoverOverRect.position.x, hoverOverRect.position.y spawnOffset, hoverOverRect.position.z) hoverElementRect.sizeDelta new Vector2(guiWidth, bgHeight) Debug.Log(hoverElementRect.sizeDelta) LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() Canvas.ForceUpdateCanvases() txtMeshPro.ForceMeshUpdate() Slide in form left to right if off bounds, need for traps for example float leftOffset hoverElementRect.position.x ((hoverElementRect.sizeDelta.x scale) 2) if (leftOffset lt 0) hoverElementRect.position new Vector2(hoverElementRect.position.x (leftOffset 1) 15, hoverElementRect.position.y) Slide in form right to left if off bounds, need for traps for example float rightOffset Screen.width (hoverElementRect.position.x ((hoverElementRect.sizeDelta.x scale) 2)) Debug.Log( quot Screen width quot Screen.width quot nrightOffset quot rightOffset) if (rightOffset lt 0) hoverElementRect.position new Vector2(hoverElementRect.position.x (rightOffset 1) 15, hoverElementRect.position.y) LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() Canvas.ForceUpdateCanvases() txtMeshPro.ForceMeshUpdate() |
0 | Changing alpha of Sprite I'm using OnGUI to draw a rect when I "box select" or "drag select". The texture that gets drawn is a PNG file made in Paint.Net with the opacity alpha channel set quite low. In Unity however, when I go to box select, the texture is completely opaque. How do I get Unity to honor the alpha set in Paint.Net? I also wouldn't mind using Unity itself to adjust the opacity, but I haven't found such an option in the import texture part of the inspector. |
0 | In Unity, is there a way to Set a new MeshRenderer? Here is what I want to do in Unity for a given GameObject go new GameObject(). I want to create a MeshRenderer, change its properties and only in the end set it as the component of go. For instance MeshRenderer newmeshrenderer (...) do stuff with newmeshrenderer go.AddComponent lt MeshRenderer gt () newmeshrenderer (or) go.GetComponent lt MeshRenderer gt (newmeshrenderer) But both way fail. What is the correct way of setting a MeshRenderer previously created to be the MeshRenderer of an object? |
0 | What controls the platform override codes in AudioClip (and maybe other Assets) .meta files? My game needs to use Unity 2019.3 for the console versions, and 2020.3 for the mobile ports. The Console Project is the master project. Virtually any changes done to it are replicated to the Mobile project. I would like to setup import overrides for Android (e.g. the compression quality for my soundtracks). To be consistent, I perform this change in my Console Project using the quot Override for Android quot checkbox (which affects the .meta file), and then replicate the change to the Mobile Project (a program checks for differences between both projects and applies most changes). Ideally, the Mobile Project will now reflect the compression quality I want for said soundtracks, but it actually doesn't in fact, the quot Override for Android quot checkbox does not appear to be checked in the Mobile Project, despite having a .meta file identical to the Console Project. I digged into the .meta files, and noticed that when I use quot Override for Android quot in my Console Project, the .meta file adds an entry code 27 platformSettingOverrides 27 loadType 2 sampleRateSetting 0 sampleRateOverride 44100 compressionFormat 1 quality 0.5 conversionMode 0 But, when I go to my Mobile Project and check the checkbox, it adds an entry coded 7 platformSettingOverrides 7 loadType 2 sampleRateSetting 0 sampleRateOverride 44100 compressionFormat 1 quality 0.5 conversionMode 0 I don't understand this inconsistency. Does anyone have any insight on the exact conditions rules Unity uses for the platform codes in the .meta files? I can only think of a few dubious reasons Maybe they changed from 2019 to 2020. My Console Project actually supports more platforms than the Mobile Project (the consoles, obviously), so maybe they quot pushed quot the Android code from 7 to 27. It is not the end of the world I could make a script that duplicates the settings of 27 into 7... But only if this behaviour is predictable or consistent. So my question is, what is Unity's logic behind the choice of these platform codes? Note so far I've only found this behaviour on AudioClip files. With Textures, I see that it actually uses the name of the platform in the .meta file, so the settings do work thankfully, but it is even more puzzling because now I don't understand why Textures and AudioClips use different conventions to begin with... What other Asset Type has numeric conventions? |
0 | Scene for Computer Screen We are developing a scene that will involve heavily interacting with a "touch screen monitor" in the scene.. Because the workflow of the touch screen will need to be dynamic we are creating a REST API that Unity will fetch JSON data and use that to build out the various parts of the UI. For instance, we get a JSON file that has a list of users and attributes and build out UI elements with that data. The question is should I build out the display and underlying logic as a 2D scene that I add in to our 3D room or just build it all in the 3D scene. I want to abstract away as much of the logic as I can for the interactive screen I want to make sure we can drop this screen in a different Scene down the road without too much reverse engineering. Sorry if this is a straightforward question, my background is software dev, not game design. |
0 | Enable SteamVR hand collision for when holding objects Just getting started on a game project with SteamVR in Unity. I've run into an issue with the collisions though. The hands and the objects that can be held collide with everything in the scene as they should. But when an object is picked up, the hand and the object stop colliding with everything. How would I go about fixing this? I could leave it as is, but if an object is let go of inside another, it gets flung out of the object it was inside. The other odd behavior happens after you let an item go. The hand that was holding it continues to not collide with anything until you move the hand away. After that it'll collide with everything normally again. |
0 | What is the difference between engine approach and language approach in terms of saving game data? I was asked to find a way to somehow save gamedata for a game we (my friends and I) are making and i found that there is something called engine and language approach. I have found something i would call language approach because it relies mostly on System libs but cannot find anything on the engine approach. Are scriptable objects the way of saving data by engine approach ? if so how do i combine them in one savefile ? Game engine we are using is Unity and we're writing code in C . |
0 | Unity Animator default values overwriten I have created a project to reproduce the problem I'm currently facing. I'm running a simple unity animation that moves a game object and expect to be able to reset the gameobject position. This can be done by adding an empty animation, that (since it does not change anything) simply writes the default values, thus returning our gameobject to its original position. But here is where things get complicated if the animator gameobject is set inactive while the animation is running, new incorrect defaults values will be saved when gameobject is activated, and I am unable to reset my gameobject position. To reproduce this issue, run the attached project (Download from here) Change the stop method to "PlayEmpty" Hit Start Animation and watch the left "Hello world" text travel. While it is traveling, click Disable Text GO. The left text disappears. Click Enable Text GO and see the text comes back at its last location. Click Start Animation and watch the left "Hello world" text travel. Click Stop Animation the text is returned to the position where it was when enabling the gameobject, rather than its original position. Any help is welcome, suggestions on how to change the code to make the above scenario work. Thanks, Yaniv |
0 | How can I make a Soft Outline Shader? Most Outline Shaders or Tutorials found online, are Shaders which are sharp edge outlines. Like here Even though a lot of games are already using soft outlines like here with a nice gradienty blurry effect. Creating a Outline is basically easy (as described here http wiki.unity3d.com index.php Silhouette Outlined Diffuse) Also ive seen that wanted effect in 2D https www.assetstore.unity3d.com en ! content 84126 But how do they do it in 3D? Ive found a useful step by step guide here (https willweissman.wordpress.com tutorials shaders unity shaderlab object outlines ) . But the first step is already not working. (rendering the 3d object in as pure white to a rendertexture). |
0 | Trying to create a '2D 8 Ball Pool' game Trajectory Prediction I am trying to create a game similar to (Pocket Run Pool) https www.youtube.com watch?v ewlAE6NQnsI amp t 215s a 2D pool game that is much simpler than a 3D one I need help with creating code for trajectory prediction something similar to this https docs.unity3d.com Manual physics multi scene.html How do I go about doing this? |
0 | The name 'txt' does not exist in the current context I am getting the error The name 'txt' does not exist in the current context and I am unsure why this is happening. I am very new to programming in C so sorry if the answer is obvious. I am trying to make my ammo count change on screen and have been told to use txt.GetComponent lt UnityEngine.UI.Text gt ().text ammo.ToString() but that gives me the error and I am unsure why. This code is supposed to spawn in bullets for my gun but that part of the script is not important. The problem is that error. If you could tell me what the problem is that would be greatly appreciated. Here is my code using System.Collections using System.Collections.Generic using UnityEngine.UI using UnityEngine public class PL MonoBehaviour public GameObject bulletPrefab public Camera playerCamera private Coroutine hasCourutineRunYet null public int ammo 165 65 enemies in total, needs tons of ammo public GameObject axe public Text Ammmo Update is called once per frame void Update() if (Input.GetMouseButtonDown(0)) if (hasCourutineRunYet null) hasCourutineRunYet StartCoroutine(BulletShot()) if (ammo 0) GameObject.Find( quot wp shotgun quot ).SetActive(false) axe.SetActive(true) txt.GetComponent lt UnityEngine.UI.Text gt ().text ammo.ToString() IEnumerator BulletShot() GameObject bulletObject Instantiate(bulletPrefab) bulletObject.transform.position playerCamera.transform.position playerCamera.transform.forward bulletObject.transform.forward playerCamera.transform.forward yield return new WaitForSeconds(1.0f) hasCourutineRunYet null ammo |
0 | How to slow down this rotation My goal here is simple. I am making a top down shooter kind of game, and I want the player to simply rotate in one axis, towards where the mouse is on the screen. I got it working, but it rotates so fast that everything is out of control. The following method is called in Update() on my player's game object void RotatePlayer() var targetPosition new Vector3(Input.mousePosition.x, Input.mousePosition.y, 100) targetPosition Camera.main.ScreenToWorldPoint(targetPosition) targetPosition.y transform.position.y Time.deltaTime transform.LookAt(targetPosition) That rotates in the direction of the mouse, but like I said it rotates so fast that you cannot control it. As you can see I tried to multiply by delta time, but that did not seem to do anything. Also, changing that last parameter of "100" to a lower number also does not do anything. Any help is greatly appreciated. |
0 | Render sprites onto a virtual 640x480 "screen" I'm making a game, and in part of it, the player uses a computer terminal. I want to draw to a virtual 640x480 screen with pixel precision, and then draw that "virtual screen" to the player's real screen. The end result will not be "pixel perfect" because 99 of people won't play the game at 640x480 and, in fact, I want to then go on and add further effects on top of this so it looks more like a CRT display but trying to figure out how to do pixel rendering in Unity has proven pretty difficult so far. Basically I want to render something that looks like this onto the screen, where I draw all of the text characters myself (using Sprites? subsections of a Texture?), and then I want to render this "virtual screen" out onto the player's screen. I know RenderTextures are a thing, and maybe that's part of it? I've tried a lot of different things so far and got nowhere, hence why I'm posting here. Sorry if this is too nooby of a question, I'm an experienced programmer who is relatively new to Unity. |
0 | Unity 2d Vector3.Lerp Not Working as Expected I have asked this question on other community but still get no response after a month, so I decided to ask it here. I am trying to put player position to the middle of camera when it is reaching near the edge of the camera. It works correctly with the following code transform.position playerPosition where playerPosition is the current position of the player. But, when I try it with Vector3.Lerp or Vector3.MoveTowards, it won't reach the player's x position. Here is how it looks when using Lerp or MoveTowards https www.youtube.com watch?v E50RpycrUxI And here is when not using Lerp or MoveTowards https www.youtube.com watch?v ng A4AfDQFE The script public GameObject player private Vector3 playerPosition private Vector3 pos public float offsetSmoothness void Update () player's position relative to camera pos Camera.main.WorldToViewportPoint(player.transform.position) playerPosition new Vector3(player.transform.position.x, transform.position.y, transform.position.z) if player reach the edge of the camera do the following if (pos.x lt 0.1 pos.x gt 0.9) transform.position Vector3.Lerp (transform.position, playerPosition, offsetSmoothness Time.deltaTime) transform.position playerPosition Why Vector3.Lerp is not positioning the player to the center of the camera when this condition is used to execute it if (pos.x lt 0.1 pos.x 0.9) ? And how to make it working as expected, which is making the Vector.Lerp position the player to the center of camera when the player close to the edge of the camera? |
0 | Algorithm for creating spheres? Does anyone have an algorithm for creating a sphere proceduraly with la amount of latitude lines, lo amount of longitude lines, and a radius of r? I need it to work with Unity, so the vertex positions need to be defined and then, the triangles defined via indexes (more info). EDIT I managed to get the code working in unity. But I think I might have done something wrong. When I turn up the detailLevel, All it does is add more vertices and polygons without moving them around. Did I forget something? EDIT 2 I tried scaling the mesh along its normals. This is what I got. I think I'm missing something. Am I supposed to only scale certain normals? |
0 | Unity Hide GameObject that is behind UI I have the following example How can I prevent the part of the sprite that is highlighted in red and is behind the UI from being displayed on the camera, but having the background image still showing? |
0 | Can't Get Component On Photon Instantiated Scene Object I'm completely new to photon. I have a fair bit of experience with Unity but learning multiplayer feels like learning a new game engine lol. I'm using photon and making a chess game, so I've put photon Views and practically everything, except the objects I want to be unique. I feel like I've gotten most of it figured out, but for some reason, when I start a multiplayer game, it doesn't initialize my chess pieces properly. So, I have it placing all the pieces at start, here is my pastebin for reference, the InitiateBoard() method is what's having issues, starting at line 85, the error is at line 100. https pastebin.com bVUJ25Yu The quot pieces quot array is a 2D array of the ChessPiece class, which assigns the sprites, team, and movesets based on position on the board. It's very strange, it works just fine on a single player game, but if I build the game and play two player(which is the exact same script, it just disables the AI), for some reason, only the build gets a null reference exception error at this line, pieces x, y spawnedPiece.GetComponent() It seems to be unable to get a reference to the chesspiece, and therefore, it sets all the pieces to white rooks as white rook is in the default position. Weirdly, the pieces initialize properly on the editor's screen. And also, if I play the build version in single player, it seems to initialize everything just fine. After some testing, I realized it's only the joined player that is having issues, I tried running the build version first, then joining through the editor, it does the exact same bug with the same error code on the editor rather than the build version. So I can look at the editor and see a bunch of white rooks, but when I look at the build, it will be a bunch of properly assigned pieces... And yes, I am certain they are in the same game, as it calls an RPC to start the game and if I move one piece, I can see said piece is moved on both games. Does anyone know what could be causing this? It's spawning the pieces just fine, but it doesn't seem to be able to get the component on the spawned piece... |
0 | Rotating with a preferred direction I do a RayCast to the terrain and then use the RaycastHit.normal to plant flags. I would like to have the flags to point up with the normal, but have them all face the same direction. As seen in the image flag 1 points to left of the screen and flag 5 to the right. I understand why, but do not know how to rotate it. I saw LookRotation (Unity) has an override that takes a forward direction too. I thought it would work with say Vector3.Forward, but if a flag is placed on a wall it points into the wall. The direction or angle they face can be set by the player. I have a hard time understanding quaternions, every time I think I do, I get stuck. Any tips ? |
0 | Having multiple different friction values on a single piece of track? I am trying to figure out a good performant way to give a piece of track multiple values of dynamic friction. A track piece is 10x10 units in Unity and the idea is to puzzle them together to a big track like the tracks in Trackmania. The game itself features no acceleration, except from gravity. To make things more interesting I want to give each track piece at the start of the scene multiple random friction values within a given range. Currently I achieve this by making each piece of track consisting of 100 little tiles which are 1x1 units and they get a random friction values assigned. This approach works somewhat fine as long as there are less than 30 to 40 track pieces(3000 4000 tiles) but with more than that the fps are dropping really low. As it is a racing type of game I had to set the quot Fixed Timestep quot in the project settings to 0.001 to get accurate time measurments and this is hurting the performance as well. With a lower timestep the collision detection with all the little tiles is really bad too. Is there a more elegant and or performant way to achieve this in within the unity physics system? |
0 | Using fixed time for Lerp I would like to change a camera's rotation and position from its current position and rotation to a destination position and rotation. This should happen within a specific time (seconds). I call this void "pRotateAndPosition" in each Public void Update(). However, I'm having trouble getting the 3rd argument for Lerp (time) correct. Could anybody tell me where my mistake(s) are? Thank you. private void pRotateAndPosition() TimeElapsed (Time.deltaTime TimeInSecondsInWhichWeWantToGetToFinalRotationAndPosition) if ( TimeElapsed gt TimeInSecondsInWhichWeWantToGetToFinalRotationAndPosition) StopCallingThisVoid true don't call this anymore set the final position and rotation in case we're not completely there yet camera.transform.localRotation Quaternion.Euler(goalRotation) camera.transform.localPosition goalPosition return float fTime TimeElapsed absolutely not sure about this one camera.transform.localRotation Quaternion.Lerp( camera.transform.localRotation, Quaternion.Euler(goalRotation), fTime) camera.transform.localPosition Vector3.Lerp( camera.transform.localPosition, goalPosition, fTime) |
0 | Two 2D objects in Unity aren't colliding together In Unity 5, I have a player shooting a projectile in aim to hit a boss, and inflict damage upon contact with the projectile. Though for some reason, the projectile and boss aren't colliding with each other. I've done the following Made sure that both the projectile and boss have a BoxCollider 2D and Rigidbody 2D Made sure that they're on the same Z Index and on the same layer Tried to Debug.Log() if there's any collision (there isn't) Made sure I'm using OnCollisionEnter2D on the boss' health script Compared the syntax I use with another collision (where the player collides with an object and dies this works perfectly fine). However, none of these seem to be working. This is the boss' health script void OnCollisionEnter2D (Collision2D coll) Debug.Log("COLLIDED") bosshealth 1 Here is the projectile prefab And the boss prefab Does anyone have a clue as to why they're not colliding? the projectile just glides over the boss EDIT I found a temporary fix! Disabling the Kinematics of the boss allows for both objects to collide, and successfully display a debug message! Just a problem though I don't want the boss to freely float around in space. I use the kinematic to ensure it stays put at all times until told to by scripts. Is there a way to get around not having to disable the kinematics? EDIT 2 Then again, I am removing the projectiles on impact anyway, so the actual boss doesn't move, but that seems dirty |
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 | Tile set showing grid with lighting Hi so I have this tile set generated procedurally at the start of the scene. When I activate the point light in the middle of the screen I keep getting this grid in the game view, i tried changing the size of the tiles but no luck if I change them before pressing play in the game view. But if I do it at run time from the inspector the bug goes away , hiding the square of the tile that I have moved...for that tile in particular even just moving it a bit solves it. This happens in edit and game mode ,and the grid is made of loads of sprites put together. The import settings of these sprites is dont generate mip maps, no compression. And each of the tiles have the default shader sprite diffuse. I deactivated gizmos but no luck either Any idea what can this be ? anything related with baking the light or something? thank you for your help! |
0 | How to search for a visible player? I've an enemy static tank with a "rotable" cannon turret. I would like to rotate it in the player's direction . How to implement it ? I've thought something like void Update SearchForPlayer() RotateTurret() I don't know how to implement a sort of radar function. Thanks |
0 | How to create scrolling input text field using Unity UI How to create scrolling input textfield using UI in Unity 4.6.6 problems in my project are 1.Cursor is not masking 2.Scrollbar size is automatically become 0 to 1 size 3.Scrollbar is not working after assigning in "Scroll Rect". Here is my sample project Thanks in advance . |
0 | Unity 3D Why does my button need to be clicked twice to work? My goal is to go back and forth between a series of animations by clicking left and right arrow UI buttons. I wrote this C script and the quot next quot button (which executes AddInt() on click) works as intended, however the quot previous quot button (which calls ReduceInt() on click), needs to be clicked twice to work. Is this a glitch or is something wrong with my code? public class update animator parameter int MonoBehaviour Animator gameobject animator public string int parameter public int max int public int current int 0 void Start() gameobject animator GetComponent lt Animator gt () public void AddInt() current int if (current int gt max int) current int 0 gameobject animator.SetInteger(int parameter, current int) public void ReduceInt() current int if (current int lt 0) current int max int gameobject animator.SetInteger(int parameter, current int) |
0 | How do I change the mesh in an existing prefab in Unity? So I made a prefab some time ago and now I want to change the mesh without changing any scripts. I have an OBJ file I want to use. Is there any way to do this? I've read the documentation but I don't seem to understand how to do it. |
0 | Unity OnCollision2D not working I'm new to Unity and C (though I'm experienced in python) and I am trying to make a pong clone, I've spent ages googling and trying to fix this issue but for some reason my OnCollisionEnter2D won't work My paddle hit method public void PaddleHit(Collision2D col) float y WhereBallHitPaddle(transform.position, col.transform.position, col.collider.bounds.size.y) Vector2 dir new Vector2() determing direction to left or right depending on the paddle if (col.gameObject.name "Player1") dir new Vector2(1, y).normalized if (col.gameObject.name "Player2") dir new Vector2( 1, y).normalized rb.velocity dir speed play ball paddle collision sound SoundManager.Instance.PlayOneShot (SoundManager.Instance.ballpaddle) When I run the game the ball moves, then when it comes into contact with a paddle it just stops moving, and if it comes into contact with a wall it bounces off, but at no point does it trigger the OnCollisionEnter2D. (I think my codes indents aren't showing properly here but it is all indented correctly, there are no compile errors or anything). |
0 | Unity Events executed out of order According to this page Events in unity are suppose to execute in a specific order. Specifically, OnCollisionEnter is supposed to be called right after OnTriggerEnter however, FixedUpdate and Update are both being called at least once in between calls to my OnTriggerEnter2D and OnCollisionEnter2D functions in my Enemy class, why is this the case? Here is my code public class Enemy Combatant public int kill points public float force public List lt GameObject gt path verticies private int pathi private bool on path private bool is flying private bool ignore collision Used for ignoring collisions with walls, if the enemy has already touched an enemy controller. void Start () Init() pathi 0 ignore collision false is flying false if (gameObject.tag.Contains("Fly")) is flying true Assuming contains is cheaper than a full string compare. on path null ! path verticies amp amp 0 ! path verticies.Count private void FixedUpdate() ignore collision false void Update () if (!CheckBounds()) Destroy(gameObject) if (on path) transform.LookAt(path verticies pathi .transform, Vector3.up) transform.Rotate(new Vector3(0, 90,0)) phys.velocity transform.right speed else dx Mathf.Sign(Cx) speed public void Flip() Cx 1 pragma warning disable CS0642 Possible mistaken empty statement private IEnumerator OnCollisionEnter2D(Collision2D collision) if (on path amp amp path verticies pathi collision.gameObject) if (collision.gameObject player) throw new System.NotImplementedException() yield return new WaitForSeconds(0.1f) Used to prevent damage to the player if the player landed on top of the enemy. var atk player.GetComponent lt Combatant gt ().vigor.Attack(2) if (Health.Atk.DIES atk) player.GetComponent lt Life gt ().Die() else pathi (pathi 1) path verticies.Count yield return new WaitForSeconds(0.0f) else if (on path) if (collision.gameObject player) yield return new WaitForSeconds(0.1f) Used to prevent damage to the player if the player landed on top of the enemy. var atk player.GetComponent lt Combatant gt ().vigor.Attack(2) if (Health.Atk.DIES atk) player.GetComponent lt Life gt ().Die() else if (collision.collider On(Truebounds)) nothing else if (collision.gameObject.layer 0 collision.gameObject.layer 8) TODO take velocity in the direction opposite of the normal and add it to the perpendicular component the enemy is moving in yield return new WaitForSeconds(0.0f) else if (collision.gameObject player) yield return new WaitForSeconds(0.1f) Used to prevent damage to the player if the player landed on top of the enemy. var atk player.GetComponent lt Combatant gt ().vigor.Attack(2) if (Health.Atk.DIES atk) player.GetComponent lt Life gt ().Die() else if (ignore collision) nothing else if (collision.collider On(Truebounds)) if (is flying) Flip() else if (collision.gameObject.layer 0 collision.gameObject.layer 8) Flip() yield return new WaitForSeconds(0.0f) private IEnumerator OnTriggerEnter2D(Collider2D collider) var component collider.GetComponent lt MonoBehaviour2 gt () if(!component) yield return null else if (on path amp amp path verticies pathi collider.gameObject) pathi (pathi 1) path verticies.Count else if (on path) nothing else if (component.type typeof(Enemy Controller)) Flip() ignore collision true yield return null pragma warning restore CS0642 Possible mistaken empty statement public void OnDestroy() and these are my timestep settings |
0 | Avoid players getting stuck by placing items in the same place Let's assume a multiplayer game of two players. These two players have to place six elements at six different positions. The order or exact place does not matter. As the items are placed correctly, they cannot be replaced anymore. Issue Both place an item at the same position and now there are basically two items at a position where only one should be. This makes the task impossible to complete, as one item is missing now for the last position. My assumption is that while both are really doing that in parallel, the communication between both computers is too slow so the other player can't know there is already an item. I encountered this issue in a game recently and I wonder how to avoid this. The simplest solution would be that the items can be replaced when placed. But let's see it more technical A correctly placed item cannot be replaced so how to circumvent or how to avoid this situation? |
0 | Is it still possible to install Unity? When trying to install Unity I am getting the following error The download of version ... was cancelled. I checked that there are no spaces in the path. Also I can not Sign in. When I provide the correct email and password the Sign in window just closes with no result. Also I tried to report a bug using the Report Bug feature, but it seems not to work. Also I tried to post a question on Unity Forum. But the Sign In over there does not work as well. What else may I try? Thank you. |
0 | Mission system for a FPS game to force the player into following the storyline Lately I've been working on a FPS game with a storyline in unity and I've encountered something that has been making my head explode for days. My objective is to be able to force the player to do a certain objective before being able to continue the game and to also give the new missions straight after the player has completed the past ones. To help the player out I've created a panel with the description of the mission so that the player can check it out whenever he wants to. I've already created some code of my own for one mission but it seems to be a mess, I'm sure I should have different scripts for different things so that I didn't need to repeat code so much when I'm about to create a new mission script. My problem is that I don't have the skills yet to do and I would like some suggestions how could reduce my code and how I could create a universal script that would be able to recognize which missions are done and which are not, instead of doing it over and over again in every single mission script? I'm kinda of new to unity and I've never posted to stack overflow so if I made any mistakes I'm sorry. Extra information the storyline is a linear, what I mean by that is that it doesn't give the player a choice to change it, it will always be the same and the quests missions are here to force the player into following it. For example, the first mission is for the player to go down stairs and turn on two batteries. The second mission is for the player to kill a certain amount of enemies that appear right after. |
0 | Making a cube follow my finger in Unity2d? I would like to make a cube follow my finger when i touch an iphone screen and drag in unity 2d. |
0 | What's wrong with my animation trigger script? So I am making an RPG and I am setting up the player. I am trying to trigger an attack animation by pressing a button. I wrote this down and I get an error that says "Expressions in statements must only be executed for their side effects". I don't know what that means, but it is an error that won't let me play the game without fixing it. I'm not sure where to go from here. How would I fix the error? EDIT I'm not using Mecanim, nor am I planning on using it. This is the script. It is in JavaScript (Unity3D). pragma strict var anim AnimationClip function Start() animation "Sword Slash" .layer 4 animation "Sword Slash" .wrapMode.Once function Update () if (Input.GetKeyDown ("c")) animation.Play("Sword Slash") |
0 | How do you deal with transparent fonts that you want to be white? I'm a bit of a total amateur, but I thought I would learn how to make a simple game during quarantine. However, I stumbled into a problem with fonts. I'm thinking about using the free font quot Pixelmania quot to show a score at the top of the screen. But the font is transparent! How do I make the inner part of the font white? Do I have to manually edit the font file myself? Or is there an easier way? |
0 | In Depth Lockstep Explanation I'm making a multiplayer game built upon a lockstep system and I'd just like a better grasp on the concept. My main question is on how to get every command to simulate at the same time on every client, or rather, on the same points in each client's timeline. I'm using a fixed update of 10 frames per second for simulating every object's position from movement commands (Click and move style) the same way. How do I tell all clients to execute all commands at the same relative time to the first command? Note I'm using Unity3D and a sufficiently accurate physics implementation. I just need to get across every command at the correct time. |
0 | Random Coroutine Delay? IEnumerator Shooting() Random Delay rand2 random.Next(1, 4) if (!audioSource.isPlaying) enemyParticles.SetActive(true) particle.Play() audioSource.Play() rand random.Next(0, 5) Vector3 vel rb.velocity if (rand 2) if (vel.x lt 6f vel.y lt 6f vel.z lt 6f) health.numOfHearts 1 yield return new WaitForSeconds(rand2) This script is tied to several enemy objects. random is initialized in the Start method with a different seed for every object. For some reason that I can't figure out, the delay is not randomized here. The AudioSource for instance is played for all the enemies at the same time with the same delay every time. I'm not too familiar with coroutines and how they are executed, but I always put the WaitForSeconds() statement at the beginning or end which usually works for me. Here is the Start method Random Seed public int RandomSeed private System.Random random private int rand Random Delay private int rand2 void Start() Random random new System.Random(RandomSeed) Could someone explain why the AudioSources of all the enemy objects are played at the same time when I encounter them? Thanks in advance. ) |
0 | How to flush changes in PlayerSettings inside Editor I have a script which works only in the Editor. The script makes changes inside PlayerSettings. However, the changes made are flushed to the hard drive just after something in Unity is saved for example any scene. We have a script which increments the build version. The described issue sometimes leads to the wrong version committed to Git as the changes a flushed to the disk later. How can I flush the changes of PlayerSettings from the code? |
0 | Flickering GUI on Android New version of Unity is causing rather weird problems on Galaxy S device. The GUI starts to flicker, tear and disappear altogether at random in different screens. But this only happens on the second launch. The first launch after full uninstall works perfectly. Normal(first launch) Screenshot of the flickering(after first launch) There are no errors in LogCat that clarifies the problem and this does not affect functionality of the app, only the GUI goes bananas. This happens on other Galaxy S devices too, not just mine. This also happens in my other projects, one which is smaller and one which is larger. But on other devices like Galaxy S2 and Motorola Xoom, there are no issues. What could be the issue here? P.S I have contacted Unity support, but have not heard from them |
0 | Unity RTS Single Selection Problem I am trying to build an RTS game and I have managed to form a way to select a unit using Raycast and the tag system. I made it so that if the object the ray falls onto is of tag "TankUnit" Make so and so variable true and allow it to move to another place. However, Units of the same tag even when not selected also move. How do I fix this problem? The script is bound to each unit. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.AI public class UnitController MonoBehaviour bool clicked false public float speed 10f public float rotationSpeed 10f public LayerMask groundLayer public NavMeshAgent playerAgent Update is called once per frame void Update() if (Input.GetMouseButton(0)) Debug.Log("Clicked") FindClickPos() if (Input.GetMouseButton(1) amp amp clicked true) Debug.Log("I clicked right mouse") Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) MoveTo(hit) private void FindClickPos() RaycastHit hitInfo new RaycastHit() bool hit Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo) if (hit true) Debug.Log("I hit " hitInfo.collider.name) if (hitInfo.collider.tag "TankUnit") Debug.Log("I hit" hitInfo.collider.tag "!") clicked true else Debug.Log("I didnt hit a unit ") clicked false else Debug.Log("I didnt hit anything...") clicked false void MoveTo(RaycastHit hit) Debug.Log("Position " hit.point) playerAgent.SetDestination(hit.point) |
0 | Unity3d iOS build restarts when regaining focus from browser I have an app made in Unity3d for android and iOS. In it, the user has the ability to link their accounts with Facebook and Twitter. For Facebook I use their Unity plugin, for Twitter, I open an external browser page that lets them accept or decline Twitter integration that then redirects to a php page the calls the app URI to return focus to Unity. On Android this all works perfectly using an Intent in the Manifest. In IOS I'm running into issues though and I don't really know my way around XCode. I'm using the newest version, XCode 7 Beta 2. The App runs as expected but for both the Facebook and Twitter authentications, upon returning focus to the App from the Browser, it completely restarts the App as if just launched rather then returning from a suspended state. In the Unity build I have "Run in Background" selected. I setup the URL Scheme in XCode. Its a pretty basic app so I don't think its being closed due to Memory usage. Any ideas or any settings I can change in XCode that might be preventing it from resuming? Note, if I just hit Home and send the App to the background it will properly resume, its only when called by the URI from the browser that it seems to completely restart. |
0 | Playing different particle effects in Unity on the same ParticleSystem The question really sums it up What is the best way to use one particle system for playing different particle effects? The scenario GameObject is picked up and it starts playing a simple indicator particle effect. If the GameObject is placed on a special platform it will play another particle effect. I have very little experience with particle systems how would you do this? |
0 | Problem with the Layer System Tilemap Layer from Unity This is my first time using Unity (and my third time creating a game in general), so I hope I can provide the needed information to solve this problem. My character overlaps with the upper wall, but doesnt with the lower wall. This is the right behaviour given the layers (seen in the picture). But I want him to be behind the lower wall AND in front of the upper wall. Side Information The Wall Tile is one piece, which covers two tiles. Movement is depended on the existents of a ground tile. The reason behind this is, that I wanted the character to always move one tile at a time. And since this is my first time with unity, that was the easiest way of doing it. So there is no actual interaction with the wall. No collsions or anything. There are three Layers (Ground, Creature, Wall) and two tilemap layers (Ground and Wall) (see picture) and the character doesnt interact with the tilemaps at all, he just gets drawn above the ground tilemap layer. What I see as answers Split the wall tile into two tiles and let the wall part be on another layer, then the roof part. Split the character into two parts and do the same thing. Both seem like a good way of solving it, but I dont even know where do start there. I think I can split the walls into two tiles, but I dont know if this is a good way to solve this issue. The other option, to split my character, there I really dont know where to start. What I tried Trying around with layers and order in layers. Trying around with the tile atlas (adding the sprite, removing tiles) |
0 | Reset Polygon Collider Runtime (Unity) I've created an animation by using different frames. Then applied polygon collider on that object. Problem is that when frame changes in animation, it does not reset collider. I've searched for resetting polygon collider as sprite gets change. One solution I've found is like following Destroying existing collider amp Adding new collider to the object. http answers.unity3d.com answers 723811 view.html I've applied this on the object. But it hangs the game. Is there any another way to reset polygon collider from c . |
0 | What is the optimal scene size? I'm coding a small quot Binding of Isaac quot like game, with a little help from the official quot Scavengers quot Unity tutorial, since it's my first game. In the tutorial every level is comprised of only one room. The player moves around and, when it reaches the ending, the whole scene is reloaded, creating a new procedurally generated map, but I wanted to do something different on my game. My idea is to have levels comprised of a procedurally generated maze of many many rooms and the player should be able to navigate across them back and forth at will, but I'm unsure about using a scene per room or per level. Q What is the ideal size (in terms of gameplay content) for a scene? Is the act of loading scenes resource expensive (therefore prohibiting it's frequent use)? Are there relevant performance differences between using many small scenes versus using one big scene? Should I make every room a scene just like the tutorial, or should I make a bigger scene for the whole level? |
0 | How to constrain axis angle rotation? I have a problem where I'm performing an axis angle rotation and am trying to constrain my rotations. Specifically I have a skeleton (model mesh with rig, transforms are hierarchy parented to pelvis which move the triangles of the mesh) and I am constraining the motions to prevent bad joint rotations (e.g. knees bending sideways or backwards). The rotations in this case can pretty much be constrained by saying "do not rotate about X Y Z." I'm using the Unity3D RotateAround function which rotates about a specified axis at a point by an arbitrary angle. Given control over this point, axis, and angle how can I constrain this rotation to prevent "bad" rotations? |
0 | Is database necessary? Hi I have studied c for good few months and I'm at intermediate level at the moment. And few days ago I decided to make simple 2D Games like "Mr Jump" after studying Unity. So my question is as follow 1)Should I study database to make simple mobile games? and if so what would be good language to study? 2)And if you have played "Mr.Jump", can you tell me if that game required complicated database coding and a lot of knowledge? 3)Also when we play the game, our best score and new characters get saved in our phone. Is that something to do with database? 4)Could tell me examples of database in games? 5)Should I study database as much as c ? |
0 | How can I save data in Unity? I'm making a game that's pretty simple and I really only need to save one int for when the game is closed (the scene the payer is at), but all the tutorials and guides I've seen haven't been much help so far. So basically I want a way to either have the game, resume right where I left off when I quit, have it load a specific scene when you resume playing, or have it save that single int. Having it load a specific scene would work best but I can use any of the options stated above. |
0 | "error CS0246 The type or namespace "NAMESPACE" could not be found" while declaring that namespace usage I have two scripts, one is located at Assets Scriptable Objects ... while the other one is located at Assets Scripts ... I have the first script encapsulated on a namespace. using System.Collections using System.Collections.Generic using UnityEngine using UnityEditor using VoidlessNodes.LevelFlowNodes namespace VoidlessUtilities CreateAssetMenu public class LevelFlowData BaseNodeEditorData lt BaseLevelNode, LevelFlowEditorAttributes gt private const string MENU ITEM PATH "Create ScriptableObjects LevelFlowData" private const string NEW ASSET PATH "ScriptableObjects Level Flow Data" SerializeField private string name private RootLevelNode root lt summary gt Gets and Sets name property. lt summary gt public string name get return name set name value lt summary gt Gets and Sets root property. lt summary gt public RootLevelNode root get return root set root value MenuItem(MENU ITEM PATH) public static void CreateAsset() LevelFlowData scriptableObject ScriptableObject.CreateInstance lt LevelFlowData gt () as LevelFlowData AssetDatabase.CreateAsset(scriptableObject, AssetDatabase.GenerateUniqueAssetPath(NEW ASSET PATH)) public BaseLevelFlowNode GetLevelFlow() BaseLevelFlowNode rootLevelFlow null if(root ! null) rootLevelFlow root.GetNode() else Debug.LogError(" LevelFlowData Data has no RootLevelFlowNode saved") return rootLevelFlow as RootLevelFlowNode And the other one is using the same namespace, which is a namespace I use for my custom scripts, but the only difference is that LevelFlowData's location is not under Scripts. using System using System.Collections using System.Collections.Generic using UnityEngine using VoidlessUtilities public class TestLevelController Singleton lt TestLevelController gt SerializeField private LevelFlowData levelFlowData SerializeField private List lt GameObject gt testViews lt summary gt Gets and Sets levelFlowData property. lt summary gt public LevelFlowData levelFlowData get return levelFlowData protected set levelFlowData value lt summary gt Gets and Sets testViews property. lt summary gt public List lt GameObject gt testViews get return testViews set testViews value region UnityMethods void OnEnable() BaseInteractable.onTriggeredEvent (int eventID, bool triggered) gt Debug.Log(" TestLevelController Event Triggered " eventID) void OnDisable() BaseInteractable.onTriggeredEvent (int eventID, bool triggered) gt Debug.Log(" TestLevelController Event Triggered " eventID) lt summary gt TestLevelController's' instance initialization. lt summary gt void Awake() lt summary gt TestLevelController's starting actions before 1st Update frame. lt summary gt void Start () lt summary gt TestLevelController's tick at each frame. lt summary gt void Update () endregion region PublicMethods public void EnableView(int index) testViews.SetAllActive(false) testViews index .SetActive(true) endregion region PrivateMethods endregion Do I need to move LevelFlowData to Scripts, and make platform independet compilation (e.g., if UNITY EDITOR) encapsulation for UnityEditor namespace usage? Or is there another point I am missing? This is the specific error log Assets Scripts Scene Controllers TestLevelController.cs(10,27) error CS0246 The type or namespace name LevelFlowData' could not be found. Are you missing an assembly reference? Thanks in advance. |
0 | Recenter User Orientation on X and Y axis on with Oculus GO and Unity I am working on an Oculus GO App for patients in a doctors chair. They'll be using Oculus GO Headsets while sitting, lying, or something in between. So what I am trying to do is to recenter the HMD orientation when the HMD is mounted. But since the patients position can be seated or lying horizontally, I will need to recenter the rotation on all three axis, or at least X and Y. Unity provides UnityEngine.XR.InputTracking.Recenter() But that will only recenter the Y Axis. Oculus Integration provides OVRManager.display.RecenterPose() But under the hood its just using the Unity InputTracking.Recenter() again. So how can I recenter my whole scene or the player on y axis as well? If you go to Oculus GO main menue and push the recenter button on your controller, it does exactly what I want. However I can't find a way to do the same thing in my Unity application. Thanks in advance! |
0 | Unity3d High level literature Is there any high level literature for mid professional programmers for Unity? There are a lot of tutorials for beginners, but I can't find anything about main API, pipeline or engine architecture. Recommend, please! |
0 | Unity Menu navigation using keyboard controller input? I am trying to create a character stats menu that uses keyboard controller input to navigate between options instead of the mouse. I have not found any tutorials for this kind of UI navigation. In this way, pressing "Up" "Down" will highlight the closest button above below the current selection, and pressing "Left" "Right" will highlight the closest button to the left right of the current selection. This is how console menus, especially for popular JRPG's, worked. Two example images of what I am talking about In this top level menu, only the 8 options in the upper right are selectable, although not all options are necessarily present when the game begins. The finger pointer icon is used to highlight a button This is the Equip menu. Equipable items are pushed into this menu as they are collected and can be scrolled through with the cursor. If the user presses "left", the cursor will jump to whichever character's valid equipment slot is closest Could anyone explain (briefly or otherwise) how to make a menu like this? WIP The hand cursor does not move yet. It is supposed to snap to highlighted buttons. |
0 | What is the most efficient technique for range detection? I have a bunch of patrolling enemies that fire projectiles when the player is in projectile range a specific radius. Which method is the most efficient and elegant? overlapSphere sphereCast triggers square magnitude anything else? I am using Unity. |
0 | UI button not working Every time I try to click on the button, nothing happens. I am linking some picks to help everyone answer my question. I have added a event system. I have a canvas. The button is set to interactable. |
0 | Sending RPC calls from server to client inside Unity In my game inside Unity, I have two scenes setup. One for the main server ( acts like authoritative server ) and the other scene for my client. The game starts once my client connects to the server. Now I am able to send RPC function calls from my scripts in my client scene to the server but I am not able to do it the other way around. Further edit to my code after comments This is my client side script attached to GameObject CursorDetection inside Scene2 using UnityEngine using System.Collections ON THE CLIENT SIDE public class CursorDetectionScript MonoBehaviour private bool hasGameStarted false void Update() if (Input.GetMouseButtonDown(0)) networkView.RPC("mouseDown", RPCMode.Server,true) RPC public void mouseDown(bool isMouseDown) On the server side script inside scene1 private void OnPlayerConnected(NetworkPlayer player) Debug.Log(" PLAYER CONNECTED " player) networkView.RPC("AddNetworkPlayer", RPCMode.AllBuffered, player) RPC public void AddNetworkPlayer(NetworkPlayer player) playersList.Add(player) Debug.Log(" FIRST PLAYER IS " playersList 0 ) if(startGame) networkView.RPC("SendMessageToClient1", RPCMode.AllBuffered, playersList 0 ) RPC public void mouseDown(bool isMouseDown, NetworkMessageInfo sender) isMouseDown true Debug.Log("CAN PLACE PANELS NOW" " VIEW IS " sender.sender.guid) back on the client side script inside scene2 I called the SendMessageToClient1 function call RPC public void SendMessageToClient1() Debug.Log(" INSIDE CLIENT 1 ") |
0 | How to instantiate a sprite from a sprite sheet using script in unity? We are creating a 2D top down rpg, and we have multiple textures, and we need to be able to change which sprite sheet its reading from in order to change the look of the walls and floor in each room. It has the same basic tiles just they need to look different. Like the corner of a cabin, to the corner of an office building. At the moment we are taking the sprite sheet, splitting it up, and making prefabs out of it for placement by script in the game. Is there a way to do this automatically because we have a lot of textures, and its too many to make into prefabs. |
0 | Update the UI Rotation According to camera rotation I have a camera which is showing the userInterface (canvas) object into the front of my camera. I am only updating my userinterface position if the camera raycast is not hitting my userInterface object collider. something like this public class UIPlacerAtCamFront MonoBehaviour public GameObject userInterface public float placementDistance Vector3 uiPlacementPosition RaycastHit objectHit void Update () Vector3 fwd this.transform.TransformDirection(Vector3.forward) Debug.DrawRay(this.transform.position, fwd 50, Color.green) if (Physics.Raycast(this.transform.position, fwd, out objectHit, 50)) raycast hitting the userInterface collider, so do nothing, userinterface is infornt of the camrea already else raycast is not hitting userInterfae collider, so update UserInterface position accoding to the camera uiPlacementPosition this.transform.position this.transform.forward placementDistance userInterface.transform.position uiPlacementPosition Continuously update userInterface rotation according to camera userInterface.transform.rotation this.transform.rotation The above script has attached with my camera, it displaying the object correctly but as i start to rotate my camera my UI object rotation looks very strange as below image suggested As i rotate, this problem occurs I know that the problem is in rotation, so I tired to change my this rotation code userInterface.transform.rotation this.transform.rotation to this userInterface.transform.localEulerAngles new Vector3 (this.transform.localEulerAngles.x, 0, this.transform.localEulerAngles.z) but it bring another strange rotation for me, like given below I want that my userinteface object face my camera correclty, even my camera watching the start or end of my userinteface object. How can i rotate my UI according to camera rotation correctly? |
0 | Make object face another object on a sphere I have a game I'm working on in Unity where there are two objects on a sphere at random locations (and random rotations). I want one of the objects to always rotate so that if it were to fire a bullet (the end goal) that it would fire at the other object along the shortest arc around the sphere. The problem I'm facing is that I don't know how to create a rotation for an object that is on the surface of a sphere, and have it point towards the other object. I can also see an issue after this where I would need it to point towards the other object in the shortest distance because there will always be two directions it can point towards. Has anyone done something like this? Definitely stuck on this one. |
0 | Avoiding audio transcoding in Unity? I'm working on a project where I only have access to MP3s versions of audio tracks I'd like to use. Unity is trying to be helpful and recompressing everything as Vorbis, which is not ideal due to quality loss. Even if I override the audio clip settings and set it to use MP3, Unity still transcodes the file for me, resulting in quality loss. I can set the clip to PCM, which would avoid re encoding the file into another lossy format, but the resulting file size is too large to be practical. In a perfect world I would have WAV versions of all the tracks I want to use, but that is not the case. Is there anyway to tell Unity to use the file the way it is and to leave it alone and not recompress it? For the record I am using Unity 5.3.1 and my project target is iOS. |
0 | How do I determine the position of one vector relative to another? I'm making a game for Kinect in Unity which tracks hand movements. I have the player's root position and the position of their fist stored as 3 dimensional vectors (Vector3 in Unity), but they're both in world space. How can I determine the location of the player's fist relative to their root position? |
0 | Fade into scene in Unity SteamVR I am using this code below for a gradual fade into a scene next level in Steam VR (HTC Vive) The whole idea is to cover up the scene loading icon which is viewable for 3 4 seconds, and the default Steam landscape scene. The fade (to red) works fine BUT it comes in after the loading icon so this defeats the whole purpose of it. Is there any simple way to fix this? thanks public class NewFade MonoBehaviour private float fadeDuration 4f private void Start() FadeFromWhite() private void FadeFromWhite() set start color SteamVR Fade.View(Color.red, 0f) set and start fade to SteamVR Fade.View(Color.clear, fadeDuration) |
0 | Starting Couroutine in newly activated gameObject I'm working on a UI system that animates an element's properties using coroutines. Every element that should be animated has a component called AnimatedUIElement which provides the function Enter(). The function Enter() is basically starting coroutines depending on the chosen animation settings, but only after calling Enable(), which sets the gameObject active with gameObject.SetActive(true) , updates its component references and makes the element interactable. AnimatedUIElement also defines an Exit() function acting similar, but disabling the element after the animation. public class AnimatedUIElement MonoBehaviour private CanvasGroup canvasGroup ... public void Enter() ... TriggerEntry() private void TriggerEntry() PlayChildrenEntry() Calls Enter() on all animated Children Enable() StartCoroutine(SomeAnimation(...)) private void Enable() gameObject.SetActive(true) Init() canvasGroup.interactable true canvasGroup.blocksRaycasts true private void Init() canvasGroup GetComponent lt CanvasGroup gt () ... private IEnumerator SomeAnimation(...) ... public void Exit() Similar to Enter, but disabling the element Now I want to open the options panel by clicking a button in the game's UI. The panel is inactive (unticked) in the beginning, while the AnimatedUIElement component is enabled. UI Hierarchy Options Button calls Enter() on Options Panel. The desired setup in the Button Component calling OptionsPanel.Enter() and MainPanel.Exit() But clicking the button throws the following exception Coroutine couldn't be started because the the game object 'Main Menu Button' is inactive! UnityEngine.MonoBehaviour StartCoroutine(IEnumerator) AnimatedUIElement AnimatePosition(Vector2, Vector2, Single, AnimationCurve) (at Assets Animated UI Elements AnimatedUIElement.cs 265) AnimatedUIElement TriggerEntry() (at Assets Animated UI Elements AnimatedUIElement.cs 93) AnimatedUIElement Enter() (at Assets Animated UI Elements AnimatedUIElement.cs 73) AnimatedUIElement PlayChildrenEntry(Transform) (at Assets Animated UI Elements AnimatedUIElement.cs 219) AnimatedUIElement TriggerEntry() (at Assets Animated UI Elements AnimatedUIElement.cs 79) AnimatedUIElement Enter() (at Assets Animated UI Elements AnimatedUIElement.cs 73) UnityEngine.EventSystems.EventSystem Update() In this stack trace you can see that the Options Panel did not start coroutines as no animation was defined in its component, but called Enter() on its children, which are animated. Using debug logs I found out that, while Init() is called immediately after Enter(), Awake() is called after the coroutines (which happen later in the program flow) throw errors. This makes it seem like the object is not available instantly after calling setActive(true). Is there an explanation and possibly a fix for this behavior? |
0 | How to make score counter independent of framerate I have a score counter, but I've noticed that the lower the framerate is, the slower it counts. How can I make it so it ignores the framerate? using System.Collections using UnityEngine using UnityEngine.UI public class Score MonoBehaviour private Text scoreText private static int score private static int finalScore private static bool count public static int scoreMultiplier private void Start() scoreText GetComponent lt Text gt () count false scoreMultiplier 1 public static void StartCounting() count true public static void StopCounting() count false public static void Reset() count false score 0 public static IEnumerator MultiplyBy(int scoreMultiplier) Score.scoreMultiplier scoreMultiplier yield return new WaitForSeconds(6f) Score.scoreMultiplier 1 private void Update() if (count) score scoreMultiplier Slice the score so the number doesn't get too big finalScore score 4 scoreText.text finalScore.ToString("00000") Edit Fixed by adding Time.deltaTime and putting it in FixedUpdate instead of Update private void FixedUpdate() if (count) score scorePerSecond Time.deltaTime scoreMultiplier finalScore Convert.ToInt32(score) scoreText.text finalScore.ToString("000000") |
0 | AI Behaviour design pattern which handles lots of diverse behaviours and mechanics? I'm working on an 2D overhead topdown game in Unity3D and I want the enemies to have lots of diverse behaviours. How should I design the architecture with this in mind? For example I want A simple walking monster, which can move on walkable tilemaps, attack the player on sight. A spider like creature, which jumps from wall tile to wall tile, and approaches the player in this manner. I want a snail which walks on a route, and makes a trail (ie by flagging the tiles) behind itself, apart from this, it's unresponsive (like doesn't care if the player attacks itself) A werewolf, which can smell the player from X tile away. (Like there is a walkable path to the player) 50 more unique behaviours... Needless to say, I'm not talking about how to implement this, but how could I design a system which will be robust enough for this many behaviours, not really error prone, low amount of code duplication, etc. Thanks in advance! |
0 | How can I make a custom mesh class in Unity? I'm doing something in Unity where I need to specify the position and orientation of vertices with two Vector4s, and they're not just position and normal vectors. I've already written my custom shader and now I need to make mesh objects that can be fed into it. So how do I make my custom mesh? Should I inherit from the mesh class? Will I still be able to use the normal mesh filter and mesh renderer components or should I replace those too? I am comfortable coding the data structure for my new mesh, the question is interfacing with the Unity rendering pipeline and sending the data to my shader in the right way. |
0 | Unity build shows wrong date I made a 3D game in Unity named Sniper Shot. I am facing a problem when I build the project at the end it shows the wrong date of build. I have tried many scripts resolving this issue but I did not find any accurate way to fix it. I completed this project on 4 march 2019 but this is showing me a wrong date, 23 July 2017. |
0 | Why isn't my method an option for onClick? Update The problem went away when I restarted Unity and tried again. The problem I am using Unity 2019.1.8f1 Personal with Visual Studio for Mac 7.8.4. I have a button named Refresh I would like its onClick handler to be the public instance method Refresh() in the class Libretto. My GameView has the Libretto script as a component The script Libretto.cs includes using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using UnityEngine.Assertions public class Libretto MonoBehaviour, IInputHandler Other members omitted public void Refresh() Code omitted My scene Scene Libretto has a Canvas that contains a Button named Refresh In the onClick() section of the Refresh component, I selected GameView, which is a GameObject When I try setting the function, the method Libretto.Refresh() is not an option Attempted solutions Searching online, I have found these solutions, none of which work for me The method must be public. (It is.) The method must be void with 0 or 1 parameters. (It is void with 0 parameters.) The script should contain using UnityEngine.UI (It does.) Try creating a new object with just the script and use that. (This makes no difference.) Your code must compile with no errors. (It does.) Full project I have tried to make my question complete, but, if anyone wants to look at my code, it is available on GitHub in espertus UnityWordGames (a fork of Roger Engelbert's code from his book Word Games With Unity). A sibling scene, Scene Crossing, in the same project has a similar Refresh button and Refresh() method that work properly. Update It worked after I restarted Unity. |
0 | Get all supported resolutions for a monitor I've been receiving complaints from users that my game doesn't support the 16 10 aspect ratio. Currently I list everything in Screen.resolutions in a dropdown and allow the user to pick from that. I have since come to the understanding that the first element is not necessarily the native resolution of the monitor. I've found the Display class but this appears to only give the native resolution, not all scaled resolutions. E.g. if the monitor is 1920x1080 then I need a list of 1600x900, 1280x720, 640x360 etc. I thought about just multiplying by some scale factor but then I'm afraid I'll get something obscure like 885x497.8. And if I have a pre determined list of resolutions for a specific aspect ratio, how do I support obscure aspect ratios like widescreen for example. |
0 | Unity stop play only background music I have a music sound clip simply drag n dropped to my hierarchy. I also have other sound effects in my game. I want to pause play background music on button press but only music, not all sound effects. How can I reach this music GameObject in C code? |
0 | How to draw a diagonal sine wave line renderer I'm trying to use a LineRenderer component to draw a sine wave from point A to B and I'm using mouse position. However what I did so far is not working as expected, it just draws a sine wave along the x axis and it's not diagonal. private void Update() if (Input.GetMouseButtonDown(0)) Vector3 newPos Camera.main.ScreenToWorldPoint(Input.mousePosition) newPos.z 0 CreatePointMarker(newPos) GenerateNewLine() private void CreatePointMarker(Vector3 pointPosition) Instantiate(linePointPrefab, pointPosition, Quaternion.identity) private void GenerateNewLine() GameObject allPoints GameObject.FindGameObjectsWithTag("PointMarker") Vector3 allPointPositions new Vector3 allPoints.Length var pointList new List lt Vector3 gt () for (int i 0 i lt 50 i ) var dir allPoints 0 .transform.position allPoints 1 .transform.position float x dir.x i float y Mathf.Sin(x Time.time) var sine new Vector3(x, y, 0f) var tangentLine allPoints 0 .transform.position sine pointList.Add(tangentLine) SpawnLineGenerator(pointList.ToArray()) private void SpawnLineGenerator(Vector3 linePoints) GameObject newLineGen Instantiate(lineGeneratorPrefab) LineRenderer lRend newLineGen.GetComponent lt LineRenderer gt () lRend.positionCount linePoints.Length lRend.SetPositions(linePoints) |
0 | Moving towards and switching targets in Unity with collision I have these nodes set up for a ship to move towards over time with out looking stops then repeats in a sequence. like so 1 2 3 1 2 3 1 2... THE PROBLEMS i keep having either come from the inability to switch direction or the ship ignores all collision which i would like to be able to shoot it with actual objects. Ignores all Collision Vector3 currentPosition thisShip.transform.position Vector3 directionOfTravel targetPosition currentPosition directionOfTravel.Normalize() thisShip.MovePosition(currentPosition directionOfTravel speed Time.smoothDeltaTime) This one works perfectly but because MovePosition is a kin to translate and actually teleports objects it ignores all collision which i need. Can't Switch Direction Vector3 currentPosition thisShip.transform.position Vector3 directionOfTravel targetPosition currentPosition directionOfTravel.Normalize() thisShip.AddRelativeForce(currentPosition directionOfTravel speed Time.smoothDeltaTime, ForceMode.Force) so in this one i try to stop the rigid body by returning its velocity to zero and it does stop for a second but continues in its original direction anyways. thisShip.velocity Vector3.zero Use this to pause object I believe i need another method of movement (maybe use a CC) or maybe i can make AddRelativeForce work and be able to switch targets like MovePosition does. I'd really like to get this one thing done so i can move on to other parts of the project. |
0 | How can I prevent the knob from resizing when I use the Slider? I am using the Unity Slider component. I have a custom background and custom knob. But whenever I move the slider, my knob's size becomes distorted. It is 100x100 pixels, and when I set it to its native size, it does so. But I soon as I move the slider, it cuts its height in half. How can I prevent this from happening? |
0 | Increase sound tempo in Unity when new player joins in Kinect game I'm using Unity to create a Windows build game with Kinect. I have some drum beats, which can either be used as single sound effect or be edited to be a piece of continuous music. I want these drum beats to be the background sound of my game. I want the drum beats to go at a constant pace, but when new users join, the beats go faster without changing its pitch. Can I achieve this Unity with either plugin or code? Or do I need to use stuff like Max MSP to run with Unity at the same time? |
0 | Unity Analytics I see custom events in funnels, but not in the Event Manager? I've just started using Unity Analytics, and I send two custom events level1Started and level2Started. After 1,5 days, the first results came in The funnels are working, so my custom events do reach Unity Analytics. But in Event Manager I can't see the mentioned events by themselves. 4 days already have passed, the funnel is updated every day, but the Event Manager is still empty. Or I'm looking at the wrong page? Then where can I see the raw number of events? Why? UPDATE For some reason, it took 12 days for them to show up in the Event Manager as well. Anyone knows why? UPDATE AGAIN Now it's gone again. Why? |
0 | Unity download image from Firebase database I am currently trying to download an image using Google Firebase. The database stores a URL to an image on Firebase storage, Unity pulls the URL from the DB and uses Unity WWW to download it. However the texture shows up as a red question mark texture. If I use a http URL from another website however it works, is Unity able to download from https addresses? This downloads the URL from Firebase and stores it in the data url variable void DownloadViaURL() Debug.Log("Called DownloadViaURL") FirebaseDatabase.DefaultInstance .GetReference("test image") .GetValueAsync().ContinueWith(task gt Debug.Log("Default Instance entered") if (task.IsFaulted) Debug.Log("Error retrieving data from server") else if (task.IsCompleted) DataSnapshot snapshot task.Result string data URL snapshot.GetValue(true).ToString() Start coroutine to download image StartCoroutine(AccessURL(data URL)) ) This uses Unity WWW to download from the URL IEnumerator AccessURL(string url) Debug.Log("Accessing texture URL in database") using (WWW www new WWW(url)) yield return www Renderer r GetComponent lt Renderer gt () r.material.mainTexture www.texture Debug.Log("Texture URL " www.url) |
0 | fbx material show correctly in unity but import to maya show wrong material see my gif, fbx material work well in unity preview, but when import it in maya, face material show wrong here is my fbx I use unitychan material in this unity asset in unity in maya the strange thing is in maya I use eye image material but show pure color material |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.