_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Experiencing strange behavior in Unity when rotating a 2D GameObject according to the slope it is standing on I am trying to rotate a square GameObject, so it appears to be standing perpendicular to the slope underneath it. However, when above a slope, the square constantly quot spins quot it seems like the rotation is set and then immediately set back to 0, causing it to jitter. I am currently using a RayCast based character controller instead of rigidbody. To change the rotation, I added the follow line of code following the vertical RayCast if ( raycastHit) transform.rotation Quaternion.FromToRotation(transform.up, raycastHit.normal) transform.rotation ... It calculates and rotates the square correctly, but I am not sure why it resets back to 0 every other frame. To avoid taking up too much space, the character controller I am using is hosted on GitHub here. Specifically, this is in the moveVertically() method.
|
0 |
If statements seem to act as though the condition is always true I have other scripts in the same project using boolean if statements that work fine, but I've tried multiple methods of testing if the if statements below are working and none of them worked! I don't really know what to ask because I don't know whats going on. I've tried placing theae statements in Update and Start, and in both instances the if statement completely ignored the check and just executed the contents of the block as though the check evaluated to true. void OnTriggerEnter(Collider other) if(other.gameObject.CompareTag("Player")) working true Extremity false if(Extremity) Instantiate(Cannon, transform.position, transform.rotation) Extremity !true The false statement is only in there to show that even when the bool is set to false immediately before the check, it still runs the Instantiate method inside as though it were true.
|
0 |
Optimizing spawning 500 objects every 3 seconds Using Object Pooling, assuming I'll like to spawn 500 cubes once every three seconds. How do I make it performance friendly? I need ideas, not the code itself.
|
0 |
Unity Canvas blocking objects in Editor I think I am missing something really basic here..., I'm creating a 2D game in unity, and the UI Canvas (with the setting "Screen Space Overlay") is blocking exactly a quarter of my workspace. I can not select any objects on the top right part of the screen. Is there any fix to this?, or do I have to move the camera down half of the screen? Thanks
|
0 |
How can I obtain the file size of a Unity build at runtime? I'm wondering if it is possible to obtain the filesize of a game's build at runtime. Searching this topic only yields results for reducing the build size, which is not at all what I'm looking for.
|
0 |
SteamVR locks position of dynamically created cameras I'm having trouble tracking down a problem with SteamVR. Here is a quick way to set up an MWE Create a new Unity project. Import the SteamVR package from the Asset Store. Create the following script using UnityEngine public class CameraCreator MonoBehaviour private GameObject cameraObject private void Start () cameraObject new GameObject("CameraObject") cameraObject.AddComponent lt Camera gt () cameraObject.transform.position Vector3.one Create an empty game object and add this script to it. SteamVR seems to lock this object's position (and that of any other game object with a dynamically created camera component) to the origin. No matter what I try to do to change it (inspector set it inside update set it in a coroutine), it always ends up back at the origin at some point during the frame (I believe somewhere between LateUpdate and OnRenderObject, but I'm not entirely sure). Without data breakpoints I find this really hard to track down. This behaviour isn't really a problem for my actual project, but I need to be able to create cameras and modify their positions in my unit tests, where I'm having the same issue. Does anyone know what's causing this, or have any advice on how to track down the cause?
|
0 |
FixedUpdate or Subroutine So Update is called every frame while FixedUpdate is called on Physics time, which can be modified. Is it better to depend on FixedUpdate to have optimized game loop so that everything doesn't get called so much. OR Is it better to write a coroutine to Update FixedUpdate and set things there? public void Start() StartCoroutine(MyIntervalMethod()) void MyIntervalMethod() for( ) yield return new WaitForSeconds(.2f or whatever time interval is suitable here )
|
0 |
How I add gap between Instantiated objects? using System.Collections using System.Collections.Generic using System.IO using UnityEngine using UnityEngine.Networking using UnityEngine.UI public class SavedGamesSlots MonoBehaviour public GameObject saveSlotPrefab public float gap private Transform slots private string imagesToLoad Start is called before the first frame update void Start() imagesToLoad Directory.GetFiles(Application.dataPath quot screenshots quot , quot .png quot ) slots GameObject.FindGameObjectWithTag( quot Slots Content quot ).transform for (int i 0 i lt imagesToLoad.Length i ) var go Instantiate(saveSlotPrefab) go.transform.SetParent(slots) Texture2D thisTexture new Texture2D(100, 100) NOW INSIDE THE FOR LOOP string fileName imagesToLoad i byte bytes File.ReadAllBytes(fileName) thisTexture.LoadImage(bytes) thisTexture.name fileName GameObject ChildGameObject go.transform.GetChild(1).gameObject ChildGameObject.GetComponent lt RawImage gt ().texture thisTexture var raw go.GetComponent lt RectTransform gt () raw.anchoredPosition new Vector3(1 1 gap, 6, 0) Update is called once per frame void Update() The way I'm doing it now is not working it's moving all the objects to the same position and not adding equal gap's between them. In the loop I tried to do it this way in this line raw.anchoredPosition new Vector3(1 1 gap, 6, 0)
|
0 |
Mathf.Round returning wrong values I want to check if the Y position is changing or not for the player and the enemy. If it has changed in the frame I want it to return true and if it didn't I want it to return false. I round because the enemy's position alternates between 0.8 and 0.800001 . I tried to do Mathf.Round(transform.position 100) 100 and I compare is to the enemyOldPosition which I assigned using enemyOldPosition Mathf.Round(transform.position 100) 100, but it says it's not equal. I tried to check Debug.Log(enemyOldPosition Mathf.Round(transform.position 100) 100) and it returned 1.192093E 08. void Update() if(Mathf.Round(player.transform.position.y 100) 100 oldPosition) isChangingY false oldPosition Mathf.Round(player.transform.position.y 100) 100 else Debug.Log(oldPosition Mathf.Round(player.transform.position.y 100) 100) isChangingY true oldPosition Mathf.Round(player.transform.position.y 100) 100 if(Mathf.Round(transform.position.y 100) 100 enemyOldPosition) enemyIsChangingY false enemyOldPosition Mathf.Round(transform.position.y 100) 100 else Debug.Log(enemyOldPosition Mathf.Round(transform.position.y 100) 100) enemyIsChangingY true enemyOldPosition Mathf.Round(transform.position.y 100) 100 This script is placed my on enemy, and they both have rigidbodies
|
0 |
What is the difference between WaitForSecondsRealtime and a counter? I am making my own button using the Unity UI code, but now I got to the OnFinishSubmit () coroutine private IEnumerator OnFinishSubmit() float fadeTime base.colors.fadeDuration float elapsedTime 0f while (elapsedTime lt fadeTime) elapsedTime Time.unscaledDeltaTime yield return null this.DoStateTransition(base.currentSelectionState, false) yield break But I want to use a different code to delay time IEnumerator FinishSumbit() yield return new WaitForSecondsRealtime(colors.fadeDuration) DoStateTransition(currentSelectionState, false) Will this also work? Why didn't the Unity developers use WaitForSecondsRealtime?
|
0 |
Profiling unity games on Android devices I would like to profile our Unity mobile game on Android devices in a way similar to profiling Unity games on iOS with Instruments. I am aware of how to do this using Unity's profiler, I would however like to use a third party profiler for the following reasons to validate Unity's profiling data to have more visibility into how the app is running, including Unity's functions, etc. the largest lag spikes cause unity's profiler to run out of samples. I'm however very interested in precisely these spikes I'd like to have profile data for longer periods than unity records for I'd like to do analysis over time (not just detailed data for each frame, but also aggregated over a time span) Essentially I'd like as much visibility as possible to make Android on device profiling as comprehensive as possible. As close to Instruments on iOS as possible. So far I've tried with DDMS, but could only get visibility into Andoid OS functions and seeminly nothing in the actual apk at least nothing I recognised. I tried with mono2x and il2cpp, with all debug features that I'm aware of in build and player settings enabled. The game is developed with Unity 5,4 with Mono2x. All help is appreciated. I've listed my intents above, so even if profiling on device is not possible in this way on Andoid, alternate solutions to the listed intents are still very appreciated. Thanks!
|
0 |
Unity3d iOS build restarts when regaining focus from browser I have an app made in Unity3d for android and iOS. In it, the user has the ability to link their accounts with Facebook and Twitter. For Facebook I use their Unity plugin, for Twitter, I open an external browser page that lets them accept or decline Twitter integration that then redirects to a php page the calls the app URI to return focus to Unity. On Android this all works perfectly using an Intent in the Manifest. In IOS I'm running into issues though and I don't really know my way around XCode. I'm using the newest version, XCode 7 Beta 2. The App runs as expected but for both the Facebook and Twitter authentications, upon returning focus to the App from the Browser, it completely restarts the App as if just launched rather then returning from a suspended state. In the Unity build I have "Run in Background" selected. I setup the URL Scheme in XCode. Its a pretty basic app so I don't think its being closed due to Memory usage. Any ideas or any settings I can change in XCode that might be preventing it from resuming? Note, if I just hit Home and send the App to the background it will properly resume, its only when called by the URI from the browser that it seems to completely restart.
|
0 |
How to make camera smooth when following player When my character moves through my cameras 'FollowPlayer' script, the background just looks really glitchy and bad Is there anyway to fix this? This is my script using UnityEngine using System.Collections public class FollowPlayer MonoBehaviour Transform bar void Start() bar GameObject.Find("PlayerMovingBar").transform void Update() transform.position new Vector3( bar.position.x, transform.position.y, transform.position.z)
|
0 |
Load custom resources in Unity The situation is I work in my free time on one study project. I have resources of one game packed in it's own format. My intent was to use those with Unity without converting them into Unity's inner format. But with brief analysis of Unity Api Reference I did not find anything that would help my in my efforts. Like I have custom binary files I would need to parse with Unity and upon that data create geometry, lights and so on using Unity's classes. So I wonder if it's even possible? I would really appreciate if anyone would show make a hint on this subject
|
0 |
How to vary the initial velocity of a jump based on hold time? What I want to do is, the longer player holds the screen, the longer distance the object will jump when they release the hold. Here is my code private float timeBeginTap switch (touch.phase) Finger start touching the screen case TouchPhase.Began print("Start tapping") timeBeginTap Time.time break Finger leaving the screen case TouchPhase.Ended when finger release,the object jump float timeHolding Time.time timeBeginTap Debug.Log( "The player1 touched the screen for timeHolding seconds.") Vector2 jumpVelocity new Vector2(timeHolding, timeHolding) rb.velocity rb.velocity jumpVelocity break So with the code above I can get the value like 0.6324167, or 0.423567 for timeHolding, which is the amount of time that user hold the finger on screen. And I able to make the object jump by using this code below Vector2 jumpVelocity new Vector2(timeHolding,timeHolding) rb.velocity rb.velocity jumpVelocity But the distance traveled or "force" with which the object jumps is very small and it doesn't make sense. Therefore I make an attempt with the code below float right 5 float up 10 Vector2 jumpVelocity new Vector2(right timeHolding,up timeHolding) rb.velocity rb.velocity jumpVelocity With the code above, the distance is of course longer. But it feels constant and not dynamic, because the relationship between the Vector2's X and Y value is always constant. Therefore my question is, What is the correct way to define the values of X and Y for a Vector2 object based on the value of Time? If I missed anything, please guide me in the right direction. Desired Outcome For example,the velocity added to the box is to let the box jump from pole to another pole and stand on it. The velocity is define by using the time user hold on the screen,the longer the user hold on screen,the greater the velocity,means the x,y value of Vector2 is define by the timeHolding. Now when I hold the screen for the long time,the box will jump to the 3rd or 4th pole,and it not guarantee will reach the pole.Like everything is by chance. What I want is,the box will jump from 1st pole to 2nd pole,from 2nd to the 3rd and continuously.At the same time,the velocity to go higher or lower and the distance is depends on the time user hold the screen. This is what I want and my limited understanding of the problem.
|
0 |
Response to form triggers creation of zero or more duplicate scenes I've got two scenes, one with room 1 and one with room 2. In room 1 I've got one table with two 3D assets on top of it. This room also has a door that connects to room 2 through a door but it's closed. Once going near the 3D assets a dialog pops up saying to click "E". This pops up a 2D form one needs to fill. Only after filling both forms I'm able to go into room 2. Now what I would like to do is, depending on the response in the form, one or more duplicate room 2 scenes should be created and dynamically added to the scene. If with scenes isn't possible, what's the way to do such thing? Know about SceneManager.CreateScene but this creates an empty scene, not exactly what I want to.
|
0 |
Generate random position within object I have a plate object which is generated somehow (I don't care how), now I want to put another object within this object on random position. Lets say that I want to put random trees on this plate. How can I achieve this in Unity. I had read for bounds but I don't know how to use it to generate position for the tree.
|
0 |
Calculate required position to keep object centered when camera is rotated I always want to keep an object in the center of view of a camera. When the camera's rotation X value is 45, the object should still be centered. Therefore I need to calculate the new position of the camera. How could the "required camera position Y value" be calculated? Thank you.
|
0 |
Unity 2D collisions imprecise I am trying to make a platformer. For the player character I am using a kinematic rigidbody because I want to calculate the jump curve myself (including physics amp gravity). The platforms are also kinematic because I want them to move. I am having issues with the collision detection being imprecise causing the sprite to not stand exactly on the platform after jumping (as seen in the three images taken after three different jumps). This issue also causes the sprite to get stuck in the ground sometimes. The left image is the character inspector and the right is the platform inspector. The jump movements are done with movePosition, and I tried many things to fix this. I tried the following decreasing the timestep from 0.02 to 0.01, using onCollisionStay to keep it exactly on the platform, adding a physics material with zero friction, using edge colliders amp capsule colliders, using interpolate and extrapolate. https imgur.com a Kech2Qy
|
0 |
problem using OnStartServer() for unity multiplayer networked game UPDATE i am still scratching my head over this. The way i see it, the Awake() function is only invoked when I load it in the Editor, but if I put the prefab Loading line into OnStartServer() it just doesnt load anything, presumably because it hasnt managed to load the prefab yet ... i think it is something to do with when it switches Scenes from the offline to online in NetworkManager, i think this script and others are being dropped because the DontDestroyOnLoad command wasnt called due to Awake not being called. Hello everyone I am making a football game which you control one player from the team. It will connect 11v11 players per server (using a "Host" acting as server and client, and other clients connecting to them) I believe I have followed the examples and information provided by Unity to the letter, but I can't seem to get it working properly. The problem My code seems to work fine, provided I open the 'Host' instance from the Unity Editor, but if I make the full build version the Host it doesnt work. Strangely all my player objects will all spawn and act exactly as I intended, but the ball will not spawn unless the 'Host' instance is the one opened inside Unity Editor. I've made the Ball a Network Identity, NetworkTransform etc and Registered Prefab in the NetworkManager in inspector. Here's the code I am using to spawn the ball on the server, what could be the problem as I really have no ideas, thanks using UnityEngine using UnityEngine.Networking public class MatchdayManager NetworkBehaviour GameObject ballPrefab private void Awake() DontDestroyOnLoad(this) ballPrefab Resources.Load lt GameObject gt ("Prefabs Ball") public override void OnStartServer() Debug.Log("on server start called") GameObject go Instantiate(ballPrefab) NetworkServer.Spawn(go)
|
0 |
How can i check when rotation is ended? At the top of script public Quaternion lookRotation In Update void Update() transform.rotation Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime RotationSpeed) I want to know when the transform rotation ended and is at lookRotation Maybe using some flag ? This is my code using System.Collections using System.Collections.Generic using UnityEngine using UnityStandardAssets.Characters.FirstPerson public class FadeScript MonoBehaviour public UnityStandardAssets.ImageEffects.Blur blur public UnityStandardAssets.ImageEffects.BlurOptimized blurOptimized public FirstPersonController fpc public float fadeDuration 5 public float startAcceleration 0.6f public float endAcceleration 0.6f public float maxSpeed 1.0f public float rotationSpeed 0.6f private Material material private float targetAlpha 0 private float lerpParam private float startAlpha 1 private bool rotated false private Quaternion clampedTargetRotation void Start() material GetComponent lt Renderer gt ().material SetMaterialAlpha(1) fpc.enabled false void Update() lerpParam Time.deltaTime float alpha Mathf.Lerp(startAlpha, targetAlpha, lerpParam fadeDuration) SetMaterialAlpha(alpha) if (alpha 0) fpc.enabled true if (rotated false) fpc.GetComponent lt FirstPersonController gt ().enabled false rotationSpeed Mathf.Clamp(rotationSpeed startAcceleration Time.deltaTime, 0, maxSpeed) if (fpc.transform.localRotation Quaternion.Euler(0,0,0)) fpc.GetComponent lt FirstPersonController gt ().enabled true rotationSpeed Mathf.Clamp(rotationSpeed endAcceleration Time.deltaTime, 0, maxSpeed) blur.enabled false blurOptimized.enabled false rotated true clampedTargetRotation Quaternion.RotateTowards(fpc.transform.localRotation, Quaternion.Euler(0, 0, 0), rotationSpeed Time.deltaTime) fpc.transform.localRotation clampedTargetRotation public void FadeTo(float alpha, float duration) startAlpha material.color.a targetAlpha alpha fadeDuration duration lerpParam 0 private void SetMaterialAlpha(float alpha) Color color material.color color.a alpha material.color color What i want in the rotation part is to start the rotation slowly and then accelerate a bit and then in the end when it's getting "close enough" to 0,0,0 so start accelerate down until complete stop. Complete stop not must be at 0,0,0 but close to it. Th way i'm doing it now is wrong i'm not using the t 0 1 solution and not courtine. The rotation now in my script is almost working as i want. It start slowly and accelerate but in the end it stop at once without smoothly accelerate down.
|
0 |
Using XBox 360 controller in Unity game game doesn't recognize axis movement I have a problem with the usage of XBox controller in Unity game. I connected the controller to the PC and it works fine, I also managed to use it in the game itself I'm using "A" button to fire and Start to start the game and they work properly. However the game doesn't recognize the x axis movement. I'm not sure if the problem is in the input settings or my code. This is how the Horizontal movement is defined in the game This is the code that handles the movement float x Input.GetAxis("Horizontal") Vector3 newPosition new Vector3(transform.position.x x playerXMoveSpeed, 0, 0) newPosition.y transform.position.y newPosition.z 0 transform.position Vector3.Lerp(transform.position, newPosition, playerXMoveSpeed Time.deltaTime) var limit animator.SpriteRenderer.bounds.extents if (transform.position.x limit.x lt leftBorder) var capped transform.position capped.x leftBorder limit.x transform.position capped else if (transform.position.x limit.x gt rightBorder) var capped transform.position capped.x rightBorder limit.x transform.position capped OnMove(gameObject) All variables are more or less self explanatory, the OnMove is a delegate that just applies the transform to the gameObject in question. The entire code is inside a void method called Move(). That method is called inside an if statement if ((Input.GetAxis("Horizontal") ! 0.0f Input.GetButtonDown("Horizontal")) amp amp !IsContinueDisplayed) FollowTouch() Like I said, the game recognizes the other buttons, but not the x axis, it doesn't move the character. The Input.GetButtonDown is there just so keyboard input would be supported also (and it works properly). Can you see the problem with this code or settings? Please advise.
|
0 |
TopDown Island Generation I am trying to generate an island using Simplex Noise. To actually make a island shape i used Amitp's answers to the following questions 1.Fast, simple procedural 2d island generation 2.Generating random Pools or lakes Using them i have snippet of code for generation (width height is 128) for(int y 0 y lt HEIGHT y ) for(int x 0 x lt WIDTH x ) amitp's solution Vector2 vec new Vector2(2 x WIDTH 1, 2 y HEIGHT 2) float d Mathf.Sqrt(vec.x vec.x vec.y vec.y) float noise Noise.Generate((float)x WIDTH 10, (float)y HEIGHT 10) amitp's solution again mapData x, y noise gt 0.3 0.4 d d ? noise 10 0.0f colors x y WIDTH new Color(mapData x, y , mapData x, y , mapData x, y ) This gives me the following unwanted result How do i get fix it to generate properly? Lastly i'm using Unity. EDIT Fixed Changed a couple of things and now i am getting this(still not what i want) with this changed code for(int y 0 y lt HEIGHT y ) for(int x 0 x lt WIDTH x ) amitp's solution Vector2 vec new Vector2(((2 x) WIDTH) 1, ((2 y) HEIGHT) 1) float d Mathf.Sqrt((vec.x vec.x) (vec.y vec.y)) float noise Noise.Generate((float)x WIDTH, (float)y HEIGHT) amitp's solution again mapData x, y noise gt 0.3 0.4 d d ? noise 10 0.0f colors x y WIDTH new Color(mapData x, y , mapData x, y , mapData x, y )
|
0 |
convert clock input into 24 hour format I have stuck in a logical problem I have a third party package of DayNight. It takes hours input(24 hour format) to show dayNight effects in scene My code is to transform 12 hours clock cycle into 24 hours is if (todsky.Cycle.Hour gt 0 amp amp todsky.Cycle.Hour lt 11.97) Debug.LogError("1st") var degree 360 hourniddle.transform.eulerAngles.z var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes ConvertMinutesToHours(degreeToMintues) else if (todsky.Cycle.Hour gt 11.97 amp amp todsky.Cycle.Hour lt 23.97) Debug.LogError("2ndt") var degree 360 hourniddle.transform.eulerAngles.z as rotation is anti clock getting rever degree var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes var MintuestTo24HoursMintueCoverstion 720 degreeToMintues add 720 mintues into current minute in order to get 24 hour format ConvertMinutesToHours(MintuestTo24HoursMintueCoverstion) void ConvertMinutesToHours(float mintues) result TimeSpan.FromMinutes(mintues) Debug.LogWarning(result.Hours " " result.TotalHours " " result.Minutes " " result.TotalMinutes) todsky.Cycle.Hour (float) result.TotalHours Debug.LogWarning("setted hours " todsky.Cycle.Hour) But it is not working correctly . have made a clock GUI(360 degree) and as you know it only show 12 digits format not 24. I am getting clock needle movement which can be change through mouse drag. Needle z position up to 320 degree which means one degree is equal to 2 minutes and i am taking it as input from GUI. I write below code to integrate my clock needle with my DayNight package in order to integrate GUI with package and passing hour parameter into the package but it not working correctly. Problem is that else condition is skipping.
|
0 |
How can I implement Objective C libraries in Unity? I've been a "hardcore" developer for sometime now, as I've always worked with pure code reactive rendering, and contributed to Cocos2d library some time ago , (It is the one I used for my games) . But I've come to realize that most of the work I'm doing by setting up my game environment , user interface and everything else is becoming a bit repetitive, and complicated, as position must be tested each build , debugging sometimes involves exploring the deep down framework and I've decided to try out a full game development environment. Some friends have recommended me Unity for mobile development (If you could give me any better advice I'd be grateful) but my main concern is my custom libraries I built on Objective C for multiplayer real time connectivity, it's probably thousands of lines and I wouldn't like to write them all over again. Is there any way I could invoke my objective c library in Unity ? I know it's probably a vague question but can't seem to find where to start! Any guidance will be highly appreciated!
|
0 |
How to flick gameObject using Touch? I've been searching for a solution for my problem for a while on the web, but i didn't find anything that work properly What i want to do I have a bouncing ball and I want to let the user flick it with his finger (using a swipe gesture or whatever). The ball shouldn't start moving unless the player flick touch the ball. I don't want the ball to move if the player flicks anywhere on the screen, only if the flick touch the ball What i've done so far I've tried to write a script which would detect the touch starting position and the touch end position, and check if the end position is the same as the ball position to make sure that the flick touch the ball. Then the script calculate the direction vector by substrating the start position from the end position. After that i use the AddForce methode and give it the direction vector as a parameter. Here's my code, (it's better than 1000 words ) using UnityEngine using System.Collections public class Movement MonoBehaviour public Vector2 start public Vector2 end public Vector2 direction public Vector2 ballPos public float Flicktime void Start() void Update() ballPos new Vector2(transform.position.x,transform.position.y) if (Input.touchCount gt 0) Touch t Input.touches 0 if (t.phase TouchPhase.Began) start Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0)) if (t.phase TouchPhase.Ended t.phase TouchPhase.Canceled) end Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0)) direction end start if(t.position ballPos) rigidbody2D.velocity direction 2 What's the problem ? The problem is that the code doesn't work. When i launch the game in the Unity Remote 4 app in my android device and try to flick the ball it doesn't move, the inspector shows that the the scripte is calculating the start amp end positions and the direction vector, but the ball doesn't move, it stays in the same position even when the flick touch the ball. So what's the problem ? is there a better way to do it ? Since the ball have a circle collider how to make it detect collision with the player swipe ? Thank's and have a nice weekend !
|
0 |
How to implement the graph for pathfinding using A The game I am working on is based on a maze where each level is procedurally generated. The pathfinding grid is a 2D array where each node holds its connections. Path requests are handled one at a time so there can't be two path calculations going on simultaneously. So far I have each node hold its data required for the A (H,F,G scores and its parent) and manipulate them directly in the algorithm. Since the nodes are the actual nodes and not copies of them, every time the algorithm runs the data changes permanently and I have to manually set them on default values before the next run. So my questions are 1) Is this a valid way of handling pathfinding in a game? 2) What other data manipulation techniques I could use in order to avoid that? If you need a copy of the code it's all on my github under Pathfinding and Managers PathfindingManager.
|
0 |
How to implement efficient Fog of War? I've asked a question how to implement Fog Of War(FOW) with shaders. Well I've got this working. I use the vertex color to identify the alpha of a single vertex. I guess the most of you know what the FOW of Age of Empires was like, anyway I'll shortly explain it You have a map. Everything is unexplored(solid black 100 transparency) at the beginning. When your NPC's other game units explore the world (by moving around mostly) they unshadow the map. That means. Everything in a specific radius (viewrange) around a NPC is visible (0 transparency). Anything that is out of viewrange but already explored is visible but shadowed (50 transparency). So yeah, AoE had relatively huge maps. Requirements was something around 100mhz etc. So it should be relatively easy to implement something to solve this problem actually. Okay. I'm currently adding planes above my world and set the color per vertex. Why do I use many planes ? Unity has a vertex limit of 65.000 per mesh. According to the size of my tiles and the size of my map I need more than one plane. So I actually need a lot of planes. This is obviously pita for my FPS. Well so my question is, what are simple (in sense of performance) techniques to implement a FOW shader? Okay some simplified code what I'm doin so far Setup for (int x 0 x lt (Map.Dimension planeSize) x ) for (int z 0 z lt (Map.Dimension planeSize) z ) CreateMeshAt(x planeSize, 3, z planeSize) Explore (is called from NPCs when walking for example) for (int x ((int) from.x radius) x lt from.x radius x ) for (int z ((int) from.z radius) z lt from.z radius z ) if (from.Distance(x, 1, z) gt radius) continue transparency x tileSize, z tileSize 0.5f Update foreach(GameObject plane in planes) foreach(Vector3 vertex in vertices) Vector3 worldPos GetWorldPos(vertex) vertex.Color new Color(0,0,0, transparency worldPos.x tileSize, worldPos.z tileSize ) My shader just sets the transparency of the vertex now, which comes from the vertex color channel
|
0 |
Unity How to create C classes with different properties like Objects in javascript and put them in an array? I just started my gamedev journey on unity this week and while I have a background with coding, I'm still somewhat of a beginner. Last year I made a text UI based game on the web browser with javascript and have been trying to make the same game on Unity. One of the main features of my game is that you press a button to "go hunting" and I had an array filled with enemies that were objects with different properties such as health, mana, attack, etc... Then I'd randomly pick one of those objects from the array to be chosen as my enemy that I'd fight. I've been trying to figure out the best way to do this with C and I might just be overthinking this. As a bonus, I'd also like to be able to see the individual enemy objects in the array in my inspector if possible so I could tweak the stats within unity. I've looked at scriptableObjects and different things but I am having a hard time putting it all together in an array from within unity. System.Serializable public class playerClass public string playerName public int lvl public int maxHealth public int health public int maxEnergy public int energy public int exp public class playerScript MonoBehaviour public playerClass player This is how I created an object for the player, I want to do something similar for the enemies but put them in an array so I could randomly pick from them. If there is a better way to do this I'd also welcome some advice ) thank you
|
0 |
Unity Photon Networking Cant understand OnPhotonSerializeView In all tutorials I see that an object sends data over the network and receives the data. For sync in the same method Code void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) if (stream.isWriting) stream.SendNext (transform.position) stream.SendNext (transform.rotation) else Debug.Log("never gets called ") never gets called... transform.position (Vector3)stream.ReceiveNext () transform.rotation (Quaternion)stream.ReceiveNext () But when I test my code, the lower part, where the data gets received, is never executed! I never see the logs. But the object is SYNCHED because it is set in the inspector But the problem is that the object is not interpolated so it looks kind of funny. So, I need to know how can I make the upper method to work so I can do some interpolation stuff.
|
0 |
Everything is set to Bounciness 0 Why am I still bouncing? I am creating a platformer where rather than manipulating the character to get them from the beginning of the level to the end, you manipulate the world. Thus, when you want to make the character 'jump' over a gap, you actually use the land like a slingshot and 'fling' them. This is all working well and good save for one thing whenever I pull my land down and my player falls into it again, it begins to bounce aggressively so! I have made EVERYTHING out of a new physics material with 0 bounce, and I set my default physics to 0 bounce. My player is a rigidbody2D that is moving itself along on top of other rigid bodies. What gives? Why, even though EVERYTHING is set to 'no bouncing allowed' does my game turn into a bouncy house whenever i start to play? EDIT Here is a video of the behavior FlingyJump Bouncing Issues EDIT I have noticed a correlation to the bounce occurring and the spring being active. It have noticed that two things are happening 1) The spring is for some reason transferring force through to the ground piece while being stretched out. 2) The player is bouncing before even ever hitting the ground. I don't know quite how that is possible but it seems like as soon as it is enters the original position of the rigidbody2D for the ground piece it bounces.
|
0 |
Why does collision only work when keys are being pressed? My player object containing a rigidbody that is controlled using Input, is not colliding with an enemy unless keys are pressed. When no keys are pressed, the enemy simply goes through the player without collision. I'm using Unity 5.6.1f1. I figured the problem is in the Patrol class because when I don't attach the script to the enemy object the collision appears to take place fine. But I don't know what I'm doing wrong in this script because I seems to do it's task well. I wrote this script to make the enemy object move between points in patrolPoints which are just some empty's in the game world. So, I would like to know if I'm doing it right or is there another way to do it. Patrol.cs public class Patrol MonoBehaviour public Transform patrolPoints public float speed private int currentPoint private bool forward Use this for initialization void Start () transform.position patrolPoints 0 .position currentPoint 0 forward true Update is called once per frame void Update () if (transform.position patrolPoints currentPoint .position) if (currentPoint lt patrolPoints.Length 1 amp amp forward) currentPoint else currentPoint forward false if (currentPoint 0) forward true transform.position Vector3.MoveTowards (transform.position, patrolPoints currentPoint .position, speed Time.deltaTime)
|
0 |
Detecting collisions during animations I am creating a prototype enemy swordsman, and I'd like to be able to parry his attacks, like the parry system from VR Dungeon Knight. This is my method of implementation Parent a sword to his hand that has a child cube trigger collider kinematic rigidbody a custom script called ParryableWeapon. In the animation clip, when he raises his hand before his swing, use an AnimationEvent to tell the ParryableWeapon to start 'listening' for a parry. This is done by checking an internal boolean during OnTriggerEnter of the sword. If the ParryableWeapon collides with another ParryableWeapon while listening, the UnityEvent 'OnParried' is invoked. After the swing completes, use another AnimationEvent to tell ParryableWeapon to stop 'listening'. I have a simple model and animation from the Asset store that I'm using to accomplish this. For some reason, the OnParried event is only being fired every 5 or so swings at a stationary test sword. I played the animation frame by frame, and I found that the enemy swords' position sometimes does not go through the other sword, despite them being on a collision course. In one frame, the enemy sword is to the left of the other, and in the next frame, it is on the other side. It seems that the interpolated frames between the animation keyframes can only sometimes collide with the other sword. What would be the proper way to remedy this? Adding more keyframes to the animation? Some sort of calculation of the sword's path between the two keyframes?
|
0 |
Android black screen with Unity app in subview I've exported an Unity app game I have made to Android Studio. In Android Studio I made a layout and within it I have a framelayout. However, when I run the app the framelayout is completely black, why? Here is my Java code public class UnityPlayerActivity extends Activity protected UnityPlayer mUnityPlayer don't change the name of this variable referenced from native code FrameLayout fl forUnity Button bt groen, bt gul, bt sort Override protected void onCreate(Bundle savedInstanceState) requestWindowFeature(Window.FEATURE NO TITLE) super.onCreate(savedInstanceState) getWindow().setFormat(PixelFormat.RGBX 8888) mUnityPlayer new UnityPlayer(this) if (mUnityPlayer.getSettings().getBoolean("hide status bar", true)) setTheme(android.R.style.Theme NoTitleBar Fullscreen) getWindow().setFlags(WindowManager.LayoutParams.FLAG FULLSCREEN, WindowManager.LayoutParams.FLAG FULLSCREEN) setContentView(R.layout.main) this.fl forUnity (FrameLayout) findViewById(R.id.fl forUnity) this.fl forUnity.addView(mUnityPlayer.getView(), FrameLayout.LayoutParams.MATCH PARENT, FrameLayout.LayoutParams.MATCH PARENT) this.bt groen (Button) findViewById(R.id.bt groen) this.bt gul (Button) findViewById(R.id.bt gul) this.bt sort (Button) findViewById(R.id.bt sort) this.bt groen.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "G") ) this.bt gul.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "Y") ) this.bt sort.setOnClickListener(new View.OnClickListener() Override public void onClick(View v) UnityPlayer.UnitySendMessage("Main Camera", "ReceiveRotDir", "B") ) mUnityPlayer.requestFocus() Here is my XML lt ?xml version "1.0" encoding "utf 8"? gt lt RelativeLayout xmlns android "http schemas.android.com apk res android" android layout width "match parent" android layout height "match parent" android rowCount "3" android columnCount "10" gt lt FrameLayout android layout width "match parent" android layout height "400dip" android id " id fl forUnity" android background " 00FFFF" android layout centerHorizontal "true" gt lt FrameLayout gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Gr n" android id " id bt groen" android layout column "4" android layout row "2" android layout alignTop " id bt sort" android layout toRightOf " id bt sort" android layout toEndOf " id bt sort" android layout marginLeft "30dp" gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Gul" android id " id bt gul" android layout column "9" android layout row "2" android layout alignTop " id bt sort" android layout toLeftOf " id bt sort" android layout toStartOf " id bt sort" android layout marginRight "30dp" gt lt Button android layout width "wrap content" android layout height "wrap content" android text "Sort" android id " id bt sort" android layout below " id fl forUnity" android layout centerHorizontal "true" android layout margin "10dip" gt lt RelativeLayout gt
|
0 |
Movement appears to be frame rate dependent, despite use of Time.deltaTime I have the following code to calculate the translation required to move a game object in Unity, which is called in LateUpdate. From what I understand, my use of Time.deltaTime should make the final translation frame rate independent (please note CollisionDetection.Move() is just performing raycasts). public IMovementModel Move(IMovementModel model) this.model model targetSpeed (model.HorizontalInput model.VerticalInput) model.Speed model.CurrentSpeed accelerateSpeed(model.CurrentSpeed, targetSpeed, model.Accel) if (model.IsJumping) model.AmountToMove new Vector3(model.AmountToMove.x, model.AmountToMove.y) else if (CollisionDetection.OnGround) model.AmountToMove new Vector3(model.AmountToMove.x, 0) model.FlipAnim flipAnimation(targetSpeed) If we're ignoring gravity, then just use the vertical input. if it's 0, then we'll just float. gravity model.IgnoreGravity ? model.VerticalInput 40f model.AmountToMove new Vector3(model.CurrentSpeed, model.AmountToMove.y gravity Time.deltaTime) model.FinalTransform CollisionDetection.Move(model.AmountToMove Time.deltaTime, model.BoxCollider.gameObject, model.IgnorePlayerLayer) Prevent the entity from moving too fast on the y axis. model.FinalTransform new Vector3(model.FinalTransform.x, Mathf.Clamp(model.FinalTransform.y, 1.0f, 1.0f), model.FinalTransform.z) return model private float accelerateSpeed(float currSpeed, float target, float accel) if (currSpeed target) return currSpeed Must currSpeed be increased or decreased to get closer to target float dir Mathf.Sign(target currSpeed) currSpeed accel Time.deltaTime dir If currSpeed has now passed Target then return Target, otherwise return currSpeed return (dir Mathf.Sign(target currSpeed)) ? currSpeed target private void OnMovementCalculated(IMovementModel model) transform.Translate(model.FinalTransform) If I lock the game's framerate to 60FPS, my objects move as expected. However, if I unlock it (Application.targetFrameRate 1 ), some objects will move at a much slower rate then I would expect when achieving 200FPS on a 144hz monitor. This only seems to happen in a standalone build, and not within the Unity editor. GIF of object movement within the editor, unlocked FPS http gfycat.com SmugAnnualFugu GIF of object movement within the standalone build, unlocked FPS http gfycat.com OldAmpleJuliabutterfly
|
0 |
How to find the closest point on multiple colliders within a box? I need to find the position of the closest point from the bounds of multiple colliders. Right now I'm using OnTriggerStay and collider.ClosestPointOnBounds(). This works great for one collider, but as when I add a new collider, it doesn't update. I've drawn a quick picture to illustrate what I'm trying to say. The black box is the area I want to check in, the red boxes are the colliders with numbers representing the order they entered the black box. The green star is what the code currently says the closest point is, and the blue star is the expected result. The purple star is the position I'm checking for, the blue star should be the closest point to the purple star. I found this answer to a similar question on answers.unity3d.com. However, I feel like that could be very inefficient because there will be many, probably up to 50 of these box checking scripts running at the same time. I've also tried using Physics.BoxCast but that gave very wild results. The area it was checking was very different to what I wanted, and also what I was visualizing with gizmos. Also, the whole idea of boxcasts are very very confusing so I would rather something else. What is the best way to find the closest point on the bounds of multiple colliders within a certain area?
|
0 |
Having 3D material properties depend on shader Disclaimer I apologise if this is somehow a duplicate question or is unclear. I am in the process of writing a 3D scene renderer editor in C using the OpenGL specification. It is actually going surprisingly well considering my past experience (all but none) however I have hit hurdle in designing the way materials work. First, this is how they work now Materials have a diffuse albedo map, a normal bump map, and a specular map. They also have a diffuse albedo colour, and a shininess value for when no specular map is provided. This works fine and all however I noticed Unity's material's properties depend entirely on a shader. This is pretty much what I want as this is wonderfully flexible. I know you can get a list of a shader program's GLSL uniforms as described here but I am struggling with what my Material class should be looking like. Do I have each material hold a map of textures, colours, floats, with the keys being their GLSL uniform name? Or is there a nicer more elegant way? The reason I am against this is because I wouldn't know how to organise the properties in a GUI when all I am given is a uniform name. For example I might have multiple diffuse or specular maps, and I would like to arrange these in a specific manor. Please let me know if this is an awful question, or if I could improve it in any way. My brain hurts right now.
|
0 |
Multiplayer turn based Android iOS We're developing a mobile endless runner game, on Unity3d where you can challenge your Facebook friends. The only interaction between the players is the challenge one player challenges the other, then each player plays when he wants, and after both players finish (when their character dies), their scores are compared to determine the winner. What system would you recommend that would allow us to implement this functionality, considering scalability, cost and ease of use? Thanks in advance!
|
0 |
Mesh made in Blender is correct in Unity3D as a rendered mesh, but "empty" as a collider? I created a simple stair "block" in Blender, and it's rendered correctly, but when I tick "Generate Colliders" and try to use it in a Mesh Collider, there is nothing. (Ps. I need the real mesh as a collider, not just that generated convex one) Maybe a good clue is that my other objects' generated colliders are smaller than the rendered meshes themselves. Maybe this one is scaled to zero? After triangulating And via Unity's automatic triangulation (the original, non triangulated blender model)
|
0 |
Unity3D GameObject as a static function Newbie Unity3D C developer here. I've tried learning Unity3D during my May June college vacation and came across a problem Code 1 CameraObj returnVoid void Start () returnVoid GameObject.Find ("Main Camera").GetComponent lt CameraObj gt () returnVoid.ComponentType () Code 2 GameObject returnDirectLight void Start () returnDirectLight GameObject.Find ("Directional Light") Debug.Log (returnDirectLight.GetComponent lt DRLight gt ().directionString) CameraObj is my custom component. As far as I know, GetComponent is actually a public method. I understand the logic behind Code 2. What I fail to understand is Code 1. How does GetComponent become a static function here? Does it become abstract in my CameraObj class?
|
0 |
Unity Avoid boucing when ground move down I have a sphere amp a quad, when the quad move down, the sphere fall after and bounce back continuously. I dont want to change my project setting like bounciness, gravity,mass and I need the sphere to move freely to jump between quad. How can I do this, thanks
|
0 |
Creating the Vertices and Triangle Indices for Voxel Generated Mesh I am running into a problem with a compute shader I am writing to generate the vertices and triangle indices for a voxel generated mesh. Currently, I am creating an AppendStructuredBuffer of triangle structs which just have the three vertices of a triangle and reading from the AppendStructuredBuffer to the CPU. When read to the CPU, I then read from the buffer and set it in a RWStructuredBuffer in the GPU. Following that, I run a compute shader kernel to parse the triangle buffer. Obviously if I can do this all on the GPU I should since reading and writing between the CPU and GPU is expensive. When trying to put it all in one kernel I run into problems however. Each voxel has a range of possible triangles (0 5) that can form in it. Because of that, I can't simply use the dispatch ID to put it in a RWStructuredBuffer (at least I don't think so). That's why using an AppendStructuredBuffer seems natural it allows for the variable amount of triangles. After getting the array of triangle vertices and array of triangle vertex indices, I bring them back to the CPU and set them to a mesh and render it. In the future I want to use a geometry shader to render the mesh since that is most likely more efficient, but I'm trying to take this one step at a time, and geometry shaders are a whole 'nother beast I know nothing about.
|
0 |
Unity or Monogame or Gamemaker 2 for an experienced application developer? So i know this question has been hammered down several times but please bear with me. I used to be a C .Net application developer but i am no longer employed, i am pretty good at C . I want to get into serious game development and i dunno where to start, i used to work with unity occasionally which is a very little and i kinda find it clunky, like it works but somehow it does not feel right and feels kinda clunky. But it works with tiled map editor without much of a hassle. I Remember using Game maker studio when i was back in college and i found it very good, its a breeze to work with and even have its own tiled map editor, even seems to have some good tutorials, the only con is its price. I was initially inclined towards Monogame cause of my C background, but i neither have time nor money and resources to support me for long enough time to be able to code every single thing from scratch and i am kinda in a pretty bad situation overall right now. It just takes too much time to do anything even to make it work with a tiled map editor, and there are very few tutorials or documentation to start with. It seems like the only option for me is Unity at the moment, cause of ease of access and how easy it is to work with tiled map editor and lots of tutorials. which one do you guys think is good overall? Please keep in mind that i am currently unemployed and have very little resources to support myself, and i am a programmer so i don't even know how to compose music and do art for the game and i'd prefer if it provides some asserts to be used so i wont waste time in learning stuff when i cannot afford to spend time. I will eventually learn them but not now, its not happening now so i prefer something that comes with some sorta free asserts that can be used (mainly music and art), I mean does it even matter if all i am trying to do is earn a decent minimum living? I just want to make simple 2D NES Snes style games with multiplayer support. Thank you.
|
0 |
Why the state of the duration is all the time 7 even if updating the state inside the while in the ienumerator? I want to get the current coroutine state. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.PostProcessing public class DepthOfField MonoBehaviour public UnityEngine.GameObject player public PostProcessingProfile postProcessingProfile public bool dephOfFieldFinished false public LockSystem playerLockMode private Animator playerAnimator private float clipLength private Coroutine depthOfFieldRoutineRef private DepthOfFieldModel.Settings depthOfField private DepthField state void Start() if (depthOfFieldRoutineRef ! null) StopCoroutine(depthOfFieldRoutineRef) playerAnimator player.GetComponent lt Animator gt () AnimationClip clips playerAnimator.runtimeAnimatorController.animationClips foreach (AnimationClip clip in clips) clipLength clip.length DepthOfFieldInit(clipLength) state new DepthField() public void DepthOfFieldInit(float duration) depthOfField postProcessingProfile.depthOfField.settings depthOfField.focalLength 300 StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, duration)) postProcessingProfile.depthOfField.settings depthOfField public IEnumerator changeValueOverTime(float fromVal, float toVal, float duration) playerLockMode.PlayerLockState(true, true) float counter 0f while (counter lt duration) var dof postProcessingProfile.depthOfField.settings counter Time.deltaTime float val Mathf.Lerp(fromVal, toVal, counter duration) dof.focalLength val postProcessingProfile.depthOfField.settings dof state.duration duration state.focalLength val yield return null playerAnimator.enabled false dephOfFieldFinished true depthOfFieldRoutineRef null public struct DepthField public float focalLength public float duration public void Save() SaveGame.Save("depthoffieldstate", state) public void Load() Time.timeScale 1f depthOfField postProcessingProfile.depthOfField.settings DepthField state SaveGame.Load lt DepthField gt ("depthoffieldstate") depthOfField.focalLength state.focalLength StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, state.duration)) postProcessingProfile.depthOfField.settings depthOfField Inside the while loop I'm doing state.duration duration state.focalLength val The focalLength value does change if for example I save onethe game start the focalLength value will be 299 and if I will save after the coroutine has finished the focalLength value is 1. But the coroutine duration value is not changing it keep staying on 7 when saving even if the coroutine has finished and should be 0 it still 7. The value 7 of the duration is coming from the clipLength. I can't get the current duration time of the coroutine. In the Load function I'm starting the coroutine over again but since I'm using the loaded focalLength value and duration value it should look like the coroutine is continue from the last saved point. But I can't get the correct duration value when saving.
|
0 |
UGUI scripts stop my project from building Unity 2019.2.21 I am trying to build out my project to Android and I am getting the following error messages H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Toggle.cs(121,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core DefaultControls.cs(152,13) error CS0103 The name 'Undo' does not exist in the current context H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core GraphicRebuildTracker.cs(24,32) error CS0117 'CanvasRenderer' does not contain a definition for 'onRequestRebuild' H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime EventSystem InputModules StandaloneInputModule.cs(159,25) error CS0234 The type or namespace name 'EditorApplication' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Slider.cs(380,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Scrollbar.cs(168,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Selectable.cs(771,48) error CS0234 The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core InputField.cs(2458,43) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) I tried updating Unity(from 2019.2.12 to current). Deleting some csproj files, and different settings in the Project settings Player. The problematic code is in an if UNITY EDITOR statement, and not meant to execute at all on builds, I guess. if UNITY EDITOR protected override void OnValidate() base.OnValidate() if (!UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this) amp amp !Application.isPlaying) CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this) endif if UNITY EDITOR
|
0 |
What is the optimal way to store customisation options? I am trying to understand the most optimal way of storing customisation options within a game, or to be precise, to store all the possible customisation options for multiple different objects. For example, assuming we are making a game about tanks and their customisation, there will be several available tanks that the player can choose from and each of the tanks will have multiple different parts available some parts will be shared across a few tanks, while some will be specific to a tank. I was thinking about a relational database, but I do not know web development, so I was initially thinking to have a table with all the tanks and a table with all the parts, then create a linking table between the two and load the available parts based on the chosen tank but I'm not sure if that would work, or if it would be the most optimal way of doing this. I tried looking for an answer, but I'm not getting any good results. People mention using files, and then parsing the data, but I'm not sure how that will work on a large scale multiple tanks with hundreds of customisation options. What is the most optimal way to to do this? If at all relevant, I am using Unity 5.
|
0 |
Press multiple switches to unlock the door I made 2 scripts, one that is a switcher and one that checks if object is switched (Switch, SwitchCheck). Switch script (it's on 2 objects that are switches and both objects have colliders with IsTrigger checked) public var IsPressed boolean false function OnTriggerStay () if (Input.GetKeyDown(KeyCode.JoystickButton1)) IsPressed true Debug.Log("Switch activated") SwitchCheck script (it's on door that should be opened) public var Switch1 Switch public var Switch2 Switch function Update() if (Switch1.IsPressed amp amp Switch2.IsPressed) Destroy (gameObject) Now, he problem here is, that it "does" kind of work...after I press the button like 20 times. My question is, did I write something wrong?
|
0 |
How to set rotations to 0,0,0 in 3ds max for exporting in unity? I'm a modeler in 3ds max and the unity programmer ask me that the object must have pivot with Y up rotations at 0,0,0 but every object that I export in fbx he says don't have rotations at 0,0,0. I tryed different solutions as reset xform freeze rotation rotation to zero .rotation eulerangles 0 0 0 but in unity he have values like this 4.577637e 05, 1.525879e 05, 0 or 90, 1.525879e 05, 0 and so on It's a problem that can I fix in max or the programmer has to fix it in unity? Thanks
|
0 |
Unity trigger method does nothing I have the following script on my object public class PlayMyCube MonoBehaviour SerializeField private Animator myAnimationController private void onTriggerEnter(Collider other) if (other.CompareTag("Player")) myAnimationController.SetBool("playSpin2", true) private void OnTriggerExit(Collider other) if (other.CompareTag("Player")) myAnimationController.SetBool("playSpin2", false) When the player character is inside the first cube's trigger, my second cube should play a spinning animation. When they leave, the second cube should stop. But what happens in the game now is, when the character runs into the trigger, it does nothing. I have configured my trigger object like this I have configured the object that should spin like this And configured the Animation Controller like this And configured my Player object like this What can I do to make this animation play when the player is inside the trigger?
|
0 |
How to set player rotation to direction the player is moving? I'm having an issue with my click to move mechanic. I want the player to move to a specific position in the game when the mouse is clicked (and it does just that) but the issue I'm having is that the player doesn't face the direction in which it is travelling. Lets say I click a position diagonally right to where the player is. Immediately after clicking that point, the character will face that direction and run to it, instead of facing the direction it has to take to get there... if that makes sense. Here's my code snippet public void moveToTargetPosition() Seeker seeker GetComponent lt Seeker gt () seeker.StartPath (transform.position, targetPlayerPosition, OnPathComplete) transform.rotation Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(targetPlayerPosition transform.position), Time.fixedDeltaTime lookSpeed) Obviously I'm missing some modifier in here. Any ideas? Thanks!
|
0 |
Unity Facebook "An access token is required to request this resource." I have installed Facebook SDK 7.6 for Unity 5.3. It is fine with login and logout stuff things but I am having a problem when it comes to use FB.API. I want to be able to fetch players' profile pictures and names for my multiplayer game project. Each client has other's facebook profile id but I cannot use those IDs on Graph API I guess. What is the way of getting such public information using Facebook SDK. FB.API(" " facebookID "?fields name", HttpMethod.GET, OnNameReceived)
|
0 |
When is transform width in code not equal to the transform width in inspector? I've come across a strange case in Unity's UI where the width of a RectTransform isn't the same as what is being reported. I have a transform which is 50 by 50 with no scaling, it is a root object of the canvas yet when I use the information that I get from the transform in code to draw from the bottom left edge of the transform to the top right it doesn't reach all the way! Gizmos.color Color.red Vector2 pos new Vector2(transform.position.x, transform.position.y) Gizmos.DrawLine(pos transform.sizeDelta, pos transform.sizeDelta) Vector3 corners new Vector3 4 transform.GetWorldCorners(corners) Gizmos.color Color.magenta Gizmos.DrawLine(corners 3 , corners 0 ) Gizmos.DrawLine(corners 0 , corners 1 ) Gizmos.DrawLine(corners 1 , corners 2 ) Gizmos.DrawLine(corners 2 , corners 3 ) The first section should draw a line from the bottom left to the top right according to what the transform reports are the width and height however they don't reach across the entire transform. Using GetWorldCorners the actual corners can be found and drawn around, with that data you can extract that the actual width is 60 (150.2 30.2 120 2 60)! Why? Is this a bug or an I missing something obvious here?
|
0 |
2D Rivers Lakes in infinite terrain I've been looking into generating lakes and rivers for a 2D infinite tilemap but I'm stuck with how to handle them for an infinite map. I can use noise heightmaps for determining the lakes and the starting points for rivers but for an infinite map I can't use the "flow downhill" or "carve out" technique because the player could come across the river at any point. If I have a river that's a max of 200 tiles long, I'd have to calculate noise map values for 33x33 chunks (my chunks are 6x6 tiles) around the player which feels excessive and very inefficient. I have not found a way to make noise alone work for this, rivers would always be too circular if I find a range narrow enough and they'd encircle lakes, not extend outward. Calculating voronoi cells and putting rivers at certain edges, with some extra noise to make the paths more natural, might work. I just can't seem to find any good examples where they aren't working with known dimension maps.
|
0 |
Unity3d deploy game to android device off site I am using Unity3d to develop my game and my friend with android device wanted to test it. I am natively IOS developer and have no knowledge of deploying Android platform. What do I need other than Unity3d? The scenario here is that I have to send to my friend who is not developer to install and test on his device via internet. We used to have TestFlight App but that is history now.
|
0 |
Restrict render in Blender is not working I click "Restrict renderability", so that everything except the item I want to export is grayed out. However, it still exports lights and everything when I import it into Unity. How can I fix this?
|
0 |
Understanding Send Message I'm trying to understand the Send Message Function but I'm a bit confused. Currently I have a game object character and I want it to send a message to the main body if one of its children hits something. On the Child object, I have void OnTriggerEnter2D(Collider2D col) Destroy(col.gameObject) Debug.Log(this.name " Hit!") gameObject.SendMessage("PlayerHitting", this.name) On the Parent Object, I have public void PlayerHitting(string Move) Debug.Log("Player hits with " Move) The Destroy code and Debug.Log on the Child work, so it is colliding, but I keep getting an error that there is no reciever. SendMessage PlayerHitting has no receiver! UnityEngine.GameObject SendMessage(String, Object, SendMessageOptions) I don't quite understand how to use Send Message to send messages and notices between objects. Can someone explain?
|
0 |
Start Broadcast Unity Network Discovery I am using the unity NetworkDiscovery component, and I am wondering how I can auto start broadcasting when the server starts, instead of the client having to click on the gui Initialize Broadcast Start Broadcasting. I would like to be able to put some C in my start host function so that the user does not have to do anything.
|
0 |
Difference between DEBUG and DEVELOPMENT BUILD in Unity? I've seen these two special compilation macros in our code base, What's the difference between Debug and DEVELOPEMENT BUILD in Unity? What's the main purpose of using each? if DEBUG Debug.Log("DEBUG") endif if DEVELOPMENT BUILD Debug.Log("DEVELOPMENT BUILD") endif
|
0 |
2 Color Fonts in Unity? (so maybe called 3 Color including transparent alpha?) I have been trying to make my game title screen look better. I realised it was because all my fonts have just one colour. I read some very old threads about a Editor Scripts to extract the font to png format. I then see there is now a way to do it in the 'hamburger' menu of the Font in Inspector. I had to change my font to be not 'Dynamic' then it allowed me to extract a copy to PNG. I opened this in GIMP and added my white inside the outlines of each character (it had been alpha before this, giving a horrible see thru effect on the letters). I put this back into Unity (the new PNG) and used it as the source texture for my Text Shader. However it is still not handling both colours. (Screenshot below). So what can I do using Unity 2020 to achieve better looking text? I've read this (https docs.unity3d.com Packages com.unity.ugui 1.0 manual StyledText.html) and many other pages on Unity site but I am now going around in circles not achieving anything. Thanks for any help. EDIT Since DMGregorys comment. I am posting picture of my import settings on the modified (coloured in) font PNG file EDIT 2 The 3rd screenshot shows the 'Text' objects settings. Note I have changed Material to be my extracted one. 4th screenshot shows that Material's settings enter image description here
|
0 |
unity webgl scale page on different sizes of internet browsers on pc or phone unity only has a fixed resolution for building webgl. how can I make it changebale on users browser size change. there are some tutorials on the internet that doesn't match. there is only index.html unityloader.js gamename.json gamename.data.unityweb gamename.asm.memory.unityweb gamename.framework.unityweb gamename.asm.code.unityweb how can I make multi res webgl output happen for unity?
|
0 |
Animator from another gameobject keeps disappearing from script on play I am working on a gun script and it worked fine until earlier today when I made a change to the script and it stopped working. I put it back, but for some reason now the animator object attached to the script keeps disappearing. using System.Collections using System.Collections.Generic using UnityEngine public class RifleShooting MonoBehaviour private float NextTimeToFire 0f private int CurrentAmmo private bool IsReloading false Space(10) Header("Floats") public float Damage 10.0f public float Range 100.0f public float ImpactForce 60f public float FireRate 15f public float ReloadTime 1.0f Space(10) Header("Others") Space(5) Space(10) Header("Others") Space(5) public int MaxAmmo 10 public Camera FPSCamera public Animator GunAnimations public ParticleSystem MuzzleFlash public GameObject impactEffect public bool AllowedToShoot true Start is called before the first frame update void Start() GunAnimations GetComponent lt Animator gt () if (CurrentAmmo 1) CurrentAmmo MaxAmmo private void OnEnable() IsReloading false GunAnimations.SetBool("Reloading", false) Update is called once per frame void Update() if (IsReloading) return if (CurrentAmmo lt 0) StartCoroutine(Reload()) return if (AllowedToShoot false) return if (Input.GetButton("Fire1") Input.GetButtonDown("Fire1") amp amp Time.time gt NextTimeToFire) NextTimeToFire Time.time 1f FireRate Shoot() IEnumerator Reload() IsReloading true Debug.Log("Reloading...") GunAnimations.SetBool("Reloading", true) GunAnimations.SetBool("IsShooting", false) yield return new WaitForSeconds(ReloadTime .25f) GunAnimations.SetBool("Reloading", false) yield return new WaitForSeconds(.25f) GunAnimations.SetBool("IsShooting", true) CurrentAmmo MaxAmmo IsReloading false void Shoot() shooting script here Also if it helps here is what I see in the console when I try to fire MissingComponentException There is no 'Animator' attached to the "M4A1" game object, but a script is trying to access it.
|
0 |
Add Boo or Python to Unity 5 I'm new to Unity, but I'm more comfortable with Python. Is there any way to use Python as scripting language in Unity 5? I heard there is some language called Boo that has a syntax like Python but it seems Unity just supports C and Javascript. How can I add Boo or Python scripting to Unity 5?
|
0 |
How can I make sure that a component gets destroyed the last out of all components attached to an object in Unity? How can I make sure that a component gets destroyed the last out of all components attached to an object in Unity? I have a component with some scripts on it Script1 and Script2. Inside the Script2.OnDestroy method I have the following line of code GetComponentInParent lt Script1 gt (). I want that line of code to return Script1 whenever I click the Play button inside Unity editor to stop my game. While right now it returns null.
|
0 |
Game shifts to edge of screen when clicking Play button in Unity I m attempting to help my young daughter who is trying to learn Unity. I know very little about the program. Recently, she developed a basic game consisting of a dragon and a person. When she presses the play button, the game shifts to the edge of the screen and does not start. I have attempted to research the issue but with my limited knowledge on the subject I could not find anything. Any help or suggestions would be appreciated! 09 22 After reading the comment and following the recommendations I do believe it s a camera issue. I ve attempted to move the camera around using the X, Y and Z axis is but I can t get it to actually change the view. See the attached screenshot. 10 02 2020 My daughter went back and redid the game from the start. The issue is that the game will not allow her to enter play mode until she places the dragon. However, as soon as she places the dragon and presses play the game moves the camera. So the issue apparently occurs prior to or at the time she places the dragon but because she can't enter play mode prior to this point I'm not sure where the issue occurs.
|
0 |
Dynamically applied texture to GameObject using GUI button In a scene I have multiple different GameObjects (almost 30 kinds) with parent child relationships. At run time (by using a GUI button) I want to change the texture of each clicked GameObject. As the user clicks specific GameObjects, a GUI with a multiple texture button will appear. By clicking on the button, that specific texture will be applied. Is there a smarter way to do this? Do I need to apply a script to every object? I have tried to apply a script with some specific code it's working but not regularly and correctly. Additionally, I want different texture options for each kind of GameObject.
|
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 |
How are methods like Awake, Start, and Update called in Unity? I'm developing with Unity 5 and I know that there are some methods you can use like in the code below public class MyGameElement MonoBehaviour private void Awake() private void Start() private void Update() private void FixedUpdate() and more I know what they do but I find it strange that the methods can be private. However they are not called into my code I've written. Here you've an image with code lens (I use VS 2015 Professional for coding) where you can really see that it has zero references. The second 'strange' thing for me is that the methods aren't overwritten. So my question is now is there anything that Unity has implemented into the MonoBehaviour class that the methods can call?
|
0 |
Can I pause Unity Setup download and continue it whenever possible as per convenience(using Unity Hub)? Actually I get only 1.5GB data daily. So it's not possible for me to download the whole Unity setup in a day. So I wanted to know if I can pause and resume download process as per convenience. I am downloading using Unity Hub.
|
0 |
Particle Effects Start Glitching out My particle effects have gone crazy look In my game, bombs drop on castle and then explode For the first few second of my game the particle effects for the explosion works. The particle effects are made using the unity particle systems As you can see below, the particle effects in the scene view are also in the game view However after a few second the particle effects start to glitch out and while they appear in the scene view, they do not appear in the game view Above there is a massive explosion in the scene view but nothing in the game view. I can make the particle effects work by doing a few weird things If I remove the walls on my castle the particles will suddenly work. The walls just contain a sprite renderer component, no script or anything. If I make a looping particle effect when the effect is visible on the game screen the particle effects start working but when I drag it off the screen even though its still working(I see it in the scene view) because its not in the game screen my explosion particle effects instantly stop working. I am super confused about why this is happening.
|
0 |
Player jittering against wall when held down button So, I'm making a top down RPG. Everything's going excellent, but this problem is quite annoying. Now, when the character moves against the wall, the player jitters back and forth. I'm guessing it's because the player is trying to move into the wall, and then the wall collision is pushing it back, which makes an annoying back and forth movement. My question is obviously, how do I stop this from happening? Thanks! PS I'm using transform.translate to move the player, and I'm using C . EDIT I'm also using a 2D Rigidbody, and 2Dbox colliders on both.
|
0 |
Issue with interpolation on a burn shader (lerp and smoothstep) I'm trying to create a simple burn shader. See here for more info on the method I'm using. However, I don't get why replacing the smoothstep with a lerp results in completely different results. Am I missing something from my knowledge of maths? As far as I know they should return similar values given the same parameters. clips materials, using an image as guidance. use clouds or random noise as the slice guide for best results. Shader "Custom Dissolving" Properties MainTex ("Texture (RGB)", 2D) "white" BorderTex ("Border Texture (RGBA)", 2D) "white" EdgeColor ("Edge Color", Color) (1,0,0) EdgeSize ("Edge Size", float) 0.1 SliceGuide ("Slice Guide (RGB)", 2D) "white" SliceAmount ("Slice Amount", Range(0.0, 1)) 0.2 MaterialToggle UseClipInstruction ("Use Clip Instruction", Float) 0 SubShader Tags "Queue" "Transparent" "IgnoreProjector" "True" "RenderType" "Transparent" Cull Off Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM if you're not planning on using shadows, remove "addshadow" for better performance pragma surface surf Lambert alpha addshadow struct Input float2 uv MainTex TEXCOORD0 float2 uv SliceGuide TEXCOORD1 float SliceAmount sampler2D MainTex sampler2D BorderTex sampler2D SliceGuide half SliceAmount half EdgeSize half3 EdgeColor void surf (Input IN, inout SurfaceOutput o) o.Alpha 1 Green is a good color for estimating grayscale values half fragSliceValue tex2D( SliceGuide, IN.uv SliceGuide).g ifdef UseClipInstruction clip(fragSliceValue SliceAmount) else TODO look for an alternative to this if (fragSliceValue SliceAmount lt 0) o.Alpha 0 endif half rampX smoothstep( SliceAmount, SliceAmount EdgeSize, fragSliceValue) half3 ramp tex2D( BorderTex,half2( rampX,0) ) EdgeColor.rgb o.Emission ramp (1 rampX) o.Albedo tex2D( MainTex,IN.uv MainTex) ENDCG Fallback "Diffuse" Left is the result of smoothstep (the provided code), right is what happens when I replace smooth with lerp.
|
0 |
Move around the object using head tracking movement in Unity I am developing an app for Samsung Gear VR with unity.I have added a cube and made the cube move forward on the terrain. Now I need to move around the cube using head tracking movement.I have referred the below link(Flyer VR movement) .But I am not able to understand the code used in it. https unity3d.com learn tutorials topics virtual reality movement vr Can anybody help me doing this in a simple way to move around the cube by head tracking
|
0 |
World coordinates on vertical grid game for different aspect ratios (Unity) new to game development and unity so hopefully someone can help. I want to make a 2D portrait mobile game that will have a grid of constant size where units can move on in Unity. This should support different aspect ratios. To do that I was thinking to cut sections at the top and bottom of the screen for smaller aspect ratios. Additionally, I would like the coordinate system to be natural to the grid, so coordinate (0,0) would be the bottom left tile in the grid, (1,0) would be the tile to the right of that,... To illustrate this concept I drew something quickly I tried with a script that resizes the size of the orthographic camera to fit the content horizontally. Problem I had with that is that I couldn't get a good coordinate system on the grid after the camera gets resized depending on the aspect ratio since the number of horizontal world units varies depending on the aspect ratio. Any thoughts on what would be the best way to do this? Thanks!
|
0 |
Detecting collisions with a wall before Update I'm making a script in unity to control (movement) a character in 3rd person and 3D space. For that I'm using the CharacterController component. All pretty standard inside the update method a Vector3 which will be passed to CharacterController.move is crafted based on the input and collisions, movement and jumping are perfectly fine but I ran into an issue when trying to make a wall jump. There are 3 steps involved in this Get the wall to jump of. Check if the player pres the jump button. Move the player in the desired direction. An this is how I'm doing it void OnControllerColliderHit(ControllerColliderHit hit) if(mController.collisionFlags CollisionFlags.Sides) Get wall normal wallNormal hit.normal isOnAWall true Now inside Update if(Input.GetButtonDown("Jump") amp isOnAWall) jump... And this work fine in most cases but only if player is giving input or last wall has a similar normal as current so obviously the normal isn't refreshing properly, but why? Well, after some testing, I discovered that the OnControllerColliderHitis called after the Update method, and this is what I think is happening Physics engine detect the collision and stops the player Update method not having any input just send it downwards The OnControllerColliderHit method is not triggered(this part I am sure) Are my conclusions correct? How can I fix this? (make the player jump without need to move the stick and just with the button)
|
0 |
How do I prevent inappropriate ads from appearing in my game? My game implements Unity ads, and is designed with a universal audience in mind. As such, I would prefer not to have 18 ads (or even 13 ads depending on the circumstances) appearing in it, especially since it would appeal to younger audiences as well. My question is then, how do I prevent age inappropriate ads from appearing? Is there a way to simply set the age limit or content restrictions on Unity ads? The only setting along those lines that I can find is the COPPA toggle, and that would cause other issues (not to mention that it wouldn't do anything to the ads). I've looked in the dashboard for a while, and I've tried to research it beforehand, but the fact that they've shifted to a centralized services page, redirected all the old links (breaking them in the process), reorganized the settings in the dashboard, and 404d their FAQ post on the topic doesn't help either. Blocking ads based on a rating would work too, as I would have to get one because I am publishing to Google Play. Edit The second link only 404s some of the time. I just happened to get it every time before asking this question. Bad luck, I guess.
|
0 |
How to save variables into a file unity I've wanted to save progress of my game (i don't have the code , sorry) without using PlayerPrefs. If it's possible with UnityEngine.
|
0 |
Unity Unable to blend 2D Light renderers I've followed the documentation on Unity regarding 2D lighting. It said to turn on Alpha blending in the options. But this is how it turns out If Alpha blending is off If Alpha blending is on I'm not entirely sure why it's turning black. These are my settings for the 2D light I've checked my layers, specifically the tile map floor, and it's on the Default layer. I just want my lights to blend well.
|
0 |
Prediction of collision place and time in Unity I have two moving objects. I have chosen trajectories for objects that they would definitely collide if they don't change speed or trajectory. Is there easy way to check at which point and time the objects will collide with given parameters (current object positions, their velocity vectors and speeds or any other parameter accessible from Unity)?
|
0 |
How to delay a timer when it's run the first time in update method not using a coroutine In the code below I am resetting a timer after a duration maxiTime within the update method. I want to delay the timer before it begins to run for a certain duration. I believe this could be done with a coroutine, but I am using StopAllCoroutines, so I need to do this within the update method. How can I get the delay only before the first run? timeElapsed 1 if(timeElapsed gt maxiTime) timeElapsed 0 Debug.Log ("Thank You!")
|
0 |
Unity C Changing Button Color? void OnMouseDown () foreach (Button thisButton in buttonArray) thisButton.GetComponent lt SpriteRenderer gt ().color Color.black GetComponent lt SpriteRenderer gt ().color Color.white This code results in whichever button I select changing color to white while the rest are black. However, I am not understanding how this works. How does it know to specifically change ONLY the selected button to white while the rest are black. Seems contradictory to me...
|
0 |
Making a Point Light follow a cube (Unity) I'm trying to have a point light positioned directly above a cube follow wherever the cube goes. However, it doesn't move at all. This is my code for the light using UnityEngine using System.Collections public class SpotlightController MonoBehaviour Use this for initialization void Start() void OnGUI() GUI.Label(new Rect(20,50,500,20), "(" transform.position.x.ToString() ", " transform.position.y.ToString() ", " transform.position.z ")") Update is called once per frame void Update() GameObject cube GameObject.Find("Cube") float xlocation cube.transform.position.x float zlocation cube.transform.position.z transform.TransformPoint(new Vector3(xlocation,transform.position.y, zlocation) Time.smoothDeltaTime) transform.Translate(new Vector3(xlocation, 0, zlocation))
|
0 |
How to create button prompts for interactable objects in Unity? I have a class of objects tagged as interactables that my player can interact with when within range. When my player is near them, I want to display a button prompt at the bottom of the screen, along with a description of the type of interaction possible (for example, "inspect", "use", etc.). I want to account for the possibility that the player might be within range of two or more of them at once, and thus allow him to toggle through them, displaying their button prompts in turn. If my player interacts with something which generates a text box or other modal, I want the button prompt to disappear, but to return when the text box or modal is closed. Any advice on how to go about achieving this? I've done it in the past in different engines, but I have always been unhappy with how convoluted my method was. I'd like to hear how others might tackle this. Given how common this kind of thing is in games, I'm surprised I haven't found a good tutorial on it yet. You can be as general or as specific as you'd like in your answer.
|
0 |
Blocking Physics Raycasts with Unity's 4.6 UI? I use raycasts to determine hit objects and object selection in our game. I want these to be blocked by UI elements. Before I had a crude form of that where I just excluded rects of the screen, though with a non rectangle shaped UI that's pretty difficult. I want to have physics raycasts NOT go through UI objects, can this be done? My initial thought it adding colliders to the UI objects, though I'm not sure if the colliders will scale with elements based on screen size. Note Canvas Group does not apply to physics.raycast
|
0 |
Room generation with external walls and doors I am looking to implement a means to generate rooms with outer walls with windows and doors from prefab game objects in Unity. The idea is that a group of tiles is defined as a room which I then iterate through to find the outer tiles and then use their external edges to generate the walls of the entire room. Gathering the outer tiles is easy enough and working out the external edges is already implemented. What I need to understand is the best approach for using prefab game objects as the set pieces for walls and floors. Currently for a single wall piece, I have created a quad and made that into a prefab which I then clone, position and rotate into place along the outer edges. The below screenshot shows a room with walls made using the prefab wall GameObject. In this screenshot, the room consists of 12 wall GameObjects. I want to avoid having lots of GameObjects for single wall segments and instead perhaps merge them all into a single mesh on a single GameObject. What I would like to achieve is to be able to create a consistent set of pieces for each outer wall, with windows and doors (most likely cloned from other prefabs) to build a realistic looking room. For example, any single length of a wall would be made up from Wall gt Wall gt Window gt Wall gt Wall Perhaps there is a much easier way to achieve this that I have overlooked but searching for room generation always leads back to examples for dungeon crawlers and roguelikes. I am not creating a dungeon crawler, nor am I generating the environment proceedurally, instead the player will be able to create rooms in a similar fashion to Evil Genius and The Sims. In the current approach, creating a room which is 5x5 would mean that there are a total of 20 wall GameObjects and 25 floor GameObjects. I am not keen on having this many objects in the scene for a single room. I would prefer to be able to create a mesh for the entire room, adding in the vertices and triangles from the prefab mesh to cut down on the number of GameObjects in the scene. Does anyone have any experience with building rooms in this fashion, or are there any clear examples of how to achieve this? I am not sure how to translate and rotate a prefab and then merge the translated meshes into a single mesh. Perhaps I am barking up the wrong tree and there is a better approach but for now, this is the only way I can see which is possible to achieve what I want.
|
0 |
Player object glitching around when there is a low framerate Unity C I just started to make this game, it runs fine on my computer. 60fps, but when I tested it on another computer, with lower fps, the player just started to jitter and glitch around a lot. The game is basically unplayable like that, and I want to make sure that everyone who plays my game will be able to enjoy the full experience. I have pasted the specific part of the code for the movement below. void Update () rb.AddForce (Vector3.forward ForwardSpeed) if (Input.GetKeyDown (KeyCode.A) amp amp side gt maxSideLeft) rb.AddForce ( Vector3.right Speed) side 1 else if (Input.GetKeyDown (KeyCode.D) amp amp side lt maxSideRight) rb.AddForce (Vector3.right Speed) side 1 if (Input.GetKeyDown (KeyCode.W) amp amp level lt maxLevelHeight) rb.AddForce (Vector3.up Speed) level 1 else if (Input.GetKeyDown (KeyCode.S) amp amp level gt minLevelHeight) rb.AddForce ( Vector3.up Speed) level 1 if (Input.GetKeyDown (KeyCode.R) Input.GetKeyDown(KeyCode.Space)) SceneManager.LoadScene ("Scene1") Time.timeScale 1
|
0 |
Doing object movement in a loop in unity I have a Game Object at position (0, 0, 0). To move it to position (2, 2, 2), I'm using this code below void Update () Vector3 TargetPosition new Vector3(2, 2, 2) transform.position Vector3.MoveTowards(transform.position,TargetPosition, 23 Time.deltaTime) How do I put this movement in a loop like behavior so that whenever the Game Object reaches position (2, 2, 2), it again starts moving from (0, 0, 0) to (2, 2, 2) ?
|
0 |
GameObject's scale gets 0 after being parented in editor 1) Before 2) After being parented. I found a pattern. When adding the child, if the parent's scale.z 0 the child scale.xyz becomes 0 on parenting. If the parent's scale.z ! 0 it works. Another experiment that I tried was, after successfully adding the child(without getting scaled down to 0) and then to make the parent's scale.z 0, the children's scales don't get affected at all. Why?
|
0 |
How to move player out of multiple penetrating colliders? The player in my game can teleport like Noctis from ffxv.The player shots a weapon projectile and then teleports to the projectile. I'm using raycast to calculate the weapon position after thrown. However, I need to check if the weapon is stuck in an unteleportable position after being thrown. It is possible to have multiple penetrating colliders. Ex spear gets sandwiched between two walls that is narrow enough for the weapon to pass through but not tall enough for the player to stand. I want to somehow check for a nearby valid position for after teleporting in that situation. I also want the teleport to fail if the weapon is horizontally in the middle of the "pipe". I could do a bunch of overlapBox checks within a radius distance from the teleport point but that doesn't seem efficient. I want to give the player some leeway when aiming a teleport. Also, the teleport is not immediate. The player can wait some time before teleporting to the weapon. So it is possible for a moving platform to block a raycast from the player. In which case I still want the raycast to succeed. I'm using unity and a custom raycast based 2d character controller for normal movement.
|
0 |
Is there any way to move the sprites inside the sprite editor? I have imported a .png file of a stickman in which I had placed his head, body, two legs, and two hands a bit far apart from each other so that Unity will automatically convert the picture into sprites. Indeed, Unity did convert those body parts into sprites easily but now I have a problem. I made a bone going through the body and another bone going from the body to the head through the transparent area in between the sprites. Also, I have created one bone for each hand and leg and parented them to the bone in the body. The problem is that when I automatically generate geometry then the mesh rendering works completely fine within the body of the stickman, but it doesn't work anywhere else, be it the hands, or the head, or the legs. I can see the mesh only in the body of the stickman and nowhere else. Does this problem arise because the sprites are not connected, or is there any other reason? I am very new to game development, therefore please try to explain it in simple words. Thank You.
|
0 |
How do you create fnt (angelcode format) files from existing bitmaps? I often gets the same problem Someones creates a nice bitmap font for me in form of a sheet nicely formated into a png, like this ...and i need to create the angelcode .fnt atlas for using it (into Unity, libGDX, or countless other engines). Yet, every time I google it, I stumble upon dozen of tools that create .fnt files from rasterized TTF fonts. (BMFont, Fontbuilder, etc.) Correct me if i'm wrong but they don't support exsting images, they always start by generating one from a vector font. I end up semi manually creating the file with an ugly script (the format is quite simple), but it's incredibly tedious. Surely there is a much better way to do that? Especially for monospaced fonts which are very easy to partition... edit I've made a small javascript tool to solve that. if by any chance you're interested, it's here http fontcutter.fbksoft.com
|
0 |
Behaviour Trees How to clean up when a sequence is interrupted? I'll try to show my problem on a minimal example, in reality it's more complex It's a simple behaviour, that repeats quot an action quot that has a certain animation. If a player gets close, this sequence gets interrupted and the AI executes the quot Flee quot action. The interruption happens because the top level selector is quot dynamic quot which in Unity NodeCanvas means, that its higher priority nodes get executed every frame and if they succeed they interrupt the lower priority ones. My problem is shown via the red arrow if the quot action quot gets interrupted, the clean up (in this case quot stop animation quot ) doesn't execute. What is the best practice to handle the clean up? Is my setup flawed? Or should I just be using a different interrupting mechanism? Thanks for any help!
|
0 |
Unity5 mixing animations with different properties Maybe there are tons of questions about this but i dont know what to look for. I have 2 animations, one is aiming a weapon and the other one is shooting. When i aim the weapon i animate only its position upward and a little bit to the left so its in front of the camera. When i shoot, i just rotate it a bit on the x axis. My problem is, when i shoot while the weapon is aimed (animated upwards and left) the whole Weaponholder get back to its initial (not aimed) position. I thought when i just animate the position in one clip and only rotation in another i can mix them together. Am i on the wrong way or just did something wrong? Thank you
|
0 |
Instantiate prefabs at particular vectors using text file (Unity3D game) I need to read a text file containing two pieces of information on each line, and use that information to instantiate a prefab at the correct location in a Unity3D game (c script). The locations are either North, South, East, or West (each a particular vector). For example, the first line of the text file might read landmark1, North In a script, I need to instantiate landmark1 and assign it to case North vector. The below script is what I've got so far. Basically, I can read from the text file but I don't know how to assign that information to different cases. I'm guessing I need to use an array somehow but I'm not sure how to do that here. Any help would be appreciated. Thanks! using System.Collections using System.Collections.Generic using System.Text.RegularExpressions using UnityEngine using System.Linq using System.IO using System public class Landmarks MonoBehaviour spawnable prefab gameobjects public GameObject castle Use this for initialization void Start() StreamReader reader new StreamReader( "C Users ... landmarks.txt") insert full path here String textContents reader.ReadToEnd() string dataArray for (int i 0 i lt (textContents.Length) i ) set case if first line "castle, North" then instantiate object castle at vector 'north'
|
0 |
Unity Third Person Controller Camera Relative Script I'm an newbie in game developing. So i have a script for a camera that i attach to the player. I was wondering how to make a Third Person Controller with WASD controls that moves in the direction that the camera is facing. If you need it here's the camera script that i use using System.Collections using System.Collections.Generic using UnityEngine public class ThirdPersonCamera MonoBehaviour define some constants private const float LOW LIMIT 0.0f private const float HIGH LIMIT 85.0f these will be available in the editor public GameObject theCamera public float followDistance 5.0f public float mouseSensitivityX 4.0f public float mouseSensitivityY 2.0f public float heightOffset 0.5f private variables are hidden in editor private bool isPaused false Use this for initialization void Start () place the camera and set the forward vector to match player theCamera.transform.forward gameObject.transform.forward hide the cursor and lock the cursor to center Cursor.visible false Cursor.lockState CursorLockMode.Locked Update is called once per frame void Update () if escape key (default) is pressed, pause the game (feel free to change this) if (Input.GetButton("Cancel")) flip the isPaused state, hide unhide the cursor, flip the lock state isPaused !isPaused Cursor.visible !Cursor.visible Cursor.lockState Cursor.lockState CursorLockMode.Locked ? CursorLockMode.None CursorLockMode.Locked System.Threading.Thread.Sleep(200) if(!isPaused) if we are not paused, get the mouse movement and adjust the camera position and rotation to reflect this movement around player Vector2 cameraMovement new Vector2(Input.GetAxis("Mouse X"),Input.GetAxis("Mouse Y")) first we place the camera at the position of the player height offset theCamera.transform.position gameObject.transform.position new Vector3(0,heightOffset,0) next we adjust the rotation based on the captured mouse movement we clamp the pitch (X angle) of the camera to avoid flipping we also adjust the values to account for mouse sensitivity settings theCamera.transform.eulerAngles new Vector3( Mathf.Clamp(theCamera.transform.eulerAngles.x cameraMovement.y mouseSensitivityY, LOW LIMIT, HIGH LIMIT), theCamera.transform.eulerAngles.y cameraMovement.x mouseSensitivityX, 0) then we move out to the desired follow distance theCamera.transform.position theCamera.transform.forward followDistance
|
0 |
Minecraft Type Game Support Blocks OK I have a game that is similar to minecraft in a sense. Players can build castles block by block. I'm using Unity3D and Photon Network for my game and I was wondering how I would handle detecting if blocks have a support system to the ground. Here is the game in question. Let me know what are some solutions besides using rigid bodies I've tried doing that and it has severe performance issues over a network. Thanks Youtube Video of Game
|
0 |
In Unity, why do my animator states wait until the end of each animation to change? I'm trying to make a simple idle walk transition in Animator using Unity. I've set a script that changes the Speed value from the Animator, and it works perfectly when I move the character forward when the game is on. The transitions work well between both animations, except that they don't start automatically after the speed has changed to greater than zero. I've found out that it waits until the animation loop gets to it's end, which makes the game feel dull and not fluid at all. I don't think there's an issue with the code, but I'm attaching it anyway pragma strict var anim Animator function Start () anim GetComponent("Animator") function Update () var move float Input.GetAxis ("Vertical") anim.SetFloat("Speed",move) transform.Rotate(0,Input.GetAxis("Horizontal"),0) transform.Translate(0,0,(Input.GetAxis("Vertical") Time.deltaTime move))
|
0 |
How to detect mouse over for UI image in Unity 5? I have an image that I have setup to move around and zoom in and out from. The trouble is the zoom can be done from anywhere in the scene, but I only want it to zoom when the mouse is hovering over the image. I have tried to use OnMouseEnter, OnMouseOver, event triggers, all three of those without a collider, with a collider, with a trigger collider, and all of that on the image itself and on an empty game object. However none of those have worked...So I am absolutely stumped...Could someone help me out here! Here is my script private float zoom public float zoomSpeed public Image map public float zoomMin public float zoomMax void Update () zoom (Input.GetAxis("Mouse ScrollWheel") Time.deltaTime zoomSpeed) map.transform.localScale new Vector3(map.transform.localScale.x zoom, map.transform.localScale.y zoom, 0) Vector3 scale map.transform.localScale scale new Vector3(Mathf.Clamp(map.transform.localScale.x, zoomMin, zoomMax), Mathf.Clamp(map.transform.localScale.y, zoomMin, zoomMax), 0) map.transform.localScale scale
|
0 |
Post processing effects not visible on mobile apk build While setting up post processing on a project that I am currently working on, I discovered that post processing effects are not visible on the apk build on mobile. I setup a new Project with URP on Unity 2019.3.0f5 and increased the post processing bloom effect intensity, it works just fine on the editor play mode, however, it is not visible when I build to a mobile apk. Is there a different way of setting up post processing specifically for mobile? Here are screenshots 1 https i.stack.imgur.com uKm5d.jpg Mobile build screenshot(post processing effects are not visible) 2 https i.stack.imgur.com ivQrQ.jpg Unity editor play mode screenshot(post processing effects are visible)
|
0 |
2D character with baseball bat implementation in Unity I'm making a 2D baseball game in Unity and I'd like to know how the player and the bat should be connected. For instance, if I use single sprite for both the player and the bat, then how should the collision between the bat and the ball be detected?
|
0 |
Why use Time.deltaTime in Lerping functions? To my understanding, a Lerp function interpolates between two values (a and b) using a third value (t) between 0 and 1. At t 0, the value a is returned, at t 1, the value b is returned. At 0.5 the value halfway between a and b is returned. (The following picture is a smoothstep, usually a cubic interpolation) I have been browsing the forums and on this answer I found the following line of code transform.rotation Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime) I thought to myself, "what a fool, he has no idea" but since it had 40 upvotes I gave it a try and sure enough, it worked! float t Time.deltaTime transform.rotation Quaternion.Slerp(transform.rotation, toRotation, t) Debug.Log(t) I got random values between 0.01 and 0.02 for t. Shouldn't the function interpolate accordingly? Why do these values stack? What is it about lerp that I do not understand?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.