_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 | How to execute a code from many scripts I want to execute a function from many scripts attached on gameobjects which will be spawned. Since game objects are spawned, I can't assign the script in the inspector. What i want is that, there are three gameobjects, A,B,C. C is already in the scene. A and B are spawned with different scripts,the spawned gameobject's script should call the function on the gameobject C. I can make a delegate but there are different scripts that want to call the function. So should i have to create different delegates for each script on A and B and then assign them onto the gameobject C so that A and B can call their delegates and these delegates will trigger the function on C or there is something like a event that i can call from B. If it was possible, i can create a event on A and assign it on C. Now A can call the delegate and B can also call that event and trigger the function on C, but this is not possible as event can't be called from another script. I need something like a function that i can call from any script and it calls the function from C. Note that function should not be static. As i can call a static function from any script but it can call only static methods, which i don't want. |
0 | Unity 5.3.4 Controlling multiple audio sources at once? Is there a way to control the max distance of a group of audio sources at once? I want to implement all my sounds, then be able to play with some of the audiosource settings of all of them.. |
0 | Is a mesh OK to use for grass if there will be 1000's of them across the terrain? Am creating a low poly game in Unity 3D for PC. The terrain is made in Blender, so it's a fixed size, but quite large for the player to explore. I want to add things such as grass and flowers, but am not sure the best practices are for creating those types of assets. Is using a mesh for small clumps of grass the wrong way to do this if there will be 1000's of them? I will likely be using the occlusion culling system Unity provides, but I'm not sure if I still need to look at doing things such as grass in a different way for performance sake. |
0 | How to await player input using Coroutines How can I accept player input using Coroutines, pausing execution of Unity while the player has not yet provided input? It seems like a simple problem, but I can't seem to figure it out. Here is my latest attempt. In this program I want to do some logic and pause in the middle, continuing only when the player has inputted some data. Someone please tell me I'm on the right track O using System using System.Collections using System.Collections.Generic using UnityEngine public class InputTester MonoBehaviour int choice 1 valid choices for this example are 0 and 1 void Start() StartCoroutine(DoSomeLogic()) IEnumerator DoSomeLogic() print("Starting...") print("Awaiting your choice 0 or 1. ") yield return StartCoroutine(WaitForKeyDown(KeyCode.Alpha0) WaitForKeyDown(KeyCode.Alpha1)) how to combine these two into a single method that gives the player a choice? print("Continuing...") switch (choice) logic based on the choice IEnumerator WaitForKeyDown(KeyCode k) while (!Input.GetKeyDown(k)) yield return null SetChoiceTo(k) private void SetChoiceTo(KeyCode keyCode) switch (keyCode) case (KeyCode.Alpha0) choice 0 break case (KeyCode.Alpha1) choice 1 break StopAllCoroutines() how do I stop all the coroutines that accept player input? print(choice) |
0 | Typedef redefinition error when running Unity iOS project in Xcode 9 simulator I was able to run my Unity 2017.1.0b10 iOS project successfully on my iPhone 6S (Using Xcode 9). I changed the Target SDK to Simulator SDK to try it out on other device simulators then I got the following errors in the UnityMetalSupport.h file. Below are screenshots of my player settings |
0 | Move objects in array with positions array I am trying to get a line of spheres to move around but all i get is the first sphere to move and get the rest to follow as one instead of building a sort of a train of spheres. Any idea how to alter the code to get it right? In the code bellow i get the first pbject in listBalls to move nicely along the Bezier curve but the rest move as one and overlap with the first sphere too. void Update() t Time.deltaTime 0.2f ballPosition Mathf.Pow(1 t, 3) p0 3 Mathf.Pow(1 t, 2) t p1 3 (1 t) Mathf.Pow(t, 2) p2 Mathf.Pow(t, 3) p3 positions.Add(ballPosition) listBalls 0 .transform.position positions j for (i 1 i lt listBalls.Count i ) Transform ball listBalls i .transform Transform nextBall listBalls i 1 .transform if ((ball.position nextBall.position).magnitude gt 1f) ball.position positions j j Feels like it should be something easy, setting the N 1 balls to same position as the first ball must be wrong. I tried setting them at positions j 2 but it didn't work either. Edit the Spheres should start rolling left to right one after the other eventually all 10 should be on the screen and when they reach P3 they should restarting the rolling. listBalls is the List with 10 spheres positions is the List with 50 Vector3 positions along the curve. ! enter code here 2 2 |
0 | HIGH energy consumption in Empty Scene Unity iOS I am struggling from quite long about this issue where I am having High Energy Impact in Unity 2019.2.16f1 on iOS platform and it doesn't matter which device I am using. It occurs on iPhone6 to iPhoneX also I tried in an empty scene and checked stats through xCode and still bar is in Very High. Can someone explain to me what is going on? because of this device gets heat up quickly. Below are stats with empty scene. I have tried following still Very High Framerate to 30 SetResolution to 720 x 1080 Compressing Textures Multi threaded Rendering enabled and disabled Auto Graphics API turned on and off in player setting Though I am making game and I don't want to set resolution too low or to compress textures, I want as much attractive graphics as unity can offer. Also is this estimation of GPU Utilization calculated on based on total capacity of GPU vs how much the app is taking at the moment? I am totally blocked here and I need to improve energy impact of my app. |
0 | Does it make sense to export and use skeletal animation as sprites? As tools like Dragonbones, Spine lets you export animations as both sprite atlas and skeleton data (JSON binary), I'm not sure which format to use when importing to Unity. I have few concerns Will there be any differences between the quality of the animations, when imported as atlas vs skeleton data? Any other pros and cons, using one over the other? If I use a sprite atlas, I don't have to depend on a third party runtime though. It is for mobile, so performance is also a concern. |
0 | Can I reset the DisallowMultipleComponent attribute in child classes in Unity somehow? Can I reset the DisallowMultipleComponent attribute in child classes in Unity somehow? I want to create my base class DisallowMultipleComponent public class MyCompanyClass Monobehaviour I want all my component scripts to inherit from the MyCompanyClass. So, I will be able to add only one instance of my component script to a game object at a time. I need it for most of my classes. But for some classes I still want to preserve the ability to add a few class instances to a game object, while still inheriting from the MyCompanyClass (because I am going to put some custom behavior into it, which is going to be used by all my component scripts). So, I was trying to search for something like AllowMultipleComponent , but found nothing. Is there maybe another way to achieve what I want? |
0 | Sharing Physics in Unity I'm making a game with an endless mode where you have to dodge asteroids until you eventually die. Since the game could be endless, I wanted to avoid the coordinates issue mentioned here. My player ship remains at 0,0,0. The asteroids spawn at the top of the screen and "fall" to simulate the player flying past them. The player can also accelerate and decelerate. I have tried scripting asteroid movement, but now I would like to try using Unity's physics to simplify code. When accelerating decelerating I could add force to all existing asteroids, but then asteroids which haven't spawned yet will not reflect the player's current speed. I basically want all asteroids to have the same speed. I was thinking maybe I could create a dummy physics object that I can apply forces to, that also keeps track of its speed. It would be great if all objects could just reference this dummy object's speed and forces. Is something like this possible with Unity's physics? Or is there a better way to do what I'm attempting? |
0 | How to target specific material with Unity VideoPlayer? I've modeled the following tv monitor This monitor has two materials. The "frame" that makes up the monitor, called MonitorFrameMaterial and the black screen material, called MonitorScreenMaterial. I've added the Video Player to the monitor and would like to play a video "on the screen material". Here's a screenshot of the inspector I've already searched the web for some time to find an answer, but I can't seem to find a way to play the video on the screen. Whenever I add a video now, it actually targets the monitor frame (probably because it's the first material?). Is there any way to change this, and if yes, how? Thanks! |
0 | How is entering cover animation done for cover system? I am trying to create a cover system for my 3rd person shooter game in Unity. My implementation is a basic one On Player enter Trigger Player move to preset cover position Player play Enter Cover animation (eg dash to cover) This is fine without root motion enabled, when it is enabled (so the movements look natural), instead of dash amp stop behind the cover, the Player will dash and stuck himself inside the cover (due to root motion). So I am curious, what is a good way to do the animation for cover system? |
0 | Unity, Replace or modify camera with own script I am making an RTS game which has a slowdown when many units are on screen at once. I have a plan to write my own camera script to speed this up. Since I have an efficient way to find where units are without the raycast, I want to write scripts to replace the camera and check raycasts against only the few objects that my scripts will identify as in the correct area for that raycast? Alternatively is is possible to have the camera ignore certain entities on one part of the screen, and then a different set on another part of the screen? Edit I am very grateful for people helping in anyway, but I wanted to know if this Could be done even if in my case it shouldn't be. |
0 | How to calculate acceleration distance(frictionless, massless) Object A is moving via. 2D rigidbody by velocity V and in script is defined breaking power P. Every frame of breaking (P Time.deltaTime) is subtracted from velocity V (in other words, ignoring mass). How i can calculate distance D required to slow down to target velocity tV ? I'm not actually using force power but i setting velocity directly with this line of code Vector3 dir transform.TransformDirection(Vector3.up) ship.rb.velocity Vector2.MoveTowards(ship.rb.velocity, (dir maximalSpeed) ship.massModifier, speedGain ship.massModifier) (Don't worry about ship.massModifier, Basically heavier ship hulls are slower) I'm self learning Indie developer and i need this for AI to my game. Enemy in space ship have nothing like space breaks so only way how to slow down is to turn ship by 180 degrees and thrust forward in counter direction.I need to know this to calculate distance from target required to slow down and prevent possible collision with target. |
0 | Detecting a 3 x 3 grid and extracting its coordinates using Kinect I'm interested in creating a DDR (dance dance revolution) game using unity3D and Kinect. However I need to do this without actually using a pressure sensor pad, just a mat with grids and numbers on it. Here is what the Grid is supposed to look like I need to be able to track where the Mat is placed on the floor and a way to check which number is the user stepping on. The user feet coordinates can be tracked via skeletal tracking, however the grid coordinates and boundaries need to be extracted. Is there a way to do this without using openCv and can opencv be used with Kinect and unity3d? |
0 | Unity animations in iOS I'm an iOS developer and I'm trying to make 2d animations with Unity 4.3 RageTools Pro RageSpline. I want to integrate the animations into a native iOS application. In Unity I have different kind of animations, different characters, and I want to control these separately in Xcode. I know how to build unity project to Xcode and I know how to customize the Unity view in Xcode, my problem is that I can't access individually the animations, I can't loop them and I can't switch them in a specific view. My another problem is that the built Xcode project from Unity is too large (more than 300 MB). So the question is if I continue to develop the character animation within unity is it possible to handle separately the animations in Xcode? Or do I have to find a another solution (use another animation tool, or export from unity into some different file format like FBX). In summary I want to make a simple iOS app with simple animations and i'm looking for the simplest solution. Thanks in advance for your help. |
0 | How to make rigid body move smoothly on uneven platform? Right now I'm using Rigidbody2d for the game character along with polygon collider 2D(2d platform game). I'm beginner hope I'm using correct components. And transform to move character from left to right. Character.transform.Translate(Vector2.right speed Time.deltaTime) And upward(jump). Character.transform.Translate(Vector2.up speed Time.deltaTime) When the game character moves on slopes there's lot of friction and bounciness and rotation and its worse when jumping from slopes. |
0 | In Unity displaying long lists of information to screen? Tables? Hello folks I'm making a little game for fun in unity, Its a boxing management sim. I've got the code done to create boxers and give them many properties such as names, weights, stats, etc. I've made another screen , lets call it 'office screen' for now. In that I want to open a panel which will show all the boxers in the game (ideally I'd like to be able to make the player be able to filter these results by which company he's signed to etc but I think that might be out of my skill range so maybe i will just make a separate screen for Owned Boxers) But I cannot seem to find a way to display all these infos in a table with columns such as Name Age Company etc I have had a go just using the UI Text components and panels. But thing is, there will be approx 100 boxers or more and this number will always change also. Any ideas for this in Unity specifically? EDIT I am storing all the data just as variables (i think fields) in a class called Boxer which is assigned as a component of a new GameObject i instantiate at the time each boxer is created. So each boxer has its own gameobject. EDIT 2 D i've found this https docs.microsoft.com en us aspnet mvc overview older versions 1 models data displaying a table of database data cs would this be the sort of thing I can add to Unity (assuming I can follow along with the guide)? Thanks for any help |
0 | How does one get sprites to hide unhide using OnMouseDown() in Unity? I'm right now using Unity for a school project and I need to be able to hide and unhide sprites for "expansions". I've looked all over the internet for this and I can't seem to find an answer. Here is the script so far using System.Collections using Systems.Collections.Generic using UnityEngine DisallowMultipleComponent public class addBlock MonoBehaviour void OnMouseDown() Debug.log(gameObject.name) |
0 | Tracking how many people play my Unity game in which language? In my game the user can change the language of the game and I'd like to know how many people play it in English, German, etc. I'm using Unity, so possibly I would like to implement in Unity Analytics. I was thinking about adding segments for the languages, but in that case if a user tries all languages, the user will appear in all languages' segments. So it won't really provide that much info. A possible solution When the user changes language, we signal a database to decrease the old language's counter and increase the new language's counter. But there must be an easier, built in solution than this. |
0 | Why does releasing a pressed "f" key not prevent the coroutine from spinning? I am learning Unity and the following is my simplification of the code presented on Coroutines. My expectation is that the Fade() just spins in a very very short period of time because the GetKeyDown("f") is true only at the transition from "unpressed" to "pressed" states. However in the following code, the Fade() spins from f 0 to f 999 continuously (non stop in one go) rather than for example, from f 0 to f 100 at the first key press and from f 101 to f 159 at the second key press, etc. IEnumerator Fade() for (int f 0 f lt 1000 f ) Debug.Log( " f ") yield return null void Update() if (Input.GetKeyDown("f")) StartCoroutine("Fade") Question What causes this unexpected result and how to solve it? |
0 | how to sync clients and local avoidance in mobile RTS game? I have been making mobile RTS game in Unity look like Clash Royale similarly. Unfortunately, I faced to two big problems. First is two phones(clients) to be synchronized each other in game state. And second is "path finding" or "local avoidance"(collision check). To solve the path finding issue, I have searched about "Flow Field". Should I do consider on 3 layer map(cost field, integration field, flow field) to apply "Flow field"? If I do apply "flow field" to my game, can I have a liberty from the problem of Sync two clients? Thank you in advance. |
0 | Changes to one Unity trail renderer causes all of them to flicker I'm using Unity. So I have a prefab, and this prefab has a trail renderer component attached to it. However, for some of the game objects I want to stop the trailer renderer at certain points in time. But doing so seems to make all of the trail renderers blink flash off and on. I've tried changing time, disabling the component, and using Clear() while hiding the trail renderer behind the background before needing to be used. All of these makes all trail renderers flicker on the frame the change happens. I believe providing the code won't be helpful, it's just if(x) disable action, if(y) enable action. What can I do? |
0 | Unable to list target platforms. Please make sure the android sdk path is correct For some reason, I am unable to test my android program because of this error. Here are some pictures of the errors. This error is not allowing me to test my app on my test Android device, I have tried uninstalling and reinstalling, checking if it is acatually the root folder, everything, PLEASE HELP! 1st error CommandInvokationFailure Unable to list target platforms. Please make sure the android sdk path is correct. C Users jayso AppData Local Android sdk tools bin avdmanager.bat list target c stderr stdout ERROR JAVA HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA HOME variable in your environment to match the location of your Java installation. exit code 1 UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.RunAndroidSdkTool (System.String toolName, System.String arguments, Boolean updateCommand, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) UnityEditor.Android.AndroidSDKTools.ListTargetPlatforms (UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit) UnityEditor.Android.AndroidSDKTools.GetTopAndroidPlatformAvailable (UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK SDKPlatformDetector.GetVersion (UnityEditor.Android.AndroidSDKTools sdkTools) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK SDKComponentDetector.Detect (UnityEditor.Android.AndroidSDKTools sdkTools, System.Version minVersion, UnityEditor.Android.PostProcessor.ProgressHandler onProgress) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (System.Version minVersion, UnityEditor.Android.PostProcessor.Tasks.SDKComponentDetector detector) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (Int32 minVersion, UnityEditor.Android.PostProcessor.Tasks.SDKComponentDetector detector) UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) UnityEditor.BuildPlayerWindow BuildPlayerAndRun() 2nd Error Error building Player CommandInvokationFailure Unable to list target platforms. Please make sure the android sdk path is correct. C Users jayso AppData Local Android sdk tools bin avdmanager.bat list target c stderr stdout ERROR JAVA HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA HOME variable in your environment to match the location of your Java installation. exit code 1 |
0 | Is there a way to get native resolution of device window display on android? When change the framebuffer resolution by calling Screen.setResolution(1920,1080) Screen.currentResolution, Screen.width, Screen.height reports back the new resolution 1920x1080. Screen.resolutions gave me empty array (tested on real android device). I am unable to get back the original resolution which was a native resolution of the device. Do I have to remember the native resolution or is there a way to get that through unity API ? |
0 | Why are my screenshots created through a RenderTexture too small? Current render result When I am rendering image in Unity and saving as file(.png), quality of those files are reduced. They become tiny and very poor. How can I enhance that? Dimension of the image file is 269 168. Code to save image using UnityEngine using System.IO using System getty code public class Capture MonoBehaviour private static int resWidth 3840 private static int resHeight 2160 private static GameObject camObj null public static string ScreenShotName() return string.Format(" 0 screenshots 1 .png", Application.dataPath, Util.name ) void Start() camObj gameObject Directory.CreateDirectory(Application.dataPath " screenshots") resHeight GetComponent lt Camera gt ().pixelHeight resWidth GetComponent lt Camera gt ().pixelWidth Util.everyThingHot true public static void TakeHiResShot() try RenderTexture rt new RenderTexture(resWidth, resHeight, 24) camObj.GetComponent lt Camera gt ().targetTexture rt Texture2D screenShot new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false) camObj.GetComponent lt Camera gt ().Render() RenderTexture.active rt screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0) camObj.GetComponent lt Camera gt ().targetTexture null RenderTexture.active null Destroy(rt) byte bytes screenShot.EncodeToPNG() string filename ScreenShotName() File.WriteAllBytes(filename, bytes) Debug.Log(string.Format("Took screenshot to 0 ", filename)) bytes null catch(Exception e) Debug.Log("Error") Sample What I see during saving shot It's taking a lot CPU,GPU resources, renders correctly but doesn't give me what I want as a file |
0 | NullReferenceException Object reference not set to an instance of an object on boolean variable from separate class I'm trying to develop game scenario that able to trigger the alarm with alarm light and siren audio to play. For the testing purpose I set it that to boolean value as "alarmOn" in AlarmLight class. AlarmLight.cs public class AlarmLight MonoBehaviour public float fadeSpeed 2f public float highIntensity 2f public float lowIntensity 0.5f public float changeMargin 0.2f public bool alarmOn false private float targetIntensity public Light light add alarm lights tag as siren void Awake() light.intensity 0f targetIntensity highIntensity void Update() if (alarmOn true) light.intensity Mathf.Lerp(light.intensity, targetIntensity,fadeSpeed Time.deltaTime) ChecktargetIntensity() else light.intensity Mathf.Lerp(light.intensity, 0f, fadeSpeed Time.deltaTime) void ChecktargetIntensity() if (Mathf.Abs(targetIntensity light.intensity) lt changeMargin) if (targetIntensity highIntensity) targetIntensity lowIntensity else targetIntensity highIntensity Then I tried to access that value with LastPlayerSight class and for the testing purpose i was trying to return false as below. alarm.alarmOn (playerPosition ! resetPlayerPosition) Then I tried to play my scene, and I got the error which is the problem with above line of code. This is my LastPlayerSight.cs class public class LastPlayerSight MonoBehaviour public Vector3 playerPosition new Vector3(1000f, 1000f, 1000f) public Vector3 resetPlayerPosition new Vector3(1000f, 1000f, 1000f) public float lightHighIntensity 0.25f public float lightLowIntensity 0f public float fadeSpeed 7f public float musicFadeSpeed 1f directional alarmlight ref private AlarmLight alarm main directional light ref private Light mainLight private AudioSource panicAudio siren audio private AudioSource sirens void Awake() alarm GameObject.FindGameObjectWithTag(Tags.alarms).GetComponent lt AlarmLight gt () mainLight GameObject.FindGameObjectWithTag(Tags.mainLight).GetComponent lt Light gt () GameObject sirenAttachedGameObjects GameObject.FindGameObjectsWithTag(Tags.siren) sirens new AudioSource sirenAttachedGameObjects.Length for(int i 0 i lt sirens.Length i ) sirens i sirenAttachedGameObjects i .GetComponent lt AudioSource gt () void Update() SwitchAlarms() MusicFading() void SwitchAlarms() alarm.alarmOn (playerPosition ! resetPlayerPosition) float newIntensity if(playerPosition ! resetPlayerPosition) newIntensity lightLowIntensity else newIntensity lightHighIntensity mainLight.intensity Mathf.Lerp(mainLight.intensity, newIntensity,fadeSpeed Time.deltaTime) for (int i 0 i lt sirens.Length i ) if (playerPosition ! resetPlayerPosition) sirens i .Play() else sirens i .Stop() void MusicFading() AudioSource audioTemp audio.GetComponent lt AudioSource gt () if (playerPosition ! resetPlayerPosition) audio.GetComponent lt AudioSource gt ().volume Mathf.Lerp(audio.volume, 0f, musicFadeSpeed Time.deltaTime) panicAudio.volume Mathf.Lerp(panicAudio.volume, 0.8f, musicFadeSpeed Time.deltaTime) else panicAudio.volume Mathf.Lerp(panicAudio.volume, 0.0f, musicFadeSpeed Time.deltaTime) I'm beginner of developing such things and can anyone guide me to correct the problem? |
0 | How to import a texture to be used as occlusion map? The same way normal maps need to be imported as "Normal map" in the import settings, how should I setup an Ambient Occlusion texture to correctly work? I've been searching around in the manual and the web but still not sure if AO maps should be imported as Lightmaps. |
0 | Loop around a 2D Tile Map I have made an algorithm for procedurally generating a 2D tile map in Unity. The player can use the mouse to pan the view and look at the map. My intention was that when the player reaches one of the sides of the map, he would simply see the other side as if he was going around the Earth so to speak. The only way I have achieved this is by simply instantly setting the camera's position to the other side of the map when the player crosses one of the edges. The problem with this is that the player never actually sees the "border" connection continuously and that bothers me since I took the care to generate the map in such a way that connecting the east west edges makes sense. How can I achieve the desired effect? |
0 | Mobu Motion Files Naming Scheme for Unity When exporting takes as several fbx files in Motionbuilder 2014 with File gt Motion File Export..., the files are named like so file Take1.fbx file Take2.fbx file Take3.fbx In order for the motion files to be loaded into Unity correctly, I have to rename them to file Take1.fbx file Take2.fbx file Take3.fbx Having to replace underscores with ' ' is fine for small projects but can become time consuming when working with many takes in large projects. Is there a way to change the default naming scheme in Motionbuilder, through preferences or python scripting, so that the default underscore is replaced with an ' '? |
0 | How can I call Schedule() on interface that inherits from IJob So I have a voxel terrain engine, and I have an interface that all meshing jobs should inherit from. That looks like this (simplified from the actual) public interface IMesherJob IJob VoxelDataVolume lt byte gt VoxelData get set NativeArray lt MeshingVertexData gt OutputVertices get set NativeArray lt ushort gt OutputTriangles get set One example of a meshing job is marching cubes, which looks like this public struct MarchingCubesJob IMesherJob So here's my question If I have a reference to an IMesherJob, can I somehow call Schedule on it? If I have a reference to MarchingCubesJob, I can call Schedule on it This works MarchingCubesJob myMeshingJob GetMeshingJob() JobHandle handle myMeshingJob.Schedule(voxelCount, 64) But this does not work IMesherJob myMeshingJob GetMeshingJob() JobHandle handle myMeshingJob.Schedule(voxelCount, 64) I noticed that Schedule() is an extension method for T where T struct, IJob so that might be interfering with it, but it should still work because IMesherJob inherits from IJob |
0 | How to create a "border" effect in Unity? Okay let me start off by saying I have searched for several days on this topic, and it seems that either nobody posted anything about it, or it is on the internet, but too far buried under piles of useless information for me to find. I have created a custom terrain algorithm in Unity and have built a parser to read provinces onto the map. The short version description of the parser is that it goes into the assets folder, finds "map provinces.png", reads the borders of the provinces as vertices, reads "map height.png" to determine the height of the visual terrain, and reads "map terrain.png" to determine how much of each province is of each terrain (for example, Paris can be 95 urban, and 5 forest in my setup). I want to make each and every one of the 500 european provinces start with a player. The idea is that the players will fight small scale wars for 30 40 turns, by which point most or all small players will be absorbed into the most successful players country. These will then fight for 60 80 turns for dominance, with alliances being forged and broken and countries being destroyed. The problem is described below Each player has his own unique color. Many of the players will obviously have similar colors, and I do not want 2 dark red countries bordering eachother without some easy way to see the border. I want to basically draw a line in between any two provinces that belong to different players and border each other. I am having trouble finding a way to easily do this, as my current solution tests all provinces if they border foreign provinces, and runs a rather expensive test on each of the bordering provinces vertices to see if they border eachother, then stores those vertices as vectors and draws a line from each vertex to its others. I have considered using a shader to accomplish this, but was unsure if that was the right approach and whether or not that would (or could?) be more efficient. |
0 | How do I differentiate between the two Vive motion controllers? I am working with a Vive Pre (devkit) and I have most everything working the way I want it to. However I am wondering how do I refer to or even know which motion controller is which? From what I can tell the headset is ALWAYS assigned first into a list, and the others are seemingly randomly assigned. So how do I differentiate between the two or refer to one separately? |
0 | Animated textures for models How to write a shader? Was watching some Rocket League and notice there was animated decals and wheels. . I would like to implement something similar to the effects in the image above. How would I go about writing a Unity Shader to do the wheel effect? I don't know much about Shaders, but can I edit the standard Unity Shader to do the animation effect? |
0 | How to create a repeating gif style imagery for a game tutorial dialog I want to create a gif style video that shows up in a tutorial window using Unity. How can I make this? Do I record the thing I want to show and then put it in a texture? Example |
0 | What's the difference between Mathf.Lerp and Mathf.SmoothDamp I want to smoothly go from one value to a new one (moving a slider or changing color). I tried using both functions and they all basically give the same result. What is the difference between them and which one should I use? How I used SmoothDamp Show the HUD private IEnumerator ShowHUD() var HUDCanvasGroup GameObject.FindWithTag("HUD").GetComponent lt CanvasGroup gt () var alphaValue 1f var velocity 0f var time 0.30f yield return new WaitForSeconds(1.5f) Gradually fade in the canvas while (!Mathf.Approximately(HUDCanvasGroup.alpha, alphaValue)) HUDCanvasGroup.alpha Mathf.SmoothDamp(HUDCanvasGroup.alpha, alphaValue, ref velocity, time) yield return null HUDCanvasGroup.alpha 1 Since float is not accurate, manually set the alpha to 1 after HUDCanvasGroup.interactable true var blur GameObject.FindWithTag("BlurryCamera").GetComponent lt BlurOptimized gt () blur.enabled true How I used Lerp public static IEnumerator Dim() while (t lt 1) t Time.deltaTime 0.4f dimRend.material.color Color.Lerp(undimColor, dimColor, t) yield return null |
0 | OnTriggerEnter error The message parameter has to be of type Collider I have a crate and I want to make it so if you are in the trigger of the crate a UI appears and says quot Click E to loot quot . I have the UI setup but the script is not working. Here is my script and after it are the errors. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class UI Appear MonoBehaviour SerializeField private Image image void OnTriggerEnter(Collider2D other) if (other.CompareTag( quot Player quot )) image.enabled true void OnTriggerExit(Collider2D other) if (other.CompareTag( quot Player quot )) image.enabled false The errors say Script Error OnTriggerEnter The message parameter has to be of type Collider Script Error OnTriggerExit The message parameter has to be of type Collider |
0 | How to add Facebook Data Storage to Mobile Game? I was wondering how I would add the option for players to sign into their Facebook profiles on my mobile game and then have Facebook store their game save data, so they can recover it on any device when they sign into Facebook. Other Facebook features would include seeing their friends on the Facebook leaderboards, inviting their friends to the game and challenging their friends to beat their scores. I would hate for the Player's data to be lost, so the Facebook data save part is very important. A good reference to this feature is the Hungry Shark mobile game. I wasn't sure how this works. My programming friend and I are creating the game together, but he doesn't know how to do this and I don't know how to program. Once I figure out exactly what has to be done, I would like to hire a programmer who knows how to add this feature. Thank you! |
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 | How to fix double click problem in this code? Please see the gif below to better understand what's going on. On first click they all work normally but after first click I have to double click them to select them. I'm not a advanced developer so I've been trying to figure this out for straight 2 hours and last choice I wanted to ask you guys. I declared select effect here. (White circle) And added an Array to get all select effects. public GameObject selectEffect private bool isSelected false public GameObject selectEffectArray I put them inside the Array. private void Awake() selectEffectArray GameObject.FindGameObjectsWithTag("planetSelected") selectEffect transform.Find("selectEffect").gameObject I deactivate all select effects on start. void Start() Deactivate() Here's Deactivate code. void Deactivate() foreach (GameObject effect in selectEffectArray) effect.SetActive(false) When I click one of the planets these happens. (I'm a little confused so I hope you can understand it.) void OnMouseUp() if (isSelected) selectEffect.SetActive(false) travelbutton.SetActive(false) isSelected false else Deactivate() planetName text.text planet.name requiredFuel text.text planet.requiredFuel.ToString() travelbutton.SetActive(true) selectEffect.SetActive(true) isSelected true I don't want to double click a planet to select it. |
0 | How to code camera for layered map in unity For a current unity project I need a layered map like in Dwarf Fortress. The game will take place in a 3D city enviroment and the camera should be 'snapped' to layers. So there will be (for example) a cave layer, ground layer and floor 1 3 layer. The player should be able to navigate the camera up and down with a keypress. So if the player is looking currently at the ground layer and press the camera should snip to floor 1 layer. All layers below the current level will be blurred and all levels above wont be visible (or at least faded out very strong) My question now is Is the layer system of unity useful for such a scenario, or is it better to implement an own data structure? I know about the ability of ignoring layers for rendering and raycasting but can the system be extended to support the features described above? |
0 | Unity C Rotate smoothly an object towards the direction given by input I am trying to rotate an object towards the direction given by de direction of the input. For example, if I am pressing 'up' of the directional pad, the player should rotate pointing that direction. I've tried using Euler angles, and when I press the direction, I call a coroutine that sums the eulerAngle.y of the object till it gets the angle of the direction, but it doesn't work. I don't know if there is another approach to use. Here is the code for the coroutine. It starts if a certain key is pressed and if a flag is not activated IEnumerator rotateTowards(float angle) rotating true Debug.Log("Rotating the mono...") Debug.Log("Your angle " transform.eulerAngles.y) float turningTime 0.8f float thisAngle this.transform.eulerAngles.y Vector3 thisAngle this.transform.eulerAngles if(thisAngle.y lt angle) while(thisAngle.y lt angle) thisAngle.y turningTime Time.deltaTime this.transform.eulerAngles thisAngle if(thisAngle.y gt angle) while(thisAngle.y gt angle) thisAngle.y turningTime Time.deltaTime this.transform.eulerAngles thisAngle this.transform.eulerAngles thisAngle rotating false yield return null Thanks in advance. |
0 | Parenting a child object to parent in Unity I am making an 3d Tennis game in Unity 5.0. I have made 3d model of the Tennis player in Makehuman and have successfully imported it to Blender and Unity. I want to add an tennis racket in the hand on my Makehuman model. So what should the strategy be? Should I add the tennis racket to the Makehuman character in Blender as the child of the Makehuman model and then animating it or is there a simple way to do that in Unity in the game. |
0 | How to slow down a Sphere smoothly in a world controlled by force and stop it (Unity 5)? I am a beginner and I started to use Unity 5. I play with tutorials on the site and documentation. I was basically testing springs, physics materials etc. I have a problem understanding probably a very basic thing I have a Sphere (Collider Rigidbody) and a Ground (Mesh Collider). I add force to Sphere on FixedUpdate with GetAxis method. I added Physics material to both sphere and the ground to create a friction. Ball slows down when I do not touch the keys (no new forces) but it never stops while moving on the ground. I know that as only 1 point is touching the gorund friction may not be good enough, but it almost does not affect the ball after a certain period. (I print the speed of the ball (Sphere) on a GUIText so I can numerically check it there too.) I am aware of default Sleep treshold value but it will effect everything as it is a global variable, so I can't use that. So, ball never sleeps. I am aware of drag and angular drag (like the friction of Air) of Rigidbody component and they for sure work, BUT it feels like the ground is sticky and ball stops very quickly. It doesn't look smooth and natural. Is there something that I am missing? The only way to do this is checking the speed of the ball and making it sleep manually when it's speed is low? Isn't there any other method? I don't want to do this as the world itself must live itself I don't want to check movement of every single object.. This is probably one of the most basic things, but I cannot understand why it doesn't work.. |
0 | How to get crash reports from game Unity3d I am working on a project and I am in need of to gather CrashReports, email crash log, along with allowing the user to describe how the crash happened. I cannot find anything on how to do this, anyone has any ideas? Thanks! Learning Unity User |
0 | How to remove an element from the scene while keeping it in array? I combined cube meshes to make a big one. I stored the info of every cube in an array within a list of chunk. Now i want to delete the cubes in the scene to only keep the combined result, but without deleting the elements in the array. After combining meshes, i want to be able do destroy cube from it. So i want to keep the info so when i click the mesh, i get the position of the cube that would be there and check if it matches wit ha cube from the array. If it does, i want to remove it from the array and regenerate the mesh without that deleted cube. How would I do that ? |
0 | When would a mesh collider be better than primitive colliders I have been reading through the Unity Manual and have come across some interesting information about mesh colliders and primitive colliders. It got me wondering if using many primitive colliders would be better than using a mesh collider for say a character object? I was also wondering if there was any information on exactly how inefficient a mesh collider is to say having 20 box or cylinder colliders on a character mesh. I am guessing that the number of polygons on the mesh would be a factor but it would be interesting to see some raw comparisons between how this efficiency scales per polygon (or per 100 polys or some unit of measurement) |
0 | Change axis to view world from above in Unity Developing a 2d game where you view the "table" from above (think of a card game being played on a table). I have a candlestick on the table, but I must have something wrong because when I run it, it thinks it's on a wall versus a table because the flame goes up to the top versus "at" the camera from above. Here's the code of that "LookAt" script public class CameraFacing MonoBehaviour public Camera cameraToLookAt void Awake() cameraToLookAt Camera.main void Update() Vector3 v cameraToLookAt.transform.position transform.position v.x v.z 0.0f transform.LookAt(cameraToLookAt.transform.position v) |
0 | How can I rotate cubemap in shadergraph? I know how to rotate cube map with legacy surface shader Shader Rotation Matrix uniform float4x4 Rotation o.Emission texCUBE ( Cube, mul( Rotation, float4(IN.worldRefl,0))).rgb RotateCubeMap using UnityEngine public class RotateCubeMap MonoBehaviour public float speed 20 private MeshRenderer meshRenderer private void Awake() meshRenderer GetComponent lt MeshRenderer gt () public void Update() var rot Quaternion.Euler (0, Time.time speed, 0) var m new Matrix4x4 () m.SetTRS(Vector3.zero, rot,new Vector3(1,1,1) ) meshRenderer.material.SetMatrix (" Rotation", m) I tried to recreate it by shadergraph but it didn't work! I need a result like this |
0 | Smooth Lighting Falloff So, I'm having some issues with lighting in my Unity game. I had implemented torches, which seem to be working fine, but I have a creature (gelatinous cube) that I've put spot lights facing to give it a "glow". The reflected and refracted light ends up having two issues the light abruptly ends at the edge of floor tiles, and depending on the position, the light sometimes goes from it's blue color to a reddish color. I have a short (11 second) video here http www.labyrintheer.com wp content uploads 2016 11 Nov 17 2016 21 07 57.mp4 so that you can see what I'm talking about. I've tried changing global lighting settings and playing with the settings on the spot lights, but nothing seems to resolve the issue. Still images for anyone hesitant to click the video link Hard falloff Reddish color Using a single point light inside the cube, instead You can see it on the wall in the upper right and the floor at the top a bit. The upload seems to have lowered the quality a bit, but you can still see it. The single light makes it a little bit better, but there's still complete falloff. |
0 | Switching between meshes vs Loading only specific mesh I am currently developing an online multiplayer game on Unity. In the game, the character of each player will be assigned its mesh after the game receives parameters (their meshes' names) for each character from the server. Assigning each character's mesh can happen after the main scene is loaded. I am wondering whether I should make each character's object the same by having every mesh possible loaded into it and only activate the corresponding mesh for that player. I should create a class that holds every mesh possible (like, mesh manager) and tell each character to use its mesh from that class. I should delay the characters' meshes loading to wait for the parameter from the server first. Then, load the mesh after the scene has been loaded. I am not sure if specific assets can be loaded outside of its scene in Unity. If anyone has any different solutions, feel free to suggest. Thanks in advance. |
0 | Is it possible to measure Used vs Unused time in a 60hz frame in Unity? In custom engines I've often made a frame rate meter that shows how much of the each frame was actually used. In other words if the game is locked to 60fps using vblank I show a graph of how much of each frame was used for processing and how much was just waiting for the next vblank. This gives a visual indication of how much more can be added to a scene without hitting my frame rate budget. Is this possible to do in Unity? What I tried I made a script that creates a System.Diagnostics.StopWatch and starts it. I set that script's Script Execution Order to be the very first script. In the script's Update I record the ElapsedTicks from the stopwatch as startTicks. In the scripts's OnGUI I compute a deltaTicks as in long deltaTicks m stopWatch.ElapsedTicks startTicks I can then compute how much of a 60fps frame was taken with long ticksPerFrame System.Diagnostics.Stopwatch.Frequency 60 float amountOfFrameUsed (float)((double)deltaTicks ticksPerFrame) Note I get that OnGUI is called multiple times per frame but the way I end up storing amountOfFrameUsed I only end up recording the time from the last time OnGUI is called that frame. Anyway, this does give me a graph to look at but I have no idea if what it's slowing me is correct for Unity. In my own engine I'd record the time at VBlank and then in my code, when all processing was done I'd compute the elapsed time since vblank. Is what I'm doing correct? Is there a better or another way I should be doing this? (note I have not used the profiler because I wanted to see this FPS meter in a production app, not in the Editor where there is tons of overhead). |
0 | Visualizing NavMesh to Camera When Unity builds a NavMesh, you can see it in the scene view if you have the Navigation window open and select "Show NavMesh" in the Navmesh Display box. I'd like to use the exact same overlay in a camera view. Is this accessible in any way? Can it be rebuilt during runtime? Since the navMesh isn't an actual mesh, I can't seem to find a way to make this happen. EDIT This is what I'm trying to work with right now public class NavMeshToCamera MonoBehaviour NavMeshTriangulation triangles Mesh mesh void Awake () triangles NavMesh.CalculateTriangulation() mesh new Mesh() mesh.vertices triangles.vertices mesh.triangles triangles.indices I have this script attached to a secondary camera that will be enabled while holding down a button to see an overlay of a minimap of the current dungeon. I'm not quite sure what to do with the mesh data to provide a mesh visible to the camera. Since no mesh exists initially, I suppose I'd have to take the new mesh, apply a layer to it, and have only that layer visible to the camera. But I'm having some difficulties with this. |
0 | How to make an object track another object's exact movements This script below helps me to to tell the follower object to copy exact movements of the leader object, I found this script in Unity forums and it works pretty well. My question is how can I add some kind speed variable to it how can I tell the follower object to move at lower speed? public class delayTracker MonoBehaviour float progress const int MAX FPS 60 public Transform leader public float lagSeconds 0.5f Vector3 positionBuffer float timeBuffer int oldestIndex int newestIndex Use this for initialization void Start() int bufferLength Mathf.CeilToInt(lagSeconds MAX FPS) positionBuffer new Vector3 bufferLength timeBuffer new float bufferLength positionBuffer 0 positionBuffer 1 leader.position timeBuffer 0 timeBuffer 1 Time.time oldestIndex 0 newestIndex 1 void LateUpdate() Insert newest position into our cache. If the cache is full, overwrite the latest sample. int newIndex ( newestIndex 1) positionBuffer.Length if (newIndex ! oldestIndex) newestIndex newIndex positionBuffer newestIndex leader.position timeBuffer newestIndex Time.time Skip ahead in the buffer to the segment containing our target time. float targetTime Time.time lagSeconds int nextIndex while ( timeBuffer nextIndex ( oldestIndex 1) timeBuffer.Length lt targetTime) oldestIndex nextIndex Interpolate between the two samples on either side of our target time. float span timeBuffer nextIndex timeBuffer oldestIndex float progress 0f if (span gt 0f) progress (targetTime timeBuffer oldestIndex ) span transform.position Vector3.Lerp( positionBuffer oldestIndex , positionBuffer nextIndex , progress ) void OnDrawGizmos() if ( positionBuffer null positionBuffer.Length 0) return Gizmos.color Color.grey Vector3 oldPosition positionBuffer oldestIndex int next for (int i oldestIndex i ! newestIndex i next) next (i 1) positionBuffer.Length Vector3 newPosition positionBuffer next Gizmos.DrawLine(oldPosition, newPosition) oldPosition newPosition |
0 | WorldToGUIPoint seems always off by about 2 pixels I'm trying to draw small boxes at each vertex of a mesh, in the editor. My OnSceneGUI code looks like this foreach (Vector3 vertex in mesh.vertices) Vector3 worldVertex meshTransform.localToWorldMatrix.MultiplyPoint3x4(vertex) Vector2 guiPoint HandleUtility.WorldToGUIPoint(worldVertex) var rect new Rect(guiPoint, Vector2.one BOX SIZE) EditorGUI.DrawRect(rect, Color.red) I want the upper left corner of each box to align with the mesh vertices. With the above code, the boxes are drawn at the wrong location, as you can see in the picture below. If I apply an offset of (2, 2) in GUI coordinates, however, the boxes are drawn at the correct location. I'd like to avoid having to hard code this (2, 2) offset into each draw call. Why is Unity off by a few pixels here? I also tried using GUI.Box to do the drawing, but it was off by the same amount. What is going on? Incorrect Correct. With constant (2, 2) offset Update I have an untested hypothesis as to why this is happening. I am rendering a GUI rect with the default GUIStyle. The default GUIStyle has the padding and margin values set. I bet that if I created a custom GUIStyle with zero padding and margin the rects would draw where I want them to. |
0 | How to create a walkable crate box? I have a 2D platformer with each platform having a PlatformEffector2D component. I want to create a crate that can be pushed. When I jump into the edge of the crate, my player gets stuck, so I added PlatformEffector2D to the crate. But when the crate has a PlatformEffector2D component it falls below the platform. I can remove the component and add a Physics2D Material with zero friction to prevent the player from getting stuck in the crate's edge, but I can't walk above the crate (because the zero friction). The images below illustrate it. Player getting stuck in the edge of the crate that don't have PlatformEffector2D. If it has a PlatformEffector2D it will fall below the platform. My objects have the following components (when the player gets stuck at the edge of a crate) Player (BoxCollider2D, Rigidbody2D) Crate (BoxCollider2D, Rigidbody2D) Platform (EdgeCollider2D, PlatformEffector2D) What should I do so my player can push the crate and walk above the crate? Would anyone happen to have a sample script? FYI I use Physics2D.OverlapCircle to detect the ground. (Unity 5.4.0) |
0 | Is it possible to debug a Unity Android game directly on a device? I'm working on my game and every time I make changes to it I send the game to my mobile device to debug it. I want to know how I can directly debug my game using an Android device instead of the MonoDevelop editor? |
0 | How can I make the overlapping object's outlines merge and not display on top of other objects that have the outline shader? This is what I am trying to achieve. I was following https www.youtube.com watch?v SlTkBe4YNbo but the outlines show on top of other if the objects overlap. I tried looking through various outline shaders but couldn't find much. I found that it has something to do with Z Depth but I am not sure how. My reason for doing this was to replicate the Unity Editor's object selection in the project. I somehow got the gizmo partially working(using a 2nd camera) and am now stuck on object highlighting on selection. |
0 | Stop Camera up movement I am developing 3D game , the main camera is child of player. When player jumps camera too gets move up with player as its child of player.Is there anyway to stop this behavior? The only thing I can guess is to make camera separate gameobject and let it follow player EDIT After applying Everless Drop 41's script, here is what main problem arises |
0 | 1 bit game How to change the palette for the entire game at runtime? So I'm making a 1 bit color game, and would like to have an option in the menu to change what those two colors are so the player can adjust it to their liking. What is the simplest and or best method to go about this? This would apply to the entire screen, not individual sprites meshes, as I want to preserve the 1 bit color look. Most of my assets are sprites, with a few flat meshes that are rendered without anti aliasing so that they blend in with the sprites. They're all exported with the two standard colors I'm using (a yellow ish off white and a dark grey ish blue), but I can go back and re export them in black and white if that is necessary for the suggested method. My eventual plan is to support the basic black and white, a few monochrome monitor color schemes, and some color combinations that you'd see on 8 bit computers (C64, Apple, etc.). |
0 | How can I separate gameview from UI most efficiently in Unity? Let me provide an image to illustrate what I mean. It is from a game called Runescape. |
0 | In Unity, how do you check if a camera is rendering anything? (Unity 2018.3) I'm trying to have a camera automatically disable if it's not rendering anything. Is there a simple way to check if a camera is blank empty? Edit Alternatively, is there a way to prevent a camera from rendering if there is nothing in it's view? For example, I do not want MSAA applied to a blank camera. (I'd hope it would attempt AA, but effectively do zero work) |
0 | How can I "amplify" current motion ? I've two objects A and B. A impact B causing B movement. I want programmatically "amplify" B movement mantaining B resulting direction. I've try adding a script like this void OnCollisionEnter(Collision col) Controllo se un tag if ( forceAlreadyApplied false) rb.AddForce ( forcePower transform.forward, ForceType) forceAlreadyApplied true The problem is that transform.forward obviously change B direction. Maybe this is a wrong approach. My question is how to "amplify" current speed ? Thanks |
0 | Unity2D Horizontal Scaling to Support Various Aspect Ratios? I am trying to work out how to support various resolutions for my Android game. I have come up with a solution, but do not know how to implement it. Automatically, I am told that Unity vertically scales the screen to match the screen, leaving more room at the sides. How can I change this behaviour? I am hoping to shrunk the game down till it fits horizontally, and filling it the background above and below with more decorative features. How can I achieve this? I'm sorry if there is an obvious answer, I'm quite new working with the Unity UI system. If it makes it any easier, my game is heavily based on UI, and is locked in landscape. BIG EDIT I completely rephrased this question because it was so broad and messy. |
0 | How do I check if animation is of Animation Type "Humanoid"? One can set the Rig Animation type of an animation to quot Generic quot , quot Humanoid quot , etc. How could I check by script if an animation rig has been set to type quot Humanoid quot ? |
0 | How to set parent for prefab in Unity I have a prefab of a button (btn) that I need to set parent ( canvos) for it after it spawned (online)... I have try this code public Transform btn public Transform mkn public Image canvos public void test () Transform InTank Network.Instantiate (btn, mkn.transform.position, Quaternion.identity, 0)as Transform btn.SetParent( canvos) But it doesn't work. error MissingReferenceException The object of type 'Object' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. what's the problem?? |
0 | How do I get a popup menu to block clicks from hitting UI elements beneath it? You can see in the picture that I have a Canvas with a popup menu in it. I just enable this, and it covers the main menu stuff. Clicks go through it and hit stuff in the main menu. I've tried adding an EventTrigger to the PopupRoot object, and adding an event to listen for PointerClick events, but it doesn't fire. EventTrigger trigger m popUpRoot.GetComponentInChildren lt EventTrigger gt () EventTrigger.Entry entry new EventTrigger.Entry() entry.eventID EventTriggerType.PointerClick entry.callback.AddListener((eventData) gt PopupClickBlocker((PointerEventData)eventData) ) trigger.triggers.Add(entry) I'm open to other suggestions. My current system is horrible button click events query the Popup to see if it's enabled or not, then return doing nothing if it is. This doesn't work for sliders very well, so I want to do this the right way. |
0 | Create an atlas texture in photoshop to use in unity To create a button in NGUI looks like we need to create something called Atlas that is a material that contains a lot of little images called Sprites. I created a set of 40 sprites (for 20 buttons needed in game, normal state and clicked state) in photoshop in a 2048x2048 image file. When i tried to use NGUI atlas maker i realized that atlas maker requires each sprite in a separate file and wants to merge them in the atlas itself! Well, i already have them in one file, should i slice all these buttons and save them in 40 other separate files and let the atlas maker merge them again for me? (Sounds very stupid!) Isn't there any way to give the merged 2048x2048 file to atlas maker (or any other equivalent plugin software) and then tell the software "Hey! I have 40 sprites in this image, let me tell you where they are! The first one is in (3,3) with size of (150px, 150px), The second one is..."? UPDATE I found a part of solution, unity could identify my 40 sprites in texture using sprite editor tool, but NGUI cannot still find them. I created a material using "Unlit Transparent Colored" shader and referencing the atlas to it, then i created a new empty game object, added UI Atlas component to it and referenced the material in it, but it says there are no sprites. If i make a prefab out of this game object then NGUI can use it as an atlas and my problem will be solved |
0 | Admob for Unity clarification on use needed I'm following this documentation by Google on how to integrate Admob ads into my game and I'm confused because of the following This documentation says I build by game and then I mess around with ads. (Section Unity plugin API tells me how to add ads and that's after the build instruction). Shouldn't it be vice versa? That I place those ads and build last? Or, if I really do build first, where do I add those ads? |
0 | Unity3d iOS build where are the textures? First time building and running my Unity3D app on my iPhone and it appears that all the textures are missing. Everything is just a solid block of whatever color I made it. When running in Unity I see everything correctly. See images below. To complicate things I'm using custom shaders, and all the objects are custom procedural meshes. Quads that I build in script. If I switch the paper backplate shader to a built in shader I still only see white on the iPhone. So I suspect that somehow the textures just aren't making it to the iOS project. When I look in the iOS project I can't find any textures. Where would they be in the iOS project? For example in Xcode under Build Phases Copy Bundle Resources the only thing there is the Images.xcassets, which only contains the splash screens and icons. Surely I'm missing something simple. I tried renaming the folder where I keep my textures to "Textures". Also my textures are not built in to the shader but added programmatically like this void Awake () meshFilterComponent GetComponent lt MeshFilter gt () Material material GetComponent lt MeshRenderer gt ().material material.SetTexture(0, paperTexture) material.color new Vector4(1f, 1f, 1f, 1f) Where paperTexture is set up in the GameObject to point to the correct texture. Is there any way to force a texture to be part of a build? Let's say that you swap out textures in code, like swapping themes, how would you make sure they're all there to be loaded as needed? Running On iPhone Running In Unity3D |
0 | Unity OnGUI streamlining So like most games, I have inventory screens, equip screens, shop screens, and all that. I've previously been making each "screen" controlled by its own script (which is normal I think), and I draw the screens using GUI. However, I'm worried about having multiple OnGUI functions in my game (one OnGUI for each "thing" I draw eg Inventory or Shop ) since OnGUI really isn't that best for performance. How should I solve this problem? I thought about making each screen its own scene in the game but I wasn't sure if that would help things much. |
0 | How do I make an object's y axis align with a Vector3? I have a golf ball on the ground, and from a raycast, I have the normal which gives me the slope of the ground by the ball. I have an object which is rendered on the HUD to show that slope to the player. I have a parent object rotated 90 degrees around X, so that the indicator's Z axis points up. This way I can do this Quaternion yRot Quaternion.Euler(0, CameraController.Instance.CachedTransform.eulerAngles.y, 0) Vector3 displayGroundNormal yRot groundNormal lieIndicator3DParentCachedTransform.rotation Quaternion.LookRotation(displayGroundNormal) This, as far as I can tell, takes the ground normal, rotates it around the y axis so that it shows the proper perspective given the camera's facing. Then it tells that parent object to look in that direction, which aligns its z axis with the rotated ground normal. This works, except the object I have also rotates around the y axis depending on the orientation of the camera. I thought that I was throwing that information away in the second step by keeping only a Vector3 aligned with the ground normal rotated for the camera position. So I want this Not this |
0 | Unity3D AI follow player script for prefab enemy? So I am having an issue, I have an enemy prefab that is created when the new wave happens(think of Nazi Zombies from Call of Duty, same system) but every script I have found that deals with ai following player always involves a public transform variable. The issue is that the object I put in that variable in the inspector does not save with the prefab, rendering the script useless. Is there anyway I can get the enemy prefab when the enemy spawns to follow the player? He is a script I tried and failed due to the issue The target player public Transform player 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 private void Start() Call every frame void Update() Look at the player transform.LookAt(player) Move the enemy towards the player with smoothdamp transform.position Vector3.SmoothDamp(transform.position, player.position, ref smoothVelocity, smoothTime) Time.deltaTime |
0 | Passing Gameobject to another script in unity 3d I'm trying to pass a gameobject from one script to another runtime attached script. My fisrt script is attached to the FirstPlayerController and the gameobject is not dragged in the editor, but is picked up and carried in the script. All i want is to pass the gameobject to the CameraController class to as make the second camera follow that object. Below is what i've tried so far. I dont want to access the gameobject with the tag, because there are more gameobjects that can be picked up. I want to access the carried object to the cameracontroller class. Thanks! Pickupobject.cs using System using System.Collections using System.Collections.Generic using UnityEngine public class pickupobject MonoBehaviour GameObject mainCamera bool carrying public GameObject carriedObject public float distances public float smooth float speed 1000f new Camera camera Use this for initialization void Start() mainCamera GameObject.FindWithTag("MainCamera") camera GameObject.FindWithTag("secondCamera").GetComponent lt Camera gt () camera.enabled false Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.T) amp amp carrying) carrying !carrying ThrowBall() if (carrying) carry(carriedObject) else pickup() private void pickup() if (Input.GetKeyDown(KeyCode.E)) int x Screen.width 2 int y Screen.height 2 Ray ray mainCamera.GetComponent lt Camera gt ().ScreenPointToRay(new Vector3(x, y)) RaycastHit hit if (Physics.Raycast(ray, out hit)) pickupable p hit.collider.GetComponent lt pickupable gt () if (p ! null) carrying true carriedObject p.gameObject camera.enabled true camera.gameObject.AddComponent lt CameraController gt () carriedObject.AddComponent lt MovingBall gt () void carry(GameObject o) o.GetComponent lt Rigidbody gt ().isKinematic true o.transform.position mainCamera.transform.position mainCamera.transform.forward distances void CheckDrop() if (Input.GetKeyDown(KeyCode.U)) Drop() void Drop() ThrowBall() void ThrowBall() mainCamera.SetActive(false) camera.enabled true carriedObject.AddComponent lt CameraController gt () camera.gameObject.AddComponent lt CameraController gt () carriedObject.AddComponent lt MovingBall gt () carriedObject.GetComponent lt Rigidbody gt ().isKinematic false carriedObject.GetComponent lt Rigidbody gt ().AddForce(0f, 0f, speed) CameraController.cs using System.Collections using System.Collections.Generic using UnityEngine public class CameraController MonoBehaviour public GameObject icosphere public GameObject abc Vector3 offset Use this for initialization void Start () icosphere GameObject.FindWithTag("purpleball") offset transform.position icosphere.transform.position Update is called once per frame void Update () transform.position icosphere.transform.position offset |
0 | Photon2 Unity2D How to send float with RPC I have big problem in my code .. I want to spawn obstacle exactly on the same position as on the server is spawned so I made rpc Method and tried to pass random variable of float , but when i run the game obstacles are spawned on the diffrent position. I am loosing a lot of time to get it done but I still can not find solution. Here is the code PunRPC void RPC SpawnColumn(Vector3 position) Instantiate(prefab, position, Quaternion.identity) Debug.Log("THIS IS SPAWNYPOSITION" spawnYPosition) Instantiate(prefab, new Vector2(9, spawnYPosition), Quaternion.identity) private void OnTriggerEnter2D(Collider2D collision) print("Are we here") if (collision.GetComponent lt ColumnsMultiplayer gt () ! null) print("Or are we here") if (SpawnOnce) spawnYPosition Random.Range( 3.36f, 2.98f) photonView.RPC("RPC SpawnColumn", RpcTarget.Others,new Vector3(9, spawnYPosition)) this is SpawnColumn() SpawnOnce false Thank you so much for reading post. Edit I need to send spawnYPosition from method two to method one and spawn it with same position of spawnYPosition in the second method. |
0 | How to rotate an object to a specific transform? I am working on a car racing game and there are some times when the car rotates and ends up on its roof. On those situations I want the car to respawn on the same location. What can I do to rotate it so the car ends up on its wheels? |
0 | How can I cut a doorway through my wall at runtime? I am working on a Unity project where I have 3 models a stacked, rounded wall (think logs), a flat wall (think bricks), and a door. The door has an animation to open close itself, and when it's attached to a wall, there's one major problem when the door swings in, it reveals not the empty space one would expect, but the segment of wall it's layered on top of! Since all 3 models are part of dynamic mesh structures, I can't "pre calculate" what the model should look like to account for the empty space of the door what if the player puts the door on the next segment of wall instead? I considered expanding the "door" model to a "door wall segment" model (replacing that wall segment entirely), but because I already have two separate shapes of wall, it quickly becomes a combinatorics problem 2 models for each door, per door shape (not to mention windows, or a 3rd or fourth! wall shape!). In short, this doesn't seem like a tenable solution. What would work most cleanly is if I could remove a "Door shaped" segment of my Wall segment mesh, leaving a clear hole that the Door model could snugly fit. In an equation Final Mesh A Mesh A Volume (Mesh A Volume Mesh B Volume) Is an operation like that feasible? My gut tells me that polyhedron intersection is hard, and there might be a better way to do this. I'm also equally interested if someone has a better suggestion on how to solve the initial problem of doors intersecting with wall segments. |
0 | How to rotate a local position offset based on a direction vector? I'm trying to fire three raycasts in the direction of movement, from offset starting points. I'm having trouble calculating the start positions of the rays based on the direction. As you can see in the animation, the three parallel lines in the middle overlap when moving upwards using the code below, but I want them to remain evenly spaced. I cannot use transform.right (up etc) etc because the transform is always facing the same direction by design. Instead I am using the currentDirection which is the normalized last movement velocity. I want the lines to always be evenly spaced based on the direction the object is moving without rotating the actual transform the problem is I don't know the math behind it and have spent last several hours trying to figure it out. Current code Debug.DrawRay(this.transform.position, currentDirection (avoidObjectsScanDistance 0.05f), Color.blue, 0.09f) Debug.DrawRay(this.transform.position new Vector3(0, 0.1f, 0), currentDirection (avoidObjectsScanDistance 0.05f), Color.magenta, 0.09f) Debug.DrawRay(this.transform.position new Vector3(0, 0.1f, 0), currentDirection (avoidObjectsScanDistance 0.05f), Color.blue, 0.09f) I've tried to get the position based on direction by using var drawRayTopPos currentDirection localpos position |
0 | Unity scaling and animations In my Unity project I have a script that programmatically changes the scaling of an object during the game. Recently I wanted to add a spawning animation clip to my object, which modifies the object's scaling (but only during a short delay). So I added an animation controller to the object, containing the spawning animation clip. I can now successfully run the spawning animation but the in game programmatic scaling changes don't work anymore, even when my animation is not running. Any idea? |
0 | How to access arrays of prefabs and other properties through the inspector in a given hierarchy The script below is added to an empty game object WeaponGroup, which can be populated using the editor. I have made a new game object WeaponGroups which should have a script SetupWeaponGroupsScript. How can I transfer the properties below so that each WeaponGroup (SetupWeaponGroupsScript will have an array of WeaponGroup objects) is setup in a way similar to what is done below, so that I make the SetupWeaponsScript properties hidden to the inspector and populate them through SetupWeaponGroupsScript? public class SetupWeaponsScript Here's our tuple combining a weapon prefab and a direction. System.Serializable public struct DirectedWeapon public WeaponScript weapon public WeaponScript.Direction direction The prefabs array is now this tuple type. public DirectedWeapon weaponPrefabs public WeaponScript weapons void Start () weapons new WeaponScript weaponPrefabs.Length for (int i 0 i lt weaponPrefabs.Length i ) Using typed Instantiate to save a GetComponent call. weapons i Instantiate lt WeaponScript gt (weaponPrefabs i .weapon) weapons i .weaponDir weaponPrefabs i .direction In other words I'd like to have the following hierarchy in the editor |
0 | Moving the rendered object the projection perspectives based on an AR marker I saw this video and now I am trying to making it. I have used Vuforia AR Camera Pulgin, and so far tracked the image on a marker but the problem is getting the four projections of the 3D object on a screen. Here is an example of what it looks like. I have used Viewport Rect method with four cameras but that does not seem to change the projections as I move the marker. |
0 | How do I prevent falling tiles from bouncing on each other in my match 3 game? I am working on a match 3 game in Unity. The tiles have a RigidBody2D in dynamic mode and a BoxCollider2D. When a match occurs and the tiles are removed, the tiles above (including spawned replacement tiles) fall until they land on another tile or the tile catcher at the bottom of the board. There is a routine which checks when everything is settled (all tile rigidbodies are asleep) and then processes any new matches. However, the tiles push each other down on impact, causing a rebound and a very slow process of "settling" to their final position. The physics material for the tiles has no bounciness, so I believe this is being caused by the cumulative force of the tiles landing on each other in the physics simulation. What I'm hoping to do is have the tiles drop the way they do (the gravity simulation is just right!) but essentially stop when they collide with another tile (i.e. not transfer any force at the point of collision). This way, they shouldn't rebound visually and also should sleep more rapidly, so matches from falling can process more immediately. So far, the suggestions I've seen are Set the velocity to 0. This doesn't work, and I assume it's because there is still being force applied. Detect the tile collision and set the tile to kinematic, then set it back to dynamic. I haven't been able to get this to work, as they won't turn back to dynamic. I even tried to disable the colliders until they turn back in case the collision detection keeps happening and is just overwriting it too rapidly. At any rate, this feels like a dead end. Scrap the rigidbodies and essentially write my own, scripted gravity simulation. I'm simply hoping to avoid this because the rest of the simulation is working great. Create a kinematic rigidbody on a child object, set the dynamic parent and kinematic child to ignore collisions with each other, make the kinematic collider slightly (0.1) larger so it collides first. I gather the idea here is to have the physics simulation pull down the dynamic body, while the kinematic child will stop on collision. At any rate, this also did not work, and also sounds like a bad idea. I've considered trying to calculate the impact force and apply an equal opposing force, but I haven't figured that out yet, and I imagine at that point I should just write my own gravity simulation, per above. I've recorded a video for visual reference on the "bounciness" https youtu.be aSCEJX4nzoI |
0 | Unity ECS How do I stop an entity from spawning twice? I am implementing a flight dynamics model using Unity's built in ECS package, Entities, and I keep running into one particular issue where the aircraft I'm trying to spawn gets converted into an entity twice. Essentially, I have a singleton Monobehaviour that handles setting up the aircraft entity from a GameObject Prefab. Here's the script public class GameManager MonoBehaviour private BlobAssetStore blobAssetStore public static GameManager main public GameObject planePrefab public float zBound 0.0f public float throttleMaxBound 1.0f public float alphaMaxBound 20.0f public float bankMaxBound 20.0f public float flapMaxBound 40.0f public float throttleMinBound 0.0f public float alphaMinBound 0.0f public float bankMinBound 20.0f public float flapMinBound 0.0f public State state public Properties prop Entity planeEntityPrefab EntityManager manager private void Awake() if (main ! null amp amp main ! this) Destroy(gameObject) return main this manager World.DefaultGameObjectInjectionWorld.EntityManager blobAssetStore new BlobAssetStore() GameObjectConversionSettings settings GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAssetStore) planeEntityPrefab GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings) SpawnEntity() private void OnDestroy() blobAssetStore.Dispose() void SpawnEntity() Entity plane manager.Instantiate(planeEntityPrefab) prop new Properties( 16.2f, 10.9f, 2.0f, 0.0889f, slope of Cl alpha curve 0.178f, intercept of Cl alpha curve 0.1f, post stall slope of Cl alpha curve 3.2f, post stall intercept of Cl alpha curve 16.0f, alpha when Cl Clmax 0.034f, parasite drag coefficient 0.77f, induced drag efficiency coefficient 1114.0f, 119310.0f, 40.0f, revolutions per second 1.905f, 1.83f, propeller efficiency coefficient 1.32f propeller efficiency coefficient ) state new State( 0.0f, time 0.0f, ODE results 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, roll angle 4.0f, pitch angle 0.0f, throttle percentage 0.0f flap deflection ) float3 position new float3(state.q1, state.q3, state.q5) manager.SetComponentData(plane, new Translation Value position ) After a little bit of commenting here and there, I was able to determine that the following two lines are responsible for creating two separate entities, though the latter is the only one I'm capable of manipulating using the system. It's also worth mentioning that these two entities are virtually identical in the Entity Debugger, except for the fact that the first entity contains the quot prefab quot tag. planeEntityPrefab GameObjectConversionUtility.ConvertGameObjectHierarchy(planePrefab, settings) and... Entity plane manager.Instantiate(planeEntityPrefab) Is there a way to spawn this entity without both showing up in the debugger or is this unavoidable? If not, is there a way to remove the entity with the quot prefab quot tag from the world? Thanks! ) |
0 | combining multiple materials into one material (Unity) I am confused with how should I texture my character. I am using blender for modelling. And while my model is too complex I dont want to use uv map techniuqe. I can get what I need with using seperate materials. Therefore I assign different materials to different meshes in Blender then import it to Unity. Therefore I have lots of different material in one model and I think it increases draw call. What can I do to combine these material into just one. I thought baking would be sollution but while my character is dynamic I can not get a good result. |
0 | How to get plane geometry associated with primitive 3d plane in unity3d I assume there should be a plane (struct) associated with a primitive 3d plane in unity3d, how to get that? Or if not associated, can we build plane struct object somehow using corner vertices of 3d plane. Can somebody help me how to get cornor vertices of 3d plane mesh. Update What I am trying to achieve is to use Plane.Raycast on a 3d Plane, but I am not certain whether there is any plane geometry component associated with it, or Is there any way to build a plane geometry which should be going through all the corners of the 3d plane, so that I'll be able to use Plane.Raycast from the normal direction of 3d plane towards itself. |
0 | Unity3d Android Fixed Resolution How can i set a fixed 720p resolution on any devices using unity3d android? unity3d version 2018.4.5f1 |
0 | Sending a shot left right up down based on directional key press I am trying to make a top down shooter game with similar combat to the Binding of Isaac when I press the up key the shot goes up when I press the right key the shot goes to the right I have all the rest of the code such as the point where the projectile is instantiating and the if statement to check for the button press I just want to know where I should put the vector 2 to allow me to set the direction and what to write into the vector 2 private void Update() if (Input.GetKeyDown("up")) if (Time.time gt shotTime) Instantiate(projectile, shotPoint) shotTime Time.time timeBetweenShots This is my Projectile script (at least the parts that I think would be useful) void Update() transform.Translate(Vector2.up speed Time.deltaTime) I realized that if I change the Vector2.up to make it say Vector2.down it would now shoot down But I need that to be able to change depending on which direction I am shooting. |
0 | How do I make my character change his ability's when his sprite changes I am making a platformer and am currently trying to have it so that my character will have different powers based on his emotions, and his sprite will change to match those emotions. I have got it so that his sprite will change but I don't know how to get his powers to change as well. Note that I haven't even made his other powers yet, but even if I did I don't know how to change his ability's with his sprites as I am still very new to this whole coding thing. Can anyone please help me? Here is my code for changing his sprites, if that would help. using UnityEngine using System.Collections public class MoodManager MonoBehaviour public Sprite sprite1 happy public Sprite sprite2 angry public Sprite sprite3 sad public Sprite sprite4 default private SpriteRenderer spriteRenderer void Start () spriteRenderer GetComponent lt SpriteRenderer gt () we are accessing the SpriteRenderer that is attached to the Gameobject if (spriteRenderer.sprite null) if the sprite on spriteRenderer is null then spriteRenderer.sprite sprite1 set the sprite to sprite1 void Update () if (Input.GetKeyDown (KeyCode.Alpha1)) If the space bar is pushed down ChangeMoodHappy () call method to change sprite if (Input.GetKeyDown (KeyCode.Alpha2)) ChangeMoodAngry () if (Input.GetKeyDown (KeyCode.Alpha3)) ChangeMoodSad () void ChangeMoodHappy () if (spriteRenderer.sprite sprite1) if the spriteRenderer sprite sprite1 then change to sprite2 spriteRenderer.sprite sprite4 else spriteRenderer.sprite sprite1 otherwise change it back to sprite1 void ChangeMoodAngry () if (spriteRenderer.sprite sprite2) if the spriteRenderer sprite sprite1 then change to sprite2 spriteRenderer.sprite sprite4 else spriteRenderer.sprite sprite2 otherwise change it back to sprite1 void ChangeMoodSad () if (spriteRenderer.sprite sprite3) if the spriteRenderer sprite sprite1 then change to sprite2 spriteRenderer.sprite sprite4 else spriteRenderer.sprite sprite3 otherwise change it back to sprite1 |
0 | Unity 3d Forge Networking Transfer object ownership I have a simple chess game setup to play around with the Forge Networking asset. I am having an issue where only the server is able to click and drag pieces around the board. If a client attempts to move a piece, it gets snapped back to its original position. I assume this issue is because the server is the actual owner of the NetworkedMonoBehaviour components on my chess pieces. Is it possible to transfer ownership of a NetworkedMonoBehaviour in code? It seems that all of the owner properties have protected set methods so I am unable to access any of them. |
0 | 3D Studio Max biped restrictions? I have a stock biped character in 3D studio max which has a jump animation. The problem I have with the jump animation is that there is actual y offset happening inside it which makes it awkward to play while the character is jumping since it's not only jumping in the game world but the jump animation is adding its own height offset. I'm tryuing to remove the jump animations height offset, so far I've found the root node and deleted all its key frames which has helped a bit. The problem I'm having now is that the character still has some height offset and if I try to lower it it has a fake 'ground' that isn't at 0 and the limbs sort of bend on the imaginary floor, si there a way to remove this restriction just for the jump animation? Here's what I mean http i.imgur.com qoWIR.png Any idea for a fix? I'm using Unity 3D if that opens any other possibilities... |
0 | What is the "Unity" way to approach tech design for a 2D game like this? So I come from C land where I've always done every little thing myself. Now I'm getting into Unity and C and I'm ironically overwhelmed with the domain. I'm starting off with this simple little 2D game and I'm wondering... if someone can point me to the correct tools that would lead to a successful implementation of this game. Here is a quick mock up I did in paint These are the parts of Unity I've investigated Tilemap Canvas GridLayout Prefabs GameObjects (these seem fundamental to Unity, heh). After researching these topics, and playing around a bit, here are my initial questions How do you approach Canvases in Unity? I could see this being split into 5 separate Canvases, one for each local body of UI. Or 1 Canvas for the game board, and 1 canvas that contains a single overlay with all of the other UI components. But then how do those components typically get positioned? Is it common practice to place by absolute coordinates? I guess I'm getting hung up on.. how do I place my canvas for the game board in that position relative to all the other UI elements? I'm a C application developer so if I'm doing UI at all I'm used to layout systems. I'm not sure how common that is in this ecosystem. Should I even use TileMap for this? It doesn't seem like I need that kind of power. My grid is finite and fits on screen. My gut reaction is that I should just instantiate a bunch of colored squares at first. But I'm not really sure the best approach to that either. GridLayout on a canvas? Absolute coords? TileMap? What other tools should I be looking at? By tools I mean Unity concepts I didn't mention above. My initial thought is to just have a backing data structure that holds all the data for the grid, and then I just render... prefabs? based on that data? Maybe I just want someone to tell me I'm on the right track or quot no you're doing it totally wrong use this other thing quot , heh. |
0 | An error comes up in console when trying to enter play mode in unity Hay folks, i pray for everyone's wellbeing. I want to ask a question that whenever i enter playmode in unity, error message is displayed even though there is nothing in the console. This doesn't get fixed even after restarting unity. Any help would be great. |
0 | Unity 3D C How to properly reset a scene I have a problem when I try to reset a scene. It doesn't seem to run, I have a script (of all scripts that have Awake and Start methods on that scene) that on the Awake method starts a coroutine, but when reseting the scene it doesn't even run it. I've read that it may be a problem of using the DontDestroyOnLoad method, but that doesn't seem to solve the problem since that script on the start takes a lot of references of objects that are only on the scene that I want to restart. I don't use any static variables on any script. I made an unitary test trying to restart a scene with just one object and one script attached, on its Start method it also starts a coroutine but even in that test it doesn't even run the coroutine. Here's the script of the unitary test using UnityEngine using System.Collections using UnityEngine.SceneManagement public class LoadingSceneController MonoBehaviour void Awake() DontDestroyOnLoad(this.gameObject) Scene scene Use this for initialization void Start() scene SceneManager.GetActiveScene() DontDestroyOnLoad(this.gameObject) useStartCoroutine() void useStartCoroutine() StartCoroutine(loadScene()) IEnumerator loadScene() yield return new WaitForSeconds(3) SceneManager.LoadScene("gameplayScene 1") SceneManager.LoadSceneAsync("gameplayScene 1") |
0 | Display musical symbol (unicode) in Text component not working? I downloaded and specified to use a unicode font that supports musical symbols (Musica), but when I set the text value of the Text component to quot quot nothing is displayed? I tried using the unicode code point with U as well. What is going wrong? (I could not get TextMesh Pro working either with that symbol.) |
0 | unity read from text file to instantiate objects I'm trying to use the following code to read a text file stored in the Resources folder or in a file on my computer, and instantiate objects in a Unity 3D scene accordingly. I'm having trouble getting it to work. I've tried attaching the script to either the main camera or an empty gameobject. Neither work so far... I either end up with an error saying the path does not exist (when I put the text file into the project folder on my desktop), or a null exception, or that the path contains invalid characters. Where am I going wrong? I'm trying to use a jagged array because I'll need users to eventually be able to change the text file on the go to create a level. The text file contains the following data S 0 0 0 1 0 0 1 0 2 2 0 0 2 1 My script currently reads using System.Collections using System.Collections.Generic using System.Text.RegularExpressions using UnityEngine using System.Linq using System.IO using UnityEngine.UI public class GenerateLevel MonoBehaviour public Transform player public Transform ground public Transform floor valid public Transform floor obstacle public Transform floor checkpoint public const string sfloor valid "0" public const string sfloor obstacle "0" public const string sfloor checkpoint "2" public const string sstart "S" public string textFile "maze" string textContents Use this for initialization void Start () Instantiate(ground) TextAsset textAssets (TextAsset)Resources.Load(textFile) textContents textAssets.text string lines System.IO.File.ReadAllLines(" maze.txt") string textFile textFile Resources.Load("assets resources maze").ToString() string jagged ReadFile(textContents) for (int y 0 y lt jagged.Length y ) for (int x 0 x lt jagged 0 .Length x ) switch (jagged y x ) case sstart Instantiate(floor valid, new Vector3(x, 0, y), Quaternion.identity) Instantiate(player, new Vector3(0, 0.5f, 0), Quaternion.identity) break case sfloor valid Instantiate(floor valid, new Vector3(x, 0, y), Quaternion.identity) break case sfloor obstacle Instantiate(floor obstacle, new Vector3(x, 0, y), Quaternion.identity) break case sfloor checkpoint Instantiate(floor checkpoint, new Vector3(x, 0, y), Quaternion.identity) break Update is called once per frame void Update () string ReadFile(string file) string text System.IO.File.ReadAllText(file) string lines Regex.Split(text, " r n") int rows lines.Length string levelBase new string rows for (int i 0 i lt lines.Length i ) string stringsOfLine Regex.Split(lines i , " ") levelBase i stringsOfLine return levelBase |
0 | Calling method with enum parameters from buttons I have the following enum public enum WeaponType Sword, Spear, Blunt, Ranged And I have the following public methods on a component public void MyMethod1(int myparam) ... public void MyMethod2(WeaponType myparam) ... Why is it that when I try to call my methods from a Button component, I can not see the ones that use enumerations as parameters? |
0 | How do I make my character change his ability's when his sprite changes I am making a platformer and am currently trying to have it so that my character will have different powers based on his emotions, and his sprite will change to match those emotions. I have got it so that his sprite will change but I don't know how to get his powers to change as well. Note that I haven't even made his other powers yet, but even if I did I don't know how to change his ability's with his sprites as I am still very new to this whole coding thing. Can anyone please help me? Here is my code for changing his sprites, if that would help. using UnityEngine using System.Collections public class MoodManager MonoBehaviour public Sprite sprite1 happy public Sprite sprite2 angry public Sprite sprite3 sad public Sprite sprite4 default private SpriteRenderer spriteRenderer void Start () spriteRenderer GetComponent lt SpriteRenderer gt () we are accessing the SpriteRenderer that is attached to the Gameobject if (spriteRenderer.sprite null) if the sprite on spriteRenderer is null then spriteRenderer.sprite sprite1 set the sprite to sprite1 void Update () if (Input.GetKeyDown (KeyCode.Alpha1)) If the space bar is pushed down ChangeMoodHappy () call method to change sprite if (Input.GetKeyDown (KeyCode.Alpha2)) ChangeMoodAngry () if (Input.GetKeyDown (KeyCode.Alpha3)) ChangeMoodSad () void ChangeMoodHappy () if (spriteRenderer.sprite sprite1) if the spriteRenderer sprite sprite1 then change to sprite2 spriteRenderer.sprite sprite4 else spriteRenderer.sprite sprite1 otherwise change it back to sprite1 void ChangeMoodAngry () if (spriteRenderer.sprite sprite2) if the spriteRenderer sprite sprite1 then change to sprite2 spriteRenderer.sprite sprite4 else spriteRenderer.sprite sprite2 otherwise change it back to sprite1 void ChangeMoodSad () if (spriteRenderer.sprite sprite3) if the spriteRenderer sprite sprite1 then change to sprite2 spriteRenderer.sprite sprite4 else spriteRenderer.sprite sprite3 otherwise change it back to sprite1 |
0 | Platformer Crouching problems I'm trying to implement a crouching system to my 2D platformer. The problem is, I don't want the character to be able to do anything else except jumping when it's crouching. I have many functions but I think posting the movement function here would be enough. When I gain velocity and then press crouch, I skid across the platform, and stop. First, my crouch function private enum State idle, running, jumping, falling, crouching void Update() crouch if(Input.GetButton( quot Crouch quot )) animator.SetInteger( quot state quot , 4) Crouch() else boxCol.size new Vector2(0.5454721f, 1.8065f) void Crouch() boxCol.size new Vector2 (0.6933689f,1.44953f) And here is my movement function. I tried to fix it by adding the if condition on top of it, but when I run and crouch, it slides a lot before stopping. What can I do to fix that? The character already has a physics material with zero friction. I know I can make the velocity zero if the player is crouching but that would just kill the gameplay. I need to add a smooth stopper. I'm not sure how to make a decelerating script and use it in my case. public void Move() if(animator.GetInteger( quot state quot ) ! 4) float x Input.GetAxis( quot Horizontal quot ) float moveBy x speed rb.velocity new Vector2(moveBy, rb.velocity.y) if (x gt 0f) transform.localScale new Vector2(1, 1) isRight 1 isLeft 0 else if (x lt 0f) transform.localScale new Vector2( 1, 1) isLeft 1 isRight 0 |
0 | Alternatives to raycasts in unity? I have an ai car script. The car needs to be able to slow down and or stop if it gets too close to another car. Right now I'm using 3 raycasts like so if (Physics.Raycast(lRay, out lHit, rs.forwardCollisionRayLength, rs.rayLayerMask) Physics.Raycast(rRay, out rHit, rs.forwardCollisionRayLength, rs.rayLayerMask) (Physics.Raycast(mRay, out mHit, rs.forwardCollisionRayLength, rs.rayLayerMask))) some code... However this is really long and inconvenient because it's a pain to figure out which raycast actually had the hit. And then there's other cases where multiple raycasts hit the same car, which point do I use, or if different raycasts hit different cars...Anyway, you can see that this is not ideal. Also, depending on the size of an object, it could go between the raycasts. In the image below, the blue box is ok because its wider than the width between the raycasts, thus two of the raycasts find it. But on the other side, the green pole is too small, so the car can't see it and drives on. I also need to get the distance between the hit.point and the car so that I know how much the car needs to slow down so that there's a reasonable distance between the two cars at all times. I could use something like Physics.OverlapBox or Physics.CheckBox but then I can't get the distance between the closest point of the car, only the center of it. This is bad because some cars are longer than others I need the distance between the nearest point of the car. Also, keep performance in mind, I could solve the problem of objects going in between raycasts by adding more, but that will drain performance hugely, mainly because I have up to about 40 cars running at a time. TL DR What are some alternatives for a raycast that can also give me the distance to the closest point? |
0 | Animate moving object I have a sphere shot out of a cannon which i need to get lined up with another sphere when and if the two spheres collide. Considering that both spheres are moving (one in X and the other is shot at the first one) how would i animate the cannon sphere to line up if the collision occurs? I can use a bool to check if collision but how do i animate the projectile in the animation tab so that the projectile takes into consideration the always changing position of the X moving sphere ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.