_id
int64
0
49
text
stringlengths
71
4.19k
0
collision detection and normals from rigidbody Until now I've been developing my player character using a Character Controller, but have since decided to switch to rigidbody due to the controller's limitations. In order for my movement code to run as expected I need to know when the player is colliding with anything, and the normal of the surface it's colliding with. This is easy with a Character Controller, but is there a simple way to do it with a rigidbody? Here is a stripped down version of the script I'm using for collisions. Used in other scripts (Necessary) public GameObject ground null public Vector3 groundNormal public bool onGround Used internally public bool isColliding public float slopeLimit Character Controller public CharacterController controller void Start() controller GetComponent lt CharacterController gt () void Update() Check if the player is colliding with anything (Character Controller) if (controller.collisionFlags CollisionFlags.None) isColliding false else isColliding true Check if the player is standing on the ground if (isColliding amp amp groundNormal ! Vector3.zero) onGround true else onGround false void OnControllerColliderHit(ControllerColliderHit hit) Check for floor if (Vector3.Angle(transform.up, hit.normal) lt slopeLimit) Store floor object data ground hit.gameObject Store ground surface normal groundNormal Vector3.Normalize(hit.normal) else reset variables ground null groundNormal Vector3.zero slopeLimit is a static value. Additionally, getting the ground object isn't actually necessary atm, but I plan on using it later. Edit Currently I'm using controller.collisionFlags to detect when the player is colliding with something and haven't been able to find a similar alternative. Setting the isColliding bool to true using Rigidbody.OnCollisionStay would be simple, but setting it to false without use of another void function seems difficult. is that possible at all?
0
Encapsulating parameterised prefabs I'm currently using the following general pattern for most of my configurable components (i.e. MonoBehaviours) public class MyComponent MonoBehaviour Configurable fields SerializeField private bool someParameter SerializeField private int anotherParameter Fake constructor to act as a replacement for GameObject.AddComponent with additional parameters. public static MyComponent AddTo(GameObject gameObject, bool someParameter, int anotherParameter) var myComponent gameObject.AddComponent lt MyComponent gt () myComponent.someParameter someParameter myComponent.anotherParameter anotherParameter return myComponent Public properties and other methods ... This works around the lack of constructors for MonoBehaviours but still encapsulates the parameters in such a way, that they can only be set at the time the object is created, or through the Inspector (which is effectively the same thing once the game is built). Unfortunately, this approach doesn't help once I want to use my component inside a prefab. When I instantiate the prefab, the component has already been created, and I can no longer touch those parameters. And as far as my google fu can tell, there's no way to pass parameters into prefab instantiation (much like there isn't a way to pass a parameter into AddComponent). It seems like everyone just instantiates their prefabs and then fiddles with some public properties to configure them. So the question is, is there any way to set things up, such that I can configure some fields on my prefabs, but without exposing them publicly and breaking encapsulation? (I realise that I could add a similar static "factory" method which instantiates a specific prefab and then configures the component inside that prefab, but a) this means adding one such method for each prefab and b) it breaks down once I want to configure multiple components within the same prefab.)
0
Why isn't my player moving? Why is my code not working? using UnityEngine using System.Collections public class NewBehaviourScript1 MonoBehaviour public float moveSpeed public Vector3 input public Rigidbody rb void Start () rb GetComponent lt Rigidbody gt () void FixedUpdate () moveSpeed 2 input new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) rb.AddForce(input moveSpeed)
0
Why are my target following objects rotated the wrong way? I writing a script that would make my players reach a target destination. It looks like this so far private void MoveTowardsGoal() if (Vector3.Distance (reachGoalTarget.transform.position, transform.position) gt 2.0f) rDirection (reachGoalTarget.transform.position transform.position).normalized if (rAcceleration lt rMaxSpeed) rAcceleration 0.5f rVelocity rDirection Time.deltaTime rAcceleration transform.Translate (rVelocity,Space.World) It works fine The objects move towards the destination point. However, I want them to move looking at the target in the forward direction (forward z axis). Currently they move with their x axis facing front. I tried a simple rotation inside Start() like transform.LookAt(reachGoalTarget.transform). With this, they look in the forward direction but then they completely move off their initial positions by rotating themselves to reach the goal. What am I doing wrong?
0
How can I implement a revealing light beam? In SEARCHLIGHT, you control a ray of light that illuminates incoming enemies that are otherwise invisible in the night sky. Here is an illustration How would I go about doing this, preferably in Unity? I imagine this is less about lighting and more about shaders, but I'm not sure on details. The fact that I know very little about coding shaders makes it worse. If it is about shaders, what are the specifics? Is there a stretched quad that moves with said shader applied to it, or perhaps is using the Line Renderer a better option? As a beginner, may I try to achieve a similar effect, or should I leave it for when I'm better? (P.S. The game was made in Unity. Here is its itch.io page.)
0
Unity2D Repeating of code makes game lag (Spawnning script) does anyone knows how to shorten down this script and that I can edit the amount of enemies I want to spawn in, so that I don't have to keep on copying and pasting the same method below again and again, my code is also making my game a bit laggy. Which isn't a good sign. This is my code public bool fromTop false public GameObject enemy1 public float enemy1Time 2f public GameObject enemy2 public float enemy2Time 2f public GameObject enemy3 public float enemy3Time 2f public GameObject enemy4 public float enemy4Time 2f Variable to know how fast we should create new enemies void Start() InvokeRepeating ("Enemy1", enemy1Time, enemy1Time) InvokeRepeating ("Enemy2", enemy2Time, enemy2Time) InvokeRepeating ("Enemy3", enemy3Time, enemy3Time) InvokeRepeating ("Enemy4", enemy4Time, enemy4Time) void Enemy1() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy1, spawnPoint, Quaternion.identity) void Enemy2() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy2, spawnPoint, Quaternion.identity) void Enemy3() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy3, spawnPoint, Quaternion.identity) void Enemy4() Vector2 spawnPoint new Vector2 (transform.position.x, transform.position.y) if (fromTop) float x1 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 float x2 transform.position.x GetComponent lt Renderer gt ().bounds.size.x 2 Randomly pick a x point within the spawn object spawnPoint.x Random.Range (x1, x2) else float y1 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 float y2 transform.position.y GetComponent lt Renderer gt ().bounds.size.y 2 Randomly pick a y point within the spawn object spawnPoint.y Random.Range (y1, y2) Instantiate (enemy4, spawnPoint, Quaternion.identity) Please and Thank you. )
0
How to pause audio playback when a breakpoint is hit or resume afterward? When my code hits a breakpoint, audio that was previously started (via an AudioSource) continues to play while the threads are paused. I'm using a coroutine to query the status of the AudioSource, and update my UI. Because the audio continues to play, then after I've spend some time stepping through code the next frame tick when Unity gets control back runs the next iteration of this coroutine, which updates the UI. I never get to see the in between states. Because it's a relativley short audio clip it's usually finished playing before I've finished stepping through the code. I'm using Unity 2018.4 with VSCode and the Debugger for Unity extension, if that helps. I'm quite lost at what to try here. Looking for issues with Unity's AudioSource and breakpoints yields a lot of varied information about audio issues in general in Unity. I've tried using Debug.Break(). It pauses the Unity editor, which can be useful but has the following caveats it requires extra effort on each breakpoint that requires enabling (if the call is not there already) it requires manual intervention to resume the editor once you've finished stepping through code because it is code, it cannot be added after Unity is playing, e.g. to additional breakpoints that are added once debugging has started Does Unity have a mechanism that enables this behaviour that I've just missed? If not, what's an appropriate alternative approach?
0
Unity built in Network Lobby How to move GUI? I'm using built in network manager HUD and I'm fine with it for now. But I can't move lobby GUI, only Network Manager HUD. Is there a way to move it down to make space for Title Art?
0
Unity (UNET) Pass custom data when creating and joining a match in multiplayer I've written some simple stuff to make a lobby for matchmaking. Now I want to pass some extra info besides the match name to the lobby. Something like Player's avatar and a number of players connected and what not. Thereto, I also want to pass information to the game from the players. For example, two players connect to a match and the character pick starts. For this I want to have the player's info regarding the characters they've picked and the character's weapons info (e.g. customized weapons info). I store all that in a json file and load from it to a class object. Is it ok to add these classes to, say, the player connection prefab that holds Network Identity or is it done somehow differently? Can someone maybe help me with that in the context of Unity 2018 (i.e. give some advice or referrences to some relevant information)? Appreciate all the help and thanks in advance.
0
How to use ref in an enumerator i have this enumerator that loads a folders images asynchronously and i would like to be able ta pass the array as a parameter, but when i try to do it even though i get no error the array (source) does not get populated. private IEnumerator GetTextureFromPath(string dirname) here it would be ,Texture2D source var fileNames Directory.GetFiles(Application.persistentDataPath quot quot dirname, quot .jpg quot ) source new Texture2D fileNames.Length this source array would be referenced in the params. Array.Sort(fileNames, (s1, s2) gt Path.GetFileName(s1).CompareTo(Path.GetFileName(s2))) int index 0 foreach (var fileName in fileNames) UnityWebRequest webRequest UnityWebRequestTexture.GetTexture( quot file quot fileName) while (!webRequest.isDone) yield return webRequest.SendWebRequest() if (webRequest.isNetworkError webRequest.isHttpError) Debug.Log(webRequest.error) else source index LoadTextureFromPath(fileName) source index .name fileName index Debug.Log( quot Ends server comm quot ) Debug.Log( quot FileNames quot quot quot fileName) what this function does is get all files from a directory and populate a texture2d array with each image. now this call happens on game load so since i have 4 more arrays (source1 , source2 etc) i would like the array to be in the parameters so i can tell the script as to which array to populate from that directory it seems its due to it being asynchronous and an enumerator. Because i made the function into a void one with the texture as a ref and it worked. public void LoadTextureArray(string dirname, ref Texture2D arr) var fileNames Directory.GetFiles(Application.persistentDataPath quot quot dirname quot quot , quot .jpg quot ) arr new Texture2D fileNames.Length Array.Sort(fileNames, (s1, s2) gt Path.GetFileName(s1).CompareTo(Path.GetFileName(s2))) Debug.Log(string.Join( quot n quot , fileNames)) int index 0 foreach (var fileName in fileNames) arr index LoadTextureFromPath(fileName) arr index .name fileName index So my take on this is i need to be able to use ref into the enumerator but that is not possible from what it seems since if i do put it as a parameter i get this error. or if there is another way to be able to pass the texture array from the function call! Thank you! iterators cannot have ref in or out parameters
0
Why models that are far from camera not rendered correct in unity? I am making a roguelike in unity and i came across a problem where models are far from the center of camera rendered weird like upper right enemy. I have added screnshot there are also camera settings. I tried changing field of view but it did not work. Does anyone know which option causes that distortion?
0
How to handle global Data within a state machine setup? (C ) I am currently building a turn based framework (Unity,C ) I was tired of my former tight coupled systems and opted for a state machine this time, basically all components subscribe to the state Enter and state Exit event. I am aiming for scalability and structure. But I ran into a problem. If the components cannot communicate directly, how to store and forward data in between states? Example The game starts with unit placement. The player has the option to select a unit in his pool via the ui and place it on the board. The Unit creation logic is and should(?) be handled inside the level script. How does it know where to create which unit? Ive done a workaround with a static container class, with is basically my clipboard. The player assigns a grid cell for his selected unit and the game leaves the state. While leaving the state the level scripts scans the clipboard and creates any assigned units. But I feel like a cheated my attempt to really work strictly within a firm structure this time to guide the design process. Is there a better way?
0
How can I add array of components to a new gameobject? I use Getcomponents to get all components from existing gameobject Component components go.GetComponents(typeof(MonoBehaviour)) And I want to add them now to another gameobject for (int i 0 i lt components.Length i ) var comp components i newObject.AddComponent lt comp gt () components is type Component But when I try to type components inside the AddComponent lt the variable components not exist. Tried then to make the comp variable but can't type it inside the lt either.
0
Assign a ScriptableObject to MonoScript through code Sample code public class Item MonoBehavior public ItemObject item the scriptable object void Start() do stuff Normally I would drag and drop the asset of the ScriptableObject in the inspector. How can I find and assign the asset (from Project View) through the script during runtime and possibly add it to a List lt gt or Array ?
0
Level Modeling Workflows in Maya for Unity I'm wondering what the standard workflow for modeling static levels for Unity (or for that matter, other High Level engines) is? My somewhat limited knowledge tells me that the best process is modeling the entire static level in Maya, texturing, then baking AO and some static lighting into the scene, then importing the single level asset into unity to add dynamic objects. Is there another way that I should be doing this that is more efficient in a performance sense or from a workflow point of view? I know the question is somewhat open ended, but generally i'm asking what the standard workflow for level modeling is. Thanks!
0
I imported both the rig and baked animation seperatly from Maya, but it's not working correctly I am using the animation controller to bind the "jump" animation I did onto the rig itself. I don't get any errors. The animation plays. Except it seems to only affect the root joint only. Basically the model moves but not the arms or legs. They stay static. So If i have a character jumping few feet away, the entire model rig will move in jump motion(X and Y axis), but nothing happens with legs and arms. What's going on?
0
Multiplayer object interpolation Currently I'm participating in a multiplayer game project as a network developer. Unfortunately, however, I'm facing an interpolation problem which makes game objects look like they are 'jumping teleporting' sometimes. Images don't look smooth compared to the server even if the client runs at 60 frames per second. Things about the architecture Based on client server model. server sends regular transform updates at every 33 milliseconds (30fps). Client receives and stores position updates in a queue. then, plays them from 1 second behind using interpolation between each update. Before processing the next packet, client calculates the sent time between current and next packet to find out how many milliseconds this interpolation should take. at every frame, it deducts the delta time from the interpolation time. so, if interpolation time reaches a number equal or less than zero, it iterates to the next packet (if the value is less than zero, it means that there is a time fragment. so the client also considers that time fragment for interpolation of the jumped packet at the same frame.) Client doesn't deal with rigidbody only position and rotation. I'm using Unity3D's LERP method from the Vector3 class. Using SLERP didn't solve the problem. Any ideas? Everything looks great on paper.
0
Finding Game Object with Regular Expressions Is there a way to use a Regular expression in the GameObject.Find() method? I'm making a checkers game and I've got pieces named Red Piece (x,y) and White Piece (x,y) (where x amp y are actual integer coordinates). I want to destroy a piece at a certain x,y. So what I'm trying to do is something like Destroy(GameObject.Find(Regex.Matches("(Red) (White) Piece (" x "," y ")"))) I need it to find any object with a name that contains "Piece (x,y)" whether it's a red piece or a white piece, and destroy it. Any ideas?
0
Is there any way to detect cpu battery temperature on Android 7.0 platform in Unity? I tried WeTest but it's not working because my test device is Android 8.1. Also, I tried Emmagee however it's just working on Android 6.0 and below. Is there any other thing?
0
Unity UI Mask is not working in samsung SM G610f I am using unity 2018.3.13f1 and getting the issue that unity ui mask is not working in a specific device like Samsung SM G610f. The masking work in other android devices. But(Samsung SM G610f) the mask became rectangle. Below is the reference image link. https drive.google.com file d 1aTvKIxFh0HhNXgTYg5FOqvTsCy0aqr4e view?usp sharing Please help. Thanks.
0
How to set up bloom in Unity Last time I used image effects in Unity it was back when 3.0 was released and for bloom you used the object's alpha to indicate whether it should glow or not. Now in 4.2 I couldn't grasp how to apply the image effect properly. It seemed to put the whole scene to glow and alpha did not affect it. There was no help from the Unity docs which are pretty much just spec sheets for the effects and no proper tutorials around. This leads to couple of questions How do you create something like the screenshots in the Bloom page in the docs? Only the car windows and metal parts glow, but no glow on the concrete. How do you make a light source like the second image on the above link? I tried different shaders and lights on a gameobject but none of them produced anything like that. What does the HDR checkbox in the camera actually do?
0
Advice regarding Unity hosted content I'm currently trying to build a mobile application that, for the purposes of trying to keep small in size, I would like to have store much of its content Online and be downloaded to the users mobile when the application requires it. Ideally I'd like to do so not just as a means to reduce the applications original size, but also to allow new assets to be introduced over time (such as new objects and textures) without the user having to reinstall the application or download a new update. I am at the moment researching into the use of Unitys Addressible Assets for these purposes, and am currently trying to test and implement this idea on a small scale using assets stored using Google Cloud storage. If possible however I would like to to ask whether anyone here has any experience with storing and accessing assets on an external server, and if so, might they have any advice as to whether or not this could be a feasible solution for these purposes? Any help would be really appreciated, as this is an area that is completely new to me. Thanks in advance.
0
How to change a background from a list of images on button click? I'm trying to create a button within the settings menu that allows you to change the image of a GameObject per click. So, let's say there are only 2 different images available to choose from and it starts with Image1, if you press the button it changes to Image2 and if you press again it goes back to Image1, like a loop. My issue is on how to write the script for this.
0
Removing all destroyed objects from a list I am a little confused on deleting objects in a List. I realise that clearing the list doesn't destroy the gameobject in Unity. Hence I have written this routine to destroy and remove clear all block sprites away for (int i 0 i lt blockSprites.Count i ) Destroy(blockSprites i ) blockSprites.Clear() But what if I only wanted to destroy some of the elements (a variable amount)? In that scenario the List.Clear() function wouldn't work. Would I have to make another list of indexes in order to go through destroying and removing from the list in two sweeps. Or is there a better way?
0
How to set a specific face's texture color in Unity? First off, let me describe my situation... So I'm building a voxel engine based on this tutorial. I'm using my own texture tilesheet. Most of the tiles have their own color except grass, leaves, and a few others. These specific ones are meant to be colored based on the temperature and humidity of the location. AlexStv (the author of the tutorial linked above) said the mesh colors array could be set, but I tried that and nothing happened. I probably did it wrong though, not sure. But he also said "you may need a shader that render vertex colors, not sure if the standard shader does that anymore" so that could also be the issue. So... Do I need a custom shader? If not how do set the face's colors? EDIT, Note I just tried a custom shader called UnityVC, it still didn't work so I guess I must be doing the color thing he suggested wrong.
0
Video play in unity3d skybox I want to play 360 video in skybox. Is there any direct way avaiable to do this task. One long, boring, inefficient procedure which seems that Convert 360 to frames Convert frames into cubmap Use that cubeMap in skybox and Programatically change it's textures(Frame) quickly so that video effects shown This is the long task which seems to me possible but is there any other way available?
0
Unity Gyroscope orientation (attitude) "wrong" I am using the Unity reference and example implementation here https docs.unity3d.com ScriptReference Gyroscope.html I struggle to fix an orientation problem. When my phone lies flat on the ground, screen facing upwards, unity thinks I am looking as if I'd take a photo of a landscape. When I actually hold the phone as if I'd take a landscape photo, the screen shows me the sky. Rotating then shows me an arc from sky to my left or right side. What I want is Holding the phone as if I'd take a landscape picture should do the same in Unity. Here is a short video where the phone lies flat and then I pick it up and look left and right on a chair. and this is the codesnipped responsible protected void Update() GyroModifyCamera() void GyroModifyCamera() transform.rotation GyroToUnity(Input.gyro.attitude) The Gyroscope is right handed. Unity is left handed. Make the necessary change to the camera. private static Quaternion GyroToUnity(Quaternion q) return new Quaternion(q.x, q.y, q.z, q.w)
0
Does pixels per unit property affect performance of the game in Unity? The Sprite import inspector has a Pixels Per Unit setting that controls the size of the sprite objects when they're added to the scene Will Unity resize the sprite at run time or will it be resized after me changing the property and saved for the future?
0
Repeating a mesh instead of stretching it I would like to put acoustic foam into a case object To do that, I have created a foam object Now I'm having a really hard time to cover the case in Unity with this object I have to adjust multiple foam objects absolutely exactely besides each other. This is really time taking. I was thinking that it would be great that if I could use scaling, and instead of scretching, Unity would repeat the object. Is that perhaps somehow possible? Thank you very much!
0
How to do draw a "visibility polygon" in 2D top down Unity? I've made a very simple 2D top down prototype with Unity. Now I want to expand the thing and add a feature where objects change when the player looks at them. So I have to add a visibility polygon feature. I want to be able to get a list of objects (2d Colliders) which are in the Field of view of the player. How I can do that? I looked around and only found a tutorial which works with Physics2D.Raycast, but this seems to be only one ray as I need a field of view. Similar to the light of a flashlight. I've drawn a sketch to illustrate my question In this case the list should contain the collider V1, V2 and V3 because the player can see them. Edit I experimented with the sending a "fan" of Raycasts every 0,1 but this solution does have some problems. The accuracy depends on how far the collider is away. Also this is not the best performing solution. And there are problems with small objects. As solutions like this https www.redblobgames.com articles visibility seems to be a lot of work just to reinvent something which is already out there I wonder if there is a built in way in unity to help me to compute this area.
0
Unity FPS style turning I have this code using System.Collections using System.Collections.Generic using UnityEngine public class Control MonoBehaviour public int speed public Transform tf Use this for initialization void Start () Update is called once per frame void Update () if (Input.GetMouseButton(1)) tf.eulerAngles tf.eulerAngles new Vector3 (0, Input.GetAxis("Mouse X") speed, 0) I would like to know how to use this so that when I move my mouse and hole right click the character will turn but the mouse will not move from the center of the screen
0
How do I make a quake style camera tilt in Unity? I want to make a retro styled game with a modern look to it, and to do so I wish to make a quake styled camera tilt. By that I mean when moving sideways the FPS Camera tilts a little bit, and the returns to default when letting go of the key. I have little to no scripting knowledge. https www.youtube.com watch?v scSea v7JHA Notice how in the video when moving to the side the camera tilts a little bit.
0
How can I make that also the yradius values will change when the flag is true? In this part when I'm changing the xradius slider it's also changing the yradius slider at the same time and same value. But I can't change the yradius when trying to change it's slider. I want to be able either change the xradius or yradius when the flag is true. Both will change to the same values but I want to be able to change also the yradius so it will change the xradius. if (changeBothRadius) yradius xradius xradius yradius I tried to add the xradius yradius but it's not working only when changing the xraiuds it's working. using UnityEngine using System.Collections using System.Collections.Generic RequireComponent(typeof(LineRenderer)) public class DrawCircle MonoBehaviour Range(0, 50) public int segments 50 Range(1, 50) public float xradius 5 Range(1, 50) public float yradius 5 public bool changeBothRadius false Range(0.1f, 2) public float lineThickness 0.1f public bool minimumRadius false private LineRenderer line private List lt float gt radiusList new List lt float gt () void Start() line gameObject.GetComponent lt LineRenderer gt () line.positionCount segments 1 line.useWorldSpace false CreatePoints() void Update() line.startWidth lineThickness line.endWidth lineThickness CreatePoints() void CreatePoints() if (changeBothRadius) yradius xradius xradius yradius float x float z float angle 20 for (int i 0 i lt (segments 1) i ) x Mathf.Sin(Mathf.Deg2Rad angle) xradius z Mathf.Cos(Mathf.Deg2Rad angle) yradius line.SetPosition(i, new Vector3(x, 0, z)) angle (360f segments 1)
0
How do i manage skill collision target in Unity? I wanted to make a skill that can be used by both Player amp Enemy. How do I make it such that the skill will not be colliding with the owner caster or colliding with both? One stupid way I have is to create empty gameObjects as the Skill's child and set their tag as "targetPlayer","targetEnemy" or "targetAll" whenever my player enemy cast the skills. And when the skill collided with Player Enemy, i will check the skill's children and see if there's matching tag and proceed if so. Is there better way to do what i wanted??
0
How do you rotate RigidBody2D along a given access using velocity and not transform? I am trying to rotate my player along the centre of the world in Unity3D. All the tutorials and references I have looked through till now have left me to this working code void MoveAlongCurve(bool moveClockwise) if (!moveClockwise) timeCounter moveSpeed Time.fixedDeltaTime else timeCounter moveSpeed Time.fixedDeltaTime float x Mathf.Cos (timeCounter) float y Mathf.Sin (timeCounter) transform.position new Vector3 (distFromCentre x, distFromCentre y,0) Also this seems to work fine as well transform.RotateAround (Vector3.zero,new Vector3(0,0,1),speed) Now my question is how do i move my player using velocity? I was forced to keep my body as 'kinematic rigidbody2D' however I want my player to be a 'dynamic rigidbody2D'. My reason for this is several 1. Movement via velocity makes it independent of the timeCounter. 2. Dynamic Bodies enable collisionDetection. Hence it is basically a requirement for my game. Thank you so much for taking the time to read this! Any suggestions or nudges in the right direction would be greatly appreciated and if you find anything wrong in my code or approach please comment!
0
GraphicRaycaster performance OnClick Let's say I have two Canvases BackgroundCanvas and UICanvas. Now, on BackgroundCanvas I have multiple moving, not clickable objects so I removed the GraphicRaycaster ( 69 to performance). On the UICanvas, all the objects are on the UI layer. I also have some additional layers somewhere else. Now, if I change the GraphicRaycaster's (on UICanvas) blocking mask to UI only, would it improve performance if there are other objects on the Default and other layers? Or would it still ray all these objects on other layers? How does this really work? I'm asking cause I don't see any performance impact while switching these Blocking Masks, but after disabling the entire component I do (but the input is not working S).
0
How to make the character move along the axis using touch? I have the following code it works, but I don't know how it works. This is the code I found void Update() if UNITY ANDROID if(Input.touchCount gt 0 amp amp Input.GetTouch(0).phase TouchPhase.Moved ) Vector2 touchDeltaPosition Input.GetTouch(0).deltaPosition float offset touchDeltaPosition.x 40f 18 Mathf.Deg2Rad transform.position new Vector3(0f, 0f, offset) transform.position new Vector3(0f, 0f, Mathf.Clamp(transform.position.z, 7.1f, 7.1f)) endif I need to move the player along the axis by touch, for example, like in the game Cube Surfer! What I want to get (I used android emulator) The code I wrote works well at 720x1280, but if you set the resolution to 1440x2960, the controls become too sharp. I know why this is happening because touch.delta is getting too big. My code if (Input.touchCount gt 0) var t Input.GetTouch(0) var delta t.deltaPosition if (delta ! Vector2.zero) var offset transform.position offset.x delta.x Sensitivity Time.deltaTime offset.x Mathf.Clamp(offset.x, 4f, 4f) transform.position offset How to fix it? ScreenToWorldPoint this does not fit because the player moves along a spline. Thank for help
0
Shadow flickering with first person near clipping plane After adding a first personal controller asset, world shadows flicker like crazy. I don't understand the cause, and everything I've tried based on googling has failed to help. https i.imgur.com Mx5MCKB.gifv I've tried Increasing the near clipping plane of the camera. The first person asset I have defaults to 0.01. Changing it to 0.1 or higher seems to solve the issue, except that breaks the first person view. Toying with bias value on the directional light Changing Render Mode from Auto to Important on the directional light Changing the Shadow Projection quality to Stable Fit The authors of the asset have not been able to help, though it doesn't seem to be specifically related to their product, just the clipping planes required. I'm using Unity 2019.1.2f1 Personal.
0
Mixamo Fuse Unity eyelashes not correct I created a character in Adobe Fuse, sent it to Mixamo for rigging with blendshapes and downloaded the fbx for unity file. Below is how the character eyelashes appear in Fuse.. However, when I imported the fbx file and pulled it in my scene, the eyelashes appear as a piece of block. How do I fix this? EDIT It seems like the eyelashes are messed up due to Mixamo, there is no issue with Unity import. It happens when the Fuse character is sent to Mixamo for rigging and downloaded from there. When I opened the downloaded fbx file in Windows 3dViewer, it appeared with messes up eyelashes as shown below. EDIT Added the texture material option pane, material settings and import settings for albedo texture in Unity below
0
Unity Terrain Tools plants trees sideways My tree is clearly straight, but painting trees result in sideways ones. What can cause this? Tree is straight when placed manually as a prefab.
0
Object not Augmenting on small marker I am new to Augmented reality. I am developing a jewellery try on app with vuforia using unty3D editor. What I want is to augment a ring on the marker. I download an image(attached bellow) and used it as my marker and it was working fine but when I resized the image in paint to fit to finger the marker stopped augmenting the object. any help. What should be the marker size or anything else which I am missing ? Please help me.
0
How to remove or disable an extension asset in Unity 2020 I've been running Unity 2020.1 on Ubuntu 19.04 without any problems for a while now. Today, I installed the VSCode extension asset and now Unity just crashes during startup. I choose my project from Unity Hub, the splash screen and progress bar pops up, and then everything just shuts down. I've already submitted a crash report but I'd rather just revert the extension entirely so I can get working again. I've tried deleting the files from disk but Unity just downloads them again during startup. How can I either remove or disable the VSCode extension completely without starting Unity?
0
Unity Project Settings What is the difference between "Graphics SRP settings" and "Quality Rendering URP Asset" As the title says, I am a bit confused about the aspect that the URP asset is referenced from two different settings quot Project Settings gt Graphics gt SRP settings quot quot Project Settings gt Quality gt Rendering gt URP Asset quot In a blank URP Project, quot Project Settings gt Graphics gt SRP settings quot references the HighQuality URP asset, and quot Project Settings gt Quality gt Rendering gt URP Asset quot has three different tiers, all of which reference their respective URP assed (i.e., either LowQuality, MediumQuality, or HighQuality. Switching from one quality tier to another applies the respective URP asset, i.e., if I switch the quality tier to Low, the LowQuality URP asset is applied, even though the HighQuality is still set in quot Project Settings gt Graphics gt SRP settings quot . So now the question Why do I have to set a URP asset in quot Project Settings gt Graphics gt SRP settings quot if it seems that it is overridden by the URP asset defined in the quality tab?
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 are game menus logically structured? I've been struggling with making a game menu system in Unity for some time now. I spent time developing a way to help myself understand how game menus are connected together. Right now, I'm calling it the Screen Menu relationship. In this relationship, Screens (e.g. Main Menu, Game Over and Inventory screens) hold access to Menus (e.g. Options Menu, Level Select menu). These Menus are accessed via MenuButtons (e.g. Options menu button via the Pause Screen). Is this a valid way of thinking about how game menus are structured? How should I be thinking about it?
0
All sides shadow outline in Unity NGUI How can I make such exactly the same shadow using NGUI?
0
Admob for Unity clarification on use needed I'm following this documentation by Google on how to integrate Admob ads into my game and I'm confused because of the following This documentation says I build by game and then I mess around with ads. (Section Unity plugin API tells me how to add ads and that's after the build instruction). Shouldn't it be vice versa? That I place those ads and build last? Or, if I really do build first, where do I add those ads?
0
Cardboard on iPhone 5 doesn't render on stereo Has anyone ran into this? I'm on Unity 5.1.1p3, Cardboard Unity Integration v0.5 (5 28 2015) and an iPhone 5 running iOS 8.3 (12F70). I made a game that uses Cardboard and on an iPhone 6 the screen renders as expected two offset cameras. On an iPhone 5 however, while the screen does show the 2 viewport masking and the distortion correction, it's actually a single camera that is being rendered, defeating the purpose of Cardboard. Here's what I mean. This is the iPhone 6, as expected And this is the iPhone 5, which is wrong Any ideas? Some extra info The iPhone5 can only use GLES2. It doesn't support ES3 or Metal. But what I did notice is that if I make a build for GLES2 the first time the app runs on the device (be it iPhone 6 or 5), when the Cardboard camera gets enabled, the app crashes If then I quit the app and start it again from the phone without it being hooked up to Xcode, on the iPhone5 I get the wrong rendering I've shown while in the iPhone 6 the app just crashes again. And if instead I make my build with automatic graphics API detection, what happens is that on iPhone6 it goes to Metal mode and so it works fine and on the iPhone5 it goes to GLES2 mode which, as stated before, crashes if attached to Xcode but otherwise just runs only that with the wrong rendering.
0
Compare Lists in Unity3D C Hi guys I am working on a combo feature and I want to compare two C lists, something like this bool found false List lt int gt combo new List lt int gt () combo.add(1) combo.add(1) combo.add(1) List lt int gt playerCombo new List lt int gt () playerCombo.add(1) playerCombo.add(1) playerCombo.add(1) if(combo playerCombo) found true The thing is that seems that does not work, always throws false, any ideas? Update already answered here https stackoverflow.com questions 3669970 compare two listt objects for equality ignoring order
0
Controlling a balance wheel using a Unity script I am working on a small demonstration project with Unity like this (screenshot from footage below). I don't want to use Unity physics, which is too heavy. I plan to create a rotation function with ratio params for gears. But I am not sure how to control the balance wheel rotation like that video, I tried animation tools which is hard to make the acceleration like real physics.
0
Batching a bunch of gameObjects that change their color So I have a bunch of cubes instantiated. Each time the player hits one of these cubes (which is quite often) they change their color to match that of the player. What would be a performant way to do this? So far i am doing this on OnTriggerEnter then grab my player s mesh renderer, get its material and get the color. This is quite an expensive process. I was wondering if there is any better way. The cubes do not move by the way, so if they can somehow be batched as well that would be a plus! Also, the player s color is random.
0
Where does Unity save the editor window layouts? In every project there are the CurrentLayout.dwlt and CurrentMaximizeLayout.dwlt files, but those, as the name implies, are just the current layouts. I've been unable to find the general files where it saves all your layouts, in order to copy it to another computer. Where is it?
0
Shader that render canvas before any object I have a canvas (in world space 3d) which is not showing to camera due to this shader which is applied to another (sphere) object. Shader "Custom TextureHolderCustom" Properties MainTex ("Albedo (RGB)", 2D) "white" Mask ("Mask Texture", 2D) "white" SubShader Tags "Queue" "Transparent" Cull Off Lighting On Zwrite On Blend SrcAlpha OneMinusSrcAlpha Pass SetTexture Mask combine texture SetTexture MainTex combine texture,previous FallBack "Diffuse" sphere object where my above shader is attached showing first but my canvas is not showing. I want to show the canvas first. I think i attach above shader to my canvas but it is not possible to apply m I am zero in shader programming
0
Unity2D Rendering multiple sprites as a single one I'm creating NPCs in Unity 2D using C , and I have 16x16 sprites for body, helmet, clothes and weapon. All these have a tile set which has been split in unity. I'd like to be able to render one of each part together, so I can drag the sprite to the field, and then it will be rendered on the NPC. IE, I drag a helmet sprite into the helmet field and that is the rendered helmet. I intend on having multiple NPCs, so I'd prefer to minimise the child objects. Multiple sprites will need rendering, however there's only one sprite renderer. Is it possible for me to combine the sprites (in code), and then render the final sprite? Or is there perhaps a better way? Thanks in advance!
0
Imported model from Blender stops updating after applying scripts I am new to Unity3D and I am trying to import a model from Blender. I save the .blend file inside the assets folder and everything works well. I drag and drop my model and apply textures, colliders and insert a player. Up until that point, I am able to change things in Blender, and see the changes inside Unity. But my problem begins when I try to apply scripts in my objects. Then the connection between Blender and Unity breaks and the model is not updated in the later. What am I doing wrong? Any help would be much appreciated!! Thanks!!
0
How to model walkable houses for Unity I created a house in blender which is a big cube with the upper face intended and pulled down back to the ground. The floors are other boxes and windows and doors are cut out using a boolean modifier. The problem is that the character controller from the Unity standard assets seems to get stuck between the floors and the walls. I have seen that counter strike maps are mostly not made out of cubes but a lot of planes put together. Is that the proper way to model walkable buildings?
0
How to change material color (LWRP) I've upgraded my project to LWRP, I've changed my materials to LWRP lit. But in one of the gamemodes i need to change one my materials' color by script. I used to do it simply like wallMat.color Color.red, but at LWRP that code doesn't work, how to fix it? Edit LWRP Light Weight Render Pipeline
0
Issue With setting Mesh.triangles in Unity Script I have been having an issue in making floating islands. For this i have created an array filled with the position data for both the top and bottom half of the island. Everything works fine when i only have the top half of the triangles implimented, but when i add the bottom half of the triangles become triangles that are shifted to the top half of the island. To be more precise, the traingle index data seems to change while writing it to mesh.triangles. This happens after mesh.triangles triangles in the following code mesh.Clear() transform.position new Vector3( width 2,0 scale, height 2 scale) positionsAll new Vector3 2 width height setupHeightMap() int triangles getTriangles() mesh.vertices positionsAll mesh.triangles triangles mesh.RecalculateNormals() An example watch can be seen here, witth the first four showing the change in index, and the final four showing how the point is the same point but on the above surface. triangles 0 30785 System.Int32 triangles 4 96322 System.Int32 mesh.triangles 0 30785 System.Int32 mesh.triangles 4 30786 System.Int32 mesh.vertices triangles 0 "(65.0, 0.0, 120.0)" UnityEngine.Vector3 mesh.vertices triangles 4 "(66.0, 0.2, 120.0)" UnityEngine.Vector3 mesh.vertices mesh.triangles 0 "(65.0, 0.0, 120.0)" UnityEngine.Vector3 mesh.vertices mesh.triangles 4 "(66.0, 0.2, 120.0)" UnityEngine.Vector3 This watch data was generated in an instance where all triangles that had positive values were not instanciated, but the same problem hapens if all Triangles are instanciated. If anyone can tell me why this happens and or how i can fix this problem that would be extremly helpful. thank you!
0
How can I create a title screen demo? I am writing a 2D game in Unity and I want to offer an old school style title screen demo (such as in Super Mario, etc.) where it shows a brief run through of either one or various levels. How would I accomplish this? If anyone can either enlighten me or point me to some further reading then it would be very welcome.
0
What revenue cuts will I take by using Unity combined with Facebook's platform? Basically me and a friend want to develop a Facebook game by using Unity. What I wanted to know is if we do earn any money on it, how would we be required to use the profits of said money? I remember reading that Unity requires you to pay royalty (or something like that) after having earned a certain amount of money from your product. What confuses me is where Facebook would enter the equation? I can't seem to find any sources on royalty on such from FB based games. Does anyone have any sources covering FB games made in Unity on how it all comes together?
0
How to set the camera projectionmatrix so that it's 4 rays always exactly hit the corners of a defined plane? I have a camera, and I have a plane. The plane has 4 corner points. I need to find out how to change the projection matrix of the camera so that the projection rays of the camera always hit the corners of the plane. The camera and the Plane are supposed to be movable rotateable (if possible) The Plane is also supposed to be scaleable. Usage I am making a Stereo 3D Game with Eyetracking where my 2 Eye Vectors hit the exact same paralax plane. That paralax plane is defined. So we have the Corner positions of the Plane.
0
Chartboost Adds are not showing up in android I am testing chartboost example but no adds are being shown up. I have added app ID and signature. and Even test mode is enabled still its not showing up. I am using chartboost SDK Provided by chartboost, also I am getting this warning CHARTBOOST You are using a Chartboost example App ID or App Signature! Go to the Chartboost dashboard and replace these with an App ID amp App Signature from your account! Though I have added correct ID and Singnature. Note Adds are showing up if I build for iOS. I have added app in dashboard for both iOS and android.
0
Is there a reason not to delete the System.Collections namespace in Unity3D? I find various scripts on tutorials, books and even on the community wiki using the System.collections namespace without ever actually using it. Is this an obscure Unity3D requirement, or are the authors using the default script template and forget don't bother deleting the import?
0
Disadvantages of using a singular scene in Unity In my previous experience with Unity, I have had an organized level structure where each level instance was easily separated into a different scene. For my current project, it would be much more natural to avoid such transitions, and instead disable or remove GameObject instances far from the player's position, and of course loading them in when necessary. It strikes me that this must be how titles like Gone Home amp Firewatch must have been made, and while my game won't be huge in scope, it will be bigger than those ("distance" wise). Basically, I don't want to get halfway down this road and realize I've made a terrible mistake, so any input is appreciated. Are there disadvantages to using a singular scene in Unity?
0
How to place an instance of Editor Window in screen center? I want to create an instance of Editor Window by using CreateInstance or GetWindow. And I want to place it in center of the screen (or center of Unity). I didn't find any methods in Unity Engine that could help me. Do they exist? How can I do it within the script? Note I mean how can I find out what is the user's screen resolution? Which method can give me that? P.S. Screen.width Screen.height is not what I need. Because it refers to the Game View's window, not Unity.exe Editor's size and not monitor Screen
0
How to find an object which is added to a scene only when game starts? I'm looking for some advice how to find an object which is added to scene only when the game starts? Before start it isn't in Scene hierarchy. It's prefab.
0
Help for structuring classes I am creating a platformer game with some card base fighting. I was thinking about how should I structure my classes? There are 2 types of cards i.e. Continuous effect and 1 time effect. Also, they can be divide into 3 other categories i.e. Environment cards, enemy cards and player cards. Please help me to get started with structuring it. For more details, I want structure to be reusable as well as organized. Enemies and player both can interact with these cards and at some points. Thank you
0
Comparing performance I wanted to create a portal. This portal looks like a semi transparent texture rotating on a cylinder At first I created such a portal using a Particle System. Then I realized that this might be an overkill and built another portal the following way I put a cylinder in the scene, put the texture on it and added a script that would rotate the cylinder. The visual result of the 2 approaches (Particle System vs. Mesh approach) is perfectly the same. Now I wanted to test which one performs better. Am I right to assume that I should write a script which creates 10.000 portals of type A or B in the scene and have a look at some statistics (not sure yet which where to find them), or is there anything more convinient to test performance? Thank you!
0
How to model muscle contraction force acting on two bones connected by joint in Unity PhysX? I'm trying to understand what is a correct way to model a muscle contraction in a physics engine like PhysX (Unity3D). Muscle that I'm modelling is connected to a bones in 2 points A and B. Having a total force for the muscle fTotal, I'm trying to apply two forces in points A and B on corresponding bones, where magnitude of each force is a half of the total force. And of course force vectors are lying on the same AB line and pointing to the opposite directions towards the center of the muscle. fTotal fA fB One thing that bothers me is a situation when one bone is fixed in space. Intuitively, all contraction force should be applied only to a single attachment point, however, my model will apply only 1 2 of a force. Can you suggest a better way to implement this?
0
Finding Endpoint of line in Unity I have a startpoint, magnitude(length) and direction and want to find endpoint to construct the line here is the code to make question more clear private Vector2 GetEndPoint(Vector2 startPoint, Vector2 direction, float magnitude) Vector2 endPoint some stfuff with parameters return endPoint And this is the visualization of what I want Hope I am clear enough, any suggestions is welcomed
0
Unassigned reference exception when proceeding from scene to scene So, I have built a script in unity in c called parralax. It basically parallaxes two backgrounds and looks like this using System.Collections using System.Collections.Generic using UnityEngine public class Parralax MonoBehaviour public float startPos public GameObject cam public float parallaxEffect public float length public GameObject player public float playerStartPos public float maxDisplacement void Start () maxDisplacement 0f playerStartPos player.transform.position.x startPos transform.position.x cam GameObject.Find ("Main Camera") length GetComponent lt SpriteRenderer gt ().bounds.size.x void Update () float dist cam.transform.position.x parallaxEffect transform.position new Vector2 (startPos dist, transform.position.y) If I put it in respective background and assign a value to it, it works fine and runs smoothly. But, if I play the game scene wise i.e. 1st scene to 2nd scene to 3rd scene it crashes and says Unassigned reference exception You need to set variable cam in inspector Even though, it runs on the same scene, it doesn't run after I play it scene wise. Please help!
0
Why do I get errors cs1502 and cs1503 in my Destroy object script? I have a script that lets the player place blocks (like in Minecraft), but I also want to be able to destroy those blocks. I keep getting error messages cs1502 and cs1503. Could anyone take a look at the script and tell me what is wrong? using UnityEngine using System.Collections public class TestForCube MonoBehaviour Ray ray RaycastHit hit Use this for initialization void Start () Update is called once per frame void Update () ray Camera.main.ScreenPointToRay (Input.mousePosition) if (Physics.Raycast (ray, out hit)) if (Input.GetKeyDown (KeyCode.Mouse0)) Vector3 position hit.transform.position hit.normal Quaternion rotation Quaternion.FromToRotation( Vector3.up , hit.normal ) GameObject Placement GameObject.CreatePrimitive( PrimitiveType.Cube ) Placement.transform.position position Placement.transform.rotation rotation if (Physics.Raycast (ray, out hit)) if (Input.GetKeyDown (KeyCode.Mouse1)) DestroyObject( PrimitiveType.Cube)
0
Getting notified about a change of a public variable in a script I have a script attached to a GameObject. In this script I have the variable public int Rotation If this value is changed, I need to do some calculations. I know that I can be notified when this value is changed in the Inspector (for example if somebody enters a different number), but I would like to be notified if this value is changed by another script. Is that possible, or do I need do introduce a void ChangeRotation(int uNewValue) or similiar? Thank you!
0
Help with Chase AI? (Similar to Blue Demon) all! I'm working on a chase ai follow player script, for a 2D project of mine, I'm going for something similar to Blue Demon where an integer value controls what enemy is on screen, and can be changed for individual instances, and it follows the players animations and directions closely, and when you make contact with the enemy, you are defeated game over. Anyways, I've got some code 'somewhat' working, i have an enumeration that controls the state machine of the animator, however, The Update loop is the real problem here, as of right now Update is called once per frame void Update () bool isMoving anim.GetBool( quot isMoving quot ) if (EnemyID 0) transform.position Vector3.MoveTowards(self.position, player.position, speed Time.deltaTime) if(Vector3.Distance(target.position, transform.position) lt maxRange amp amp Vector3.Distance(target.position, transform.position) gt minRange) anim.SetBool( quot isMoving quot , true) transform.position Vector3.MoveTowards(transform.position, target.transform.position, speed Time.deltaTime) Enter State MovingState() else IdleState() Instead of the object following the player, it starts to run away when the player gets near? or when the player goes to a corner, it moves diagonally? It never seems to actually follow the player consistently. Suggestions and constructive criticism are greatly appreciated, thanks in advance! Edit Animator anim bool caught public Animator player public Transform target SerializeField float speed 5f SerializeField float maxRange SerializeField float minRange public int EnemyID State state The EnemyID as of now isn't necessarily set to a specific value (i.e, it is set to 0) When it is equal to that number, the Update loop is supposed to have the object follow the player at a specific speed and range, during this time, the anim reference is setting the animator boolean parameter 'isMoving' to true starting the walking animation. If the enemy object stops moving, it should enter its idle state. IEnumerator IdleState() yield return new WaitForEndOfFrame() anim.Play( quot Idle quot ) IEnumerator MovingState() yield return new WaitForEndOfFrame() anim.Play( quot Move quot ) Currently the idle state is not working, but this is alright.
0
How can I get a raycast to hit navmesh only? In Unity, I'm trying to get the raycast to hit the navmesh only, but I cannot find an option to place navmesh on a specific layer. Is there a way to raycast to the navmesh itself?
0
Unity prefab functionality without files? Task Display a UI list Assumptions Most UI parts only get their data during runtime UI parts need to be styled in the editor ( before runtime) UI editing should be done with real time preview in the editor The items in UI list should look the same Current solution Save a list item prototype as a prefab (drag amp drop in the editor) Set that prefab as the reference in the script managing the list During runtime, instantiate the referenced prefab as needed However, this needs a prefab file, which seems like an unnecessary additional point of failure. Just one annoying example More often than not I forget to click "Apply" after editing such a prototype which only becomes apparent at runtime. Suggested solution In the script managing the list, set the list item prototype as a reference On Awake(), create a prefab and store it in a class field During runtime, instantiate the prefab from the class field Question I got the suggested solution working withPrefabUtility.CreatePrefab(). The only issue with that is that it still saves a prefab file. I currently just save those to a temp directory, but that is a workaround. Is it possible to have a prefab which does not exist as a file, but still allows copying with Instantiate()?
0
How Lots of ComputeBuffers at Once Affect Performance Unity How will lots ComputeBuffer instances affect performance? And why? I know that I should call ComputeBuffer.Release() on every ComputeBuffer I create, but will it affect performance if I were to have lots of open ComputeBuffers at once? and by "lots" I mean hundreds to thousands. It of course goes without saying that all of those ComputeBuffers will be released at some point, possibly at the same time.
0
How can I implement UI in Unity using Chromium? I'm looking for an alternative to UI Builder. Ideally I'd like to have basically a Chromium instance atop Unity3D which would have its JS calls somehow land in the C (maybe in the quot Update quot loop it listens to a constant stream of potential calls and the parameters will correspond to function names in my Unity code, I don't know) here's what I found which doesn't quite live up to my expectations Unity WebView doesn't support Windows. 3D WebView for Windows and macOS (Web Browser) requires the UI to be served on an actual live URL and for Unity to access it via that URL and for all interaction to be handled via API, impractical or slow at best. PowerUI HTML CSS is interesting, but was made in 2011. The documentation is all gone. the support for css feature is probably incredibly slim. Embedded Browser looks pretty good, but I'm unsure that it could be bent into a UI system. I want it to frame my game, not to cover it. Coherent Gameface looks probably the best, although the CSS implementation seems a tad lackluster. Also this project was started in 2012, it's probably carrying very old, very slow code. This Unity forum thread may be relevant. Chromium Embedded Framework was a tool used by some assets on the asset store to create chromium UI but it has been removed. If not using these assets, how can I implement my idea of using Chromium as my UI layer?
0
LookRotation() make X axis face the target instead of Z I use LookRotation() in order for an object to look at another, but since I'm using 2D I would like to make the axis looking facing the target to be X instead of Z. I have the code below currently Vector3 dif targetPos obj.position Quaternion angle Quaternion.LookRotation(dif, obj.up) obj.rotation Quaternion.Lerp(obj.localRotation, angle, Time.deltaTime) Now What I'm trying to achieve Thanks!
0
Bullet Projectile Verticle Rotation I'm very new to C and Unity, and have been working on a projectile based weapon, and for the most part it's been working well. However, although the bullet fires facing the direction it's being shot horizontally, when shot up or down, the bullet is still parallel to the ground when shot. Any help would be appreciated, thanks! using System.Collections using System.Collections.Generic using UnityEngine public class PlayerWeapon MonoBehaviour public GameObject bulletPrefab public Transform BulletSpawn public float bulletSpeed 30 public float lifeTime 3 Start is called before the first frame update void Start() Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.Mouse0)) Fire() private void Fire() GameObject bullet Instantiate(bulletPrefab) Physics.IgnoreCollision(bullet.GetComponent lt Collider gt (), BulletSpawn.parent.GetComponent lt Collider gt ()) bullet.transform.position BulletSpawn.position Vector3 rotation bullet.transform.rotation.eulerAngles bullet.transform.rotation Quaternion.Euler(rotation.x, transform.eulerAngles.y, rotation.z) bullet.GetComponent lt Rigidbody gt ().AddForce(BulletSpawn.forward bulletSpeed, ForceMode.Impulse) StartCoroutine(DestroyBulletAfterTime(bullet, lifeTime)) private IEnumerator DestroyBulletAfterTime(GameObject bullet, float delay) yield return new WaitForSeconds(delay) Destroy(bullet)
0
Issue with Button component When I add a Button component, it looks like this Normally, it should look like this How can I fix this issue?
0
Code for making Material offset follow Bone transform not exactly working In my game, I have an Eye Bone that is constantly moving. I'm trying to make a material attached to the eye (pupil material) move in relation to the Eye bone's transform. This Script is indeed moving the Material's offset, but it is seemingly ignoring the offsetMultiplier bit. For instance, if I set offsetMultiplier to 0, the material offset never equals 0 but instead keeps exactly following the Bone transform numbers. What might be the mistake here? using System.Collections using System.Collections.Generic using UnityEngine public class EyeBoneMatOffset MonoBehaviour public Transform targetBone public Material mat public float offsetMultiplier 0.0f 0 for testing purposes Start is called before the first frame update void Start() Update is called once per frame void Update() Create a vector to offset the material var offset new Vector2(targetBone.transform.localRotation.eulerAngles.x offsetMultiplier, targetBone.transform.localRotation.eulerAngles.y offsetMultiplier) Apply the offset mat.mainTextureOffset offset Script inspector set up Edit I'm having issues getting the Eye(Pupil) Material to correctly move with the Eye bone movement. You can see that when I hit play, the script does get the Eye Material to Initially move, but then it is (visually) frozen instead of moving back and forth. The goal is for it to correctly Eye Track the cube. As a sidenote, for the Eye Material's X and Y offset, the visually correct range of its pupil movement is 0.45 to 0.45 (X), and 0.45 to 0.45 (Y). So it's weird to me that the X and Y offset of the Eye Materials are shown to be moving within that range (which should be good!), yet are not actually moving visually except for when the game first starts.
0
Best way to save game data in Unity I am currently developing a game in unity and I want to add some sort of saving system that saves the following Locked unlocked level. The amount of money the player has. Items perks that the player has. As you can see, the data I want to save is global, and has nothing to do with any specific scene. How would you reccomend save this kind of data? I have heard about the EasySave asset but I don't know if it is the right choice it is pretty expensive and I belive that there has to be some easier, cheaper (even free) way to save the data. I'll appreciate any answer or consideration.
0
Keeping over shoulder camera view consistent at different screen resolutions I have a player GameObject. There is a character attached to it and a camera (both are children of the player GameObject). The over shoulder camera is positioned nicely. The player should appear on the left edge of the screen. Now when I change the viewport screen size and make it larger, the camera doesn't keep it's view. I can see in the Inspector that the camera's view changes. I don't understand in which way it does that. What would I need to do to keep the player always on the left edge, no matter what the screen resolution is? Thank you. The upper image shows how I have planned developed the camera view. This is what the camera view should look like. The lower image shows how the camera changes at larger viewport.
0
Can not play a disabled audio source? I have 5 cubes and all 5 cubes have an audiosource. When my player jumps into those cubes, the audiosource is playing just once. It was working. But then, I decided to re organize my hierarchy and audiosource didn t work well. When I jump to first cube, the audio plays but then if I try to jump to the other cubes, the audio does not play. I have a prefab cube and all 5 cubes are the created from that prefab. It gives Can not play a disabled audio source and I don t know why? I haven t changed about coding part. This is my first cube component The other 4 cubes (actually they all the same as with the first cube) Coding Part E er karakter ses efekti tamamlanmadan di er paddle'a atlarsa paddle ses karm yor. Bunu d zelt SerializeField AudioSource clickSound bool landedorNot false void Start() private void OnCollisionEnter(Collision collision) if (collision.gameObject.name quot Ship New Pos quot amp amp landedorNot false ) landedorNot true if (!clickSound.isPlaying) clickSound.Play() this is where the error occurs according to Unity
0
Why does the debug say my assigned field "is never assigned to, and will always have its default value 'null'"? I have an itemData class that stores the data for a couple of items. It looks something like this public class ItemData MonoBehaviour public List lt Item gt items SerializeField private Sprite itemOneSprite, itemTwoSprite, itemThreeSprite void Awake() items new List lt Item gt () Item itemOne new Item(0, "Item 1", itemOneSprite) items.Add(itemOne) Item itemTwo new Item(1, "Item 2", itemTwoSprite) items.Add(itemTwo) Item itemThree new Item(2, "Item 3", itemThreeSprite) items.Add(itemThree) I get an error message for itemTwoSprite and itemThreeSprite, stating that they are null and will always be null Field name of field is never assigned to, and will always have its default value 'null' Oddly, when I check the inspector, those fields are not null. I have manually attached sprites to them. When I debug, I see that they are not null. I get something like "itemTwoSprite(UnityEngine.Sprite)". I can run the game, and things seem to work normally. The order of the declared Sprite variables seems to be important, as well. For instance, if my line of code looked like Sprite itemTwoSprite, itemOneSprite, itemThreeSprite, then itemOneSprite and itemThreeSprite would bring up error messages. The first one declared seems to be unproblematic. What could be causing the issue, and how do I fix it? I have isolated the problem into an empty project, and it still persists. The only other script is the item class. To reiterate, the error message does not prevent the game from running, but it pops up in the console from time to time, with the yellow exclamation mark.
0
How to generate a "loop room" in a platformer game (by Unity)? I want to build a level with a room whose left edge is linked to right edge in a 2D platformer game in Unity. My goal is let all objects disappear in one side will appear in other side of the room. Just like this Both sides should have collision with other objects. Right now I'm doing this by cloning objects on the other side, but it is too complicated. Is there any other good way to solve this?
0
Spawning a customized sprite with text I'm making a game where I have circles filed with words or pictures drop from the top of the screen to the bottom. they should spawn right above and then drop. I just started using unity a couple days ago and I managed to do this with a simple sprite, but I couldn't fill it with the info I wanted and from searching online it seems like it can't be done. So I decided to try with buttons instead, since those can be given text and images(I think) but i'm not sure how to do so. with the circles I passed an object of them to the script and then used newCircle Instantiate(Circle, temp, Quaternion.identity) but with buttons everything seems to work weird because there's also the need for the canvas and the units are different so I'm not sure how to do it
0
Performance of separate Animators vs single multilayer Animator I am making a 2D game with Unity 5.4 and I want to animate my 2D human character. He has different sprites for its body parts leg(s), hand(s), head, eye(s), nose, mouth. Its eyes, hands, legs move independently from each other meaning their animations and transitions are not related in any way. My question is, which alternative is the better choice performance wise when animating? For legs, hands, eyes, etc. create separate Animator and animate them separately. For all animations use single Animator (attached on body's "container" GameObject) and create for legs hands eyes different Layers in the Animator.
0
How to fix problems with connecting VsCode to Omnisharp server? I'm using sourcetree for version controlling for Unity. I'm using VsCode version 1.45.1 and when sourctree is running on pc and I open a script on my Unity project, VsCode can't connect to Omnisharp server. What's the problem? I've recently installed Git on my pc.
0
How to get light level (brightness) of a particular location? I'm making a 2D top down survival game similar to Rimworld, I'm trying to emulate a day night system. Many features depend on whether any tile is light (or dark) enough, based on time of day or other light sources such as torches, so I'm wondering if there's an easy way to detect how much light there is on a certain tile without making a whole system that tracks light on a per tile level (or maybe the latter option is better)? I am using Unity 2020.3.6f1 and the URP, which means I'm going to be using the 'new' 2D lights. EXAMPLE When it's nighttime, I'm going to disable the global light (sun) so those tiles will be pitch black. When it's daytime, the global light will have an intensity of 1 so that tile will have 100 brightness (look normal). When it's nighttime, but there's a torch, the tile where the torch is sitting on will have 100 brightness, and that will slowly fade to 0 over a span of 5 tiles. Making a system that updates every single tile in the game with information about the light level seems pretty expensive. Is there a way we can observe a block quot graphically quot , or in other words, literally look at the pixel on the screen, and determine it's alpha value to check for light level? Any suggestion is super welcome. EDIT Every tile does not need to know its brightness every frame, but they do need to know it less often. Some examples are A plant checking every couple of frames to see if it can grow A character checking every couple of frames to see if he's in the dark (and if he is, he needs to start panicking) More importantly, I need my characters to make decisions based on light amount. For an example, if there is a job that needs to be done at a certain location, a character should first check the light level of that location before going to do it.
0
How can I randomly generate objects inside of a Complex Area? In my game, I want to generate randomize enemies inside of this green area that I made with a custom editor tool.
0
Pong tutorial Unity Logic question I've been following this Pong tutorial, which is great https noobtuts.com unity 2d pong game. The C , unity components etc I understand. But what I am having trouble with is understanding the logic of how it reverses the direction of the ball depending on where it hits. I know that what it is doing is condensing a new Y value to 1, 0, 1, via the hitFactor function, which returns that value and then sets that to the new Y (so going up or down) based on the relative ball position to the paddle, divided by the height size of the paddle. But that's the bit I don't really truly understand, how does that work and why? I have been using Debug.log to send all the different parts of it to try and understand, as well as visually looking in Unity and trying to figure it out from there via the inspector, but I'm just having a mental block. To me I can vaguely see how this code is finding a relative position and then dividing by the height of the paddle to somehow condense it to this range but I'm really just stuck on it in my head.(the hitfactor function itself is basically where I am stuck) Here's the function float hitFactor(Vector2 ballPos, Vector2 racketPos, float racketHeight) ascii art 1 lt at the top of the racket 0 lt at the middle of the racket 1 lt at the bottom of the racket return (ballPos.y racketPos.y) racketHeight And in context with the collision if (col.gameObject.name "RacketLeft") Calculate hit Factor float y hitFactor(transform.position, col.transform.position, col.collider.bounds.size.y) Calculate direction, make length 1 via .normalized Vector2 dir new Vector2(1, y).normalized Set Velocity with dir speed GetComponent lt Rigidbody2D gt ().velocity dir speed I'm sure this is a very basic thing, but I am struggling with this type of thing. I am on Khan academy, starting from very basic stuff and working my way up, so no doubt maybe when I get to vectors I might understand this more, but I'd like to try and really get my head around this particular issue. Sorry for the very basic question, I have been dabbling in C and Unity for a while, but I have realised my weakness is really in the basic core logic of some things....I am a composer by day but I really enjoy trying to get back into this side of my brain, I guess it's super dusty in there hahaha. Thanks so much in advance for any help, I truly appreciate it.
0
Camera looking around with mouse Unity, C I am building a script in C for camera logic in Unity, the camera is supposed to follow the player (a 3rd person character) around and the user should be able to look around using the mouse, so far everything works fine (the following logic and looking around on the horizontal axis) the problem is I can't get the camera to move along the vertical axis, left and right are fine but up and down are not working. This is the C script public class PlayerFollow MonoBehaviour public Transform PlayerTransform private Vector3 cameraOffset Range(0.01f, 1.0f) public float SmoothFactor 0.5f public bool LookAtPlayer false public bool RotateAroundPlayer true public bool RotateMiddleMouseButton true public float RotationsSpeed 5.0f public float CameraPitchMin 1.5f public float CameraPitchMax 6.5f Use this for initialization void Start() cameraOffset transform.position PlayerTransform.position private bool IsRotateActive get if (!RotateAroundPlayer) return false if (!RotateMiddleMouseButton) return true if (RotateMiddleMouseButton amp amp Input.GetMouseButton(2)) return true return false LateUpdate is called after Update methods void LateUpdate() if (IsRotateActive) float h Input.GetAxis("Mouse X") RotationsSpeed float v Input.GetAxis("Mouse Y") RotationsSpeed Quaternion camTurnAngle Quaternion.AngleAxis(h, Vector3.up) Quaternion camTurnAngleY Quaternion.AngleAxis(v, Vector3.up) Vector3 newCameraOffset camTurnAngle camTurnAngleY cameraOffset Limit camera pitch if (newCameraOffset.y lt CameraPitchMin newCameraOffset.y gt CameraPitchMax) newCameraOffset camTurnAngle cameraOffset cameraOffset newCameraOffset Vector3 newPos PlayerTransform.position cameraOffset transform.position Vector3.Slerp(transform.position, newPos, SmoothFactor) if (LookAtPlayer RotateAroundPlayer) transform.LookAt(PlayerTransform)
0
Is there a difference in the time taken to load one texture instead of many? Is there a difference in the loading time of 16 256 256 textures versus a single 1024 1024 texture? Specifically for level loading time?
0
How to leave a permanent skidmark on the ground in unity2d I am working on a 2D driving game.I have a sprite of a car.Set the car movement.Now I need to create a skid mark on the ground for that I have created a empte game object and added Trial Renderer component and set the skid mark material to it.The problem is that when i start moving the car ,the skid mark follows the car as if that a skid mark is attached to the car. Is there any simple way to leave a permanent skid mark on the ground in unity2d. Can anybody please help me
0
How to avoid assigning the same GameObject individually for every prefab? In many times, prefabs that share the same script may require the same GameObject in the script. For example, in my game I want to make a series of card prefabs. Each card has their own image when shown, but has the same back image when hidden. My script for card is public class DraggingCard DragAndDropItem public Sprite secretSprite This is the same for every card Sprite oringinalSprite This is individual for every card Image image public void Awake() image GetComponent lt Image gt () oringinalSprite image.sprite public void Activate() image.sprite oringinalSprite public void Hide() image.sprite secretSprite But if I write this, I'll have to assign the secretSprite in the inspector for every DraggingCard prefab. I tried to set secretPrefab to be static or const but neither worked. I believe there must be a clever way to avoid the repeat work. Could anyone tell me that? Thank you!
0
Making an object hang This image is pretty self explanatory I hope How can I achieve this effect without animating it? I want to avoid animations as there are many objects hanging and I dont want them to move the exact same way.
0
how does collaboration in unity work? i've been working on a 2d game for a bit now, almost all assets made but when ive tried to collaborate everything was quite glitched out, edits weren't saved, nothing was working at all. im not sure quite what the problem was because we were both on the latest version. maybe i got to something wrong, or did something wrong im not sure. this was a few months ago now and ive been busy but i want to come back to this project. should i start over?
0
Issue with dark .PNG files in Unity I made sprite assets in Krita and I exported them as .PNG files. When I import the files into Unity assets, however, they become a lot darker than the original colors. So far, I haven't found the issue, and I was wondering what's going on?