_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
File operation(s) failure on game crash kill by OS User in Android My game saves its state after fixed interval on a file in game app internal storage. When my game is killed or crashed by user or OS respectively, We write current game state on that file. File writing after fix interval is working fine but when game is crashed killed by OS or user, file writing operation fails. Operation failure results incomplete game state or empty game state i.e. no data written on file at all. I have tried multiple solutions using android service, In case the service is NON STICKY service is killed with the app. On the other hand if service is STICKY then it is restarted but intent that was attached initially with service is null or new one. The question is that how can i save my data (could be 2 3MB) completely on file in internal storage when my game app is killed by user OS ?
|
0 |
Getting mousemovement despite mouselock unity I have lockcursor so the cursor doesn't leave the screen, but now i have to rotate an object based on mouse movement (think garrys mod item rotation) but the mouse cursor is obviusly locked to the center, is there anyway of getting the input from the mouse? public void GetRotated() Debug.Log(Input.GetAxis("Mouse X").ToString() ", " Input.GetAxis("Mouse Y").ToString()) gameObject.transform.localRotation new Quaternion(Input.GetAxis("Mouse X") RotationSpeed Time.deltaTime, Input.GetAxis("Mouse Y") RotationSpeed Time.deltaTime, 0, 0)
|
0 |
Unity Easier way to resize group of buttons to the same size I have a canvas with buttons, with a script attached to each button. This script creates an array for buttons and resizes every button to the same size as the longest one in that array (the button with the longest line of text in it). Everything works, but I was wondering is there is an easier, more automatic way for this instead of having to drag every button in every array in the Inspector tab? Any ideas would be greatly appreciated UnityPackage https transfer.sh 6BCDG buttonwidth.unitypackage public Image otherbutton void Start () for(int i 0 i lt otherbutton.Length i ) if (otherbutton i .rectTransform.sizeDelta.x gt gameObject.GetComponent lt Image gt ().rectTransform.sizeDelta.x) gameObject.GetComponent lt ContentSizeFitter gt ().enabled false gameObject.GetComponent lt Image gt ().rectTransform.sizeDelta new Vector2( otherbutton i .rectTransform.sizeDelta.x, otherbutton i .rectTransform.sizeDelta.y)
|
0 |
Rendering a distant star field in Unity using a separate camera for near stars I'm currently working on a hobby project which is a universe simulator (exclusive to stars) built in unity3D. In order to deal with the raw scale of the universe I'm trying to implement two co ordinate systems. In my project I have two cameras camera1 is the first co ordinate system where all stars are loaded as high detail 3D objects. While camera2 is used for gathering a list of points within this "extended" frustum. I want to display these stars from camera2 on the farplane of camera1 in a lowdetail 2d manner. I'm new to game development so this may be completely wrong my plan was to generate a mesh from all the points in cameras2 frustum (this mesh now respresents my points in world space). I have a variable that represents the conversionFactor between the two co ordinate systems. I will convert this mesh into projection view using the my conversionFactor in the translation component. I will display this projection view on my camera1 farplane selling the illusion of far away stars? Please let me know the flaws in my deisgn! any help is much appreciated
|
0 |
Calcluate Mesh top, bottom, left and right position relative to mouse click position on the mesh I have a mesh (suppose it can be circle, or rectangular,square or an arc). The geometry of the mesh can be anything. I can click on mesh at any position. From relative to the clicked position, I want to get its right, left top and bottom position of the mesh. Maybe the picture explain it better then my words Update I tried to apply a quick dirty solution. It is incomplete Update is called once per frame void Update() if (Input.GetMouseButtonDown(0)) Ray r Ray(Input.mousePosition) RaycastHit rayHit Ray r Camera.main.ScreenPointToRay(Input.mousePosition) if(Physics.Raycast(r,out rayHit,1000)) Debug.Log(rayHit.transform.name) Debug.Log(rayHit.point) Debug.Log(rayHit.normal) StartCoroutine(MoveToDirection(rayHit.point)) IEnumerator MoveToDirection(Vector3 startPosition) GameObject go GameObject.CreatePrimitive(PrimitiveType.Cube) go.transform.position startPosition while (true) go.transform.position go.transform.position go.transform.up Time.deltaTime speed yield return new WaitForEndOfFrame() On click i instantiated a gameobject and start moving in upward direction and when it leaves the mesh bounds i will get the position but it have differet problems, like 1. It will not work with arc object or maybe with non rectangular geomerty. 2. I have to apply onTrigger and onExitEvent that can be skip when the cube move with fast pace.
|
0 |
How can I extend the FindObjectsByTag to filter multiple parents of the found objects? private List lt GameObject gt FindDoors(string parents) GameObject doorsLeft GameObject.FindGameObjectsWithTag(c doorLeft) GameObject doorsRight GameObject.FindGameObjectsWithTag(c doorRight) List lt GameObject gt allDoors doorsLeft.Union(doorsRight).ToList() List lt GameObject gt toRemove new List lt GameObject gt () for (int i 0 i lt allDoors.Count i ) for (int x 0 x lt parents.Length x ) if (allDoors i .transform.parent.name ! parents x ) toRemove.Add(allDoors i ) foreach (var it in toRemove) allDoors.Remove(it) foreach (GameObject door in allDoors) Debug.Log("Door Parent " door.transform.parent) return allDoors Usage var allDoors FindDoors(new string "Wall Door Long 01", "Wall Door Long 02" ) But in the function FindDoors the return allDoors is empty. I think the problem is at this IF if (allDoors i .transform.parent.name ! parents x ) Once it's Wall Door Long 01 so if it's Wall Door Long 01 it will not remove the item but next it's Wall Door Long 02 so now the it's true and will remove the even if the parent name is Wall Door Long 01 and same if it's Wall Door Long 02 And then in the end it will remove all the items. But I want it to remove only doors that the parents of them is not Wall Door Long 01 and not Wall Door Long 02
|
0 |
Making an RTS game how to handle player created units interacting with each other I'm making an RTS game in Unity with C . However, the interaction I'm going to have with player created units interacting with other player created units is what has me stumped. The player and his opponent can purchase units when they have the resources, and it instantiates them in the game. The main thing is checking whether an opponent's unit is within range to attack. Obviously, you can't have every unit asking every other unit what its position is, or it would get exponentially more CPU consuming the more units are built, right? I'm trying to figure out how I'm going to go about this. I figured I could have every unit report its position to a sort of master 'tracker', and then every unit could ask the tracker if any opponents' units have a position within X of their own. How I would actually implement this in Unity, though, I'm not sure about. Moreover, I'm trying to get my head around Instantiated objects. If every unit is telling its position to the master 'tracker', what does it call itself? And let's say a unit asks the tracker if an enemy is in range and one is, what does the tracker tell it so it can locate the right GameObject and attack it? Sorry if I'm talking about it all wrong, I'm sure there's a simple methodology that exists on how to do it, but I can't think of any. Thank you.
|
0 |
How to make a merge animation in Unity? I've seen a merge animation in a mobile game which you can check here https youtu.be G7l24Wtdcxw You can observe the animation when the tiles combine. Can it be done in Unity3d, may be using shaders? Or, do I need to use a 3d app like Blender?
|
0 |
Can you adjust the proportions of a 3D model via scripting? We are developing a game in Unity where the character is different ages in different levels. Would it be possible to use a single 3D model asset, and alter its proportions via scripting to achieve this effect? For example, stretching the head to make it more oval for older self, or increasing head size for toddler self? We don't have a model yet. We are envisaging a simplistic, cartoony look rather than something realistic. Is this doable?
|
0 |
how to detect touch on instantiated prefabs in unity I have instantiated objects (that have collider2D attached) in a grid of 9x13. Now I want to detect a touch on each object individually. I am confused about how to do it. Either write script separately on prefab or do it in my gameController script? Also what is the method to do it? Here is my code for instantiating public GameObject bubble int row int col float x float y void Start () x 2.4f y 2.95f row 13 col 9 Vector2 position new Vector2(x, y) for (int i 0 i lt row i ) for (int j 0 j lt col j ) Instantiate(bubble, position, Quaternion.identity) position.x 0.6f position.x x position.y 0.6f
|
0 |
Unity material has shiny white outline I have two different projects open in Unity. But my grass material appears different in each project, despite all the parameters being the same. See this image On the left is the desired appearance. But on the right my material has a strange white ish outline. How do I get rid of it? I have tried copying the material between the projects, and the problem seems to be independent of the available lighting
|
0 |
Unity Collision detection issue with CharacterController I am making an isometric game (3d scene, using 2d sprites). Currently I am trying to add collision to the enviroment to prevent the player from walking through everything. However no matter what I do the player seems to simply ignore the and walks through the object. Below are some combination I have tried and the results I got. For this instance I am looking at the windmill object NOTE Player has a character controller , no rigidbody. Scenario 1 Windmill has Rigibody IsKinematic false No rotation amp Position constraints Boxcollider isTrigger false result On touching object it start flying around. So collision is there. Scenario 2 Windmill has Rigibody IsKinematic false has rotation amp Position constraints (all axis) Boxcollider isTrigger false result I can walk through the object and somehow the collision is gone. the reason for constraints is so that the object wont move. (its a windmill) Scenario 3 Windmill has Rigibody IsKinematic false both with and without rotation amp Position constraints (all axis) Boxcollider isTrigger true result Debug.Log shows that there is collision Now what I would like to achieve is that the windmill can't be moved yet also can't be moved through.I am willing to programm collision if needed, but i rather do it with the unity provided tools. Any idea what I am overlooking? EDIT 1 Since it was asked how I moved the player, I use the Fingers asset. We make use of the joystick to move the player around. Below is our JoystickExecuted method depicting what exactly I do. private void JoystickExecuted(FingersJoystickScript script, Vector2 amount) if (amount.x gt 0 amp amp ! facingRight) FlipXAxis() else if (amount.x lt 0 amp amp facingRight) if (amount.x gt 0 amp amp ! facingRight) FlipXAxis() else if (amount.x lt 0 amp amp facingRight) FlipXAxis() var pos transform.position pos.x amount.x 8 Time.deltaTime pos.z amount.y 8 Time.deltaTime transform.position pos anim.SetBool("isWalking", true) if (amount Vector2.zero) anim.SetBool("isWalking", false)
|
0 |
In GameCenter realtime multiplayer how to identify who is host? In GameCenter real time multiplayer how to identify who is a host?
|
0 |
How can I continue to rotate a 2D UI Object using OnPointerEnter when object is on its side? (OnPointerExit is triggered) I have been wracking my brain on this for days. I'm trying to create a nice looking hand of cards, when the card is hovered over, it bobs up and down and rotates. This is triggered by OnPointerEnter, however, whenever it turns on its side and out of the mouses path OnPointerExit triggers, I've tried MANY things, including a bool that triggers the hover effect OnPointerEnter but it is just toggled off when it's turned on its side. Is it possible to use the collider on my card with OnPointerEnter? Because that would probably solve my problem but haven't found anything on this. Since the card is on UI, I have some placeholder code in there in order the have the inspected card render on top and return to its place. void Update() if (inspect) transform.localScale cardUpscale posOffset transform.position transform.Rotate(new Vector3(0f, Time.deltaTime degreesPerSecond, 0f), Space.World) Float up down with a Sin() tempPos posOffset tempPos.y Mathf.Sin(Time.fixedTime Mathf.PI frequency) amplitude transform.position tempPos public void OnPointerEnter(PointerEventData eventData) zoomPlaceholder new GameObject() zoomPlaceholder.name "zoomPlaceholder" zoomPlaceholder.transform.SetParent(this.transform.parent) binds the placeholder to the hand zoomPlaceholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex()) LayoutElement cardProxy1 zoomPlaceholder.AddComponent lt LayoutElement gt () cardProxy1.preferredHeight this.GetComponent lt LayoutElement gt ().preferredHeight cardProxy1.preferredWidth this.GetComponent lt LayoutElement gt ().preferredWidth cardProxy1.flexibleHeight 0 cardProxy1.flexibleWidth 0 zoomPosition transform.parent transform.SetParent(transform.parent.parent) inspect true public void OnPointerExit(PointerEventData eventData) inspect false this.transform.SetParent(zoomPosition) this.transform.SetSiblingIndex(zoomPlaceholder.transform.GetSiblingIndex()) transform.localScale cardNormalScale Destroy(zoomPlaceholder)
|
0 |
In Unity how can I know which direction is the screen auto rotated? From the Screen.orientation description I get If the value is set to ScreenOrientation.AutoRotation then the screen will select ... automatically as the device orientation changes. This seems to imply that if the screen does auto rotate, then Screen.orientation has been set to ScreenOrientation.AutoRotation. If that's so, how can I know in which direction it has been auto rotated? Disabling the auto rotation doesn't count (obviously), and I need to distinguish between LandscapeLeft and LandscapeRight, so checking height and width doesn't work either. This should be cross platform, without including any kind of non C plugin. (the answer, given this documentation, seems to be "you can't", but maybe I'm missing something)
|
0 |
How can I use height patches to generate terrain such as what was used to create Abzu? Last year's GDC was pretty inspirational for me and Matt's talk about GiantSquid's landscape creating workflow was the best of all. If you haven't seen it I highly recommend you to check it out. I'm a Unity dev and I'm aware of the fact that Abzu was done with UE and the tools they used in this landscape creation and customizing was custom built. Although I'd eventually like to create similar tools for terrain generation via mashing height patches and enabling different surfaces blending, terrain stamps, and such, the first thing I should ask should be about the level terrain bit. How can I use height patches to generate a terrain (like sand) and then blending them together with something else without extra sculpting (like rock protruding from the sand surface)?
|
0 |
How to add high score? I wanted to add a high score to my game but I don't know how I already tried to find some videos for it but I just can't find the right one. I already have a scoreUI on my game I just wanted to add a high score. Here is my UIManager's script which consists of different functions including the score system. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using UnityEngine.SceneManagement public class uiManager MonoBehaviour public Button buttons public Text scoreText int score bool gameOver Use this for initialization void Start () gameOver false score 0 InvokeRepeating("scoreUpdate", 0.5f, 0.25f) Update is called once per frame void Update () scoreText.text "" score void scoreUpdate() if (gameOver false) score 1 public void gameOverActivated() gameOver true foreach(Button button in buttons) button.gameObject.SetActive(true) public void Play() SceneManager.LoadScene("level1") public void Menu() SceneManager.LoadScene("Menu") public void Retry() SceneManager.LoadScene(SceneManager.GetActiveScene().name) public void Pause() if (Time.timeScale 1) Time.timeScale 0 else if (Time.timeScale 0) Time.timeScale 1 I got the score system from Charger Games. Here is the link to the Video and here is what my game looks like
|
0 |
Animation inside a .obj file? Ok, so yesterday I understood that "rigging (bone and joints)" are things that are use inside a 3D animation software like maya. By that I mean that those bones and joints are not inside the .obj file but only inside the software to help you animate the model. My plan was to create my own voxel model using my own editor, then load it up into maya to animate it and then put it inside Unity to use the animation but from what I understand, its impossible to put multiple frame inside a file to use the pre made animation inside a software like Unity. Does that mean that I will have to load my voxel model inside unity and animate it using the Unity Animation Engine ?
|
0 |
Set up Blob shadow projector My game completely uses baked lighting in URP and because of URP's forward renderer, point and spot lights can't cast realtime shadows on moving characters if I set their types to mixed lighting, and my game mostly takes place indoors, so directional lights wouldn't make sense. So now, I thought I'd use the blob shadow projector from the standard assets pack and it didn't work then I found out that it does not support URP. Does anyone know how I can recreate the blob shadow projector for URP? Or is there another way to create fake shadows for non static characters?
|
0 |
How to synchronize a parent and child position? When watching this video of Unity development, I was following along trying to learn Unity and for the most part understood everything conceptually. Where I got lost was when I tried using some of the same code and setup in Unity. I got the code working fine, but I got in trouble when I tried to implement the parent child behavior seen in the video at around 7 minutes regarding the Enemy objects. The solution described is set up as follows (someone correct me if I didn't understand it properly from the video). Parent Object Contains the script which drives behavior and movement Is located at the origin of the scene (reset the transform in other words) Child Object Contains the graphics renderer which draws the actual sprite or 3D object Is located at the enemy spawn point For me to get this setup working, I had to run the Translate function explicitly against the child object transform.GetChild(0).Translate(dir.normalized distThisTurn) However, in the video, it appears to work just fine with only transform.Translate(dir.normalized distThisTurn) Once he fixes the rotation issue, at about 7 minutes in, this works beautifully, and the enemy travels the path exactly as expected. When I tried this exact same approach, my enemy sprite jumps all over the place. It took me several hours to figure out that I needed to add the .GetChild(0) part. The behavior I saw with the setup from the video is that the invisible parent object moved correctly along the path, and the child went crazy and followed some alternate version of the same path, as if the origin was different or offset, or the path was reflected across some axis. My question is what did I do wrong? Can anyone spot how my setup is different than the one used in the video? Did I miss some detail of how he set up his parent child objects, particularly for the enemies? Or could this be some different behavior due to the version of Unity he is using (I believe mine is newer as I installed it just this week). I think it could also be some small gizmo or feature he neglects to mention that allows you to synchronize the movement of a parent object with its children. The reason for this setup (at least as given in the video) is it allows you to easily swap out the graphics. The scripting is tied to the parent, so all you have to do is exchange the child for one with different graphics and you're done. That part makes sense, I just don't understand why the exact same code he uses did not work for me. I'm talking only about the Enemy object here the creeps that move along the path (it's a tower defense game). I just want to know because I may have to use this extra GetChild call quite a bit, and I feel like it shouldn't be necessary, especially after seeing it work so well in the video. Doing this would also make my scene design a little easier. I have already read the comments on that video for additional info, as well as looked through Unity forum posts, other posts here on Game Dev.SE, and Google results. It would seem as if this is either old behavior, or there is some small detail neglected to explain in the video of how to synchronize movement of parent and child objects.
|
0 |
Unity. Draw mesh without a mesh class Is there a way to draw an array of vertices traingles directly from code, above 65k verts? I looked at Graphics class but it can only render a Mesh object.
|
0 |
How to access Lit shader properties through code? Currently i'm using HDRP in my project, so i have a question. How can i access Lit shader properties through code ? Or where i can see names of variables in this shader ? For example
|
0 |
FBX exported from C4D and imported into Unity creating new materials When importing a FBX model created in C4D, unity is creating new materials for certain meshes. For example, I have a material in C4D applied to my model called Metal. When imported into unity a new Material called Metal.1 is created and assigned to the mesh. I have no idea why this is happening.
|
0 |
Moving a platform left to right with continuous movement I made a 2D game with Unity, and I am trying to create a platform that will move from left to right continuously, but I don't know how to make the platform move a greater distance then 1 to 1 units because I use the Mathf.Sin function. I can only control the speed of the platform. Here is my code private Vector2 startPosition private int speed void Start () startPosition transform.position speed 3 void Update() transform.position new Vector2(startPosition.x Mathf.Sin(Time.time speed), transform.position.y) Here is what the code actually does How can I control the distance that the platform can move to each side? For now, it can only move 1 unit to each side.
|
0 |
Unity Calculating a rotation based on game time I have a simple script to make an object spin Spin Speed is the speed to rotate the object on each axis (preferably in degrees per second). Local is whether the rotation should be done based on world axes or object axes. Starting Rotation is the initial rotation of the object. Normally I would use Transform.Rotate to do the rotation, but in this case I have to make the rotation a function of time, so you can pass in any time value and it will return what the rotation should be at that time. Here is an example (this doesn't work properly for either world or object axis rotation) private Quaternion getRotation(float time) return Quaternion.Euler(InitialRotation SpinSpeed time) I just need some help figuring out the math behind calculating rotations for both world and object axes. I think that matrices can be used but I honestly don't remember anything about how to use them. Here's an example of using world axes with a SpinSpeed of 180 on the y axis and an initial rotation of 45 on the x axis https i.gyazo.com d7f41b6a88425b5d8b8237cd7ac40878.gif An example of using local axes with the same parameters as above https i.gyazo.com d453b3dd239c9f77b86ce372c499d068.gif
|
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 do I edit a Unity InputField by clicking on Android UI Button? I have been stuck on this problem for a long time and not sure what I need to do. Would appreciate any help. I am building an Android app using Unity. In my app I have an InputField, a TMP InputField to be precise, in my Unity scene as a Prefab. I want to edit this input field by clicking on a button in my Android UI (not part of Unity scene). I don't want the input field to be editable by clicking on the input field itself. In order to achieve this, I enabled the Hide Soft keyboard option in the editor so that user can't edit the field by clicking on the field. But I am not able to figure out how to edit the input field. First problem is how to pop up the keyboard when I click on the Android button. I tried this. TouchScreenKeyboard.Open("") This pops up the keyboard but the input field doesn't show the caret and doesn't accept input. I also tried, EventSystem.current.SetSelectedGameObject(inputField.gameObject, null) inputField.OnPointerClick(null) and inputField.Select() inputField.ActivateInputField() But no success. I tried to play with the focused, interactable, activated properties but nothing works. This should be easy but I am unable to get it to work. Would really appreciate any help. Thanks!
|
0 |
Best way to do discontinuous animation? Or Best way to animate a character with a jerky center of mass? I am using Unity and need to know how to use it animation system properly for well let me describe it below. In this game I have this big 3D block like character that moves in an unusual fashion compared to most game characters. In most games, the character moves along a straight line at a constant rate. However this character, and other characters in the game, does not move in a continuous fashion. Instead it is discontinuous and choppy in unique ways. For example, here is how I want a big block character to move Basically the two corners in front of him are pivot points, and the character moves forward by alternating between these two points and rotating. How can I do this with Unity's animation system? For the most part the animations in Unity don't move the character but instead have an animation play, such as the "Run" animation, and then a script actually moves the character. Know I the animator has a use root movement or something that does exactly this, but I have heard that it can causes problems. I ve been considering just programming all of the animations, since they are relatively simple. However that makes fine tuning them a nuisance, and have some animations programmed and others not is probably not a good practice. I kind of also fear that if I don t end up programming it I will have troubles with detecting if a character can walk through a certain walkway, considering for example the above animation his walk width is greater than his actual width since he rotates side to side. Also keep in mind that there are other animations that are discontinuous like this but work in different ways. For example, another block that hops but pauses between hops. Another might rock backwards and then slide forward on the forward rocking animation. So I know there are multiple ways to tackle this, but my question is what is the best way to do this? How would you do it?
|
0 |
Unity2D Pressing my mute button twice in order for it to set music back to 1 So far my mute button works, its just that I have to press my button twice (when game is restarted) in order for it to put my volume back to 1. Does anyone knows the problem. Anyway this is my script public bool mute void Start() check if the player has a music volume preference if (PlayerPrefs.HasKey("musicVolume")) if yes, apply it. GetComponent lt AudioSource gt ().volume PlayerPrefs.GetFloat("musicVolume") private void Muted () AudioSource audioSource gameObject.GetComponent lt AudioSource gt () mute !mute if (mute) gameObject.GetComponent lt AudioSource gt ().volume 0 PlayerPrefs.SetFloat("mute", 0) else gameObject.GetComponent lt AudioSource gt ().volume 1 PlayerPrefs.SetFloat("mute", 1) write new music volume preference to persistent storage PlayerPrefs.SetFloat("musicVolume", audioSource.volume) Thank you. )
|
0 |
How can I restart an animation? The first time the player clicks a button, my animation plays properly. The problem is that when the player presses the button a second time, the animation does not play. Here is the code I'm using to control my animation public Animator anim public Animator animsfirst public Animator animssecond public Animator animsthird public Animator reanimsfirst public Animator reanimssecond public Animator reanimsthird public Animator closeinstruct public void instructionpanel() (instruction panel open animation) anim.enabled true when button click instruction panel open animsfirst.enabled true animssecond.enabled true animsthird.enabled true public void closeinstructionpanel() (instruction panel close animation) Debug.Log("animationrun") when button click instruction panel close reanimsfirst.Play("freverse") reanimssecond.Play("srevese") reanimsthird.Play("lreverse") closeinstruct.Play("clreverse") Here is the animator controller setup for the animsfirst object And for the reanimsfirst object How can I resolve this issue?
|
0 |
Client projectile ignores camera Y axis in multiplayer shooter I'm able to spawn the bullet and make it move. But the problem is, only the host can shoot the bullet in the way the camera is facing(takes both X axis and Y axis correctly). The client takes only the X axis of the camera and keeps the Y axis at zero. Here's the code for spawning and applying velocity Command void CmdFire() GameObject fb Instantiate(fireBall, spawnPoint.position, spawnPoint.rotation) fb.GetComponent lt Rigidbody gt ().velocity gameObject.GetComponentInChildren lt Camera gt ().transform.forward fireSpeed NetworkServer.Spawn(fb) And the code for the camera attached to the player void Update() mouseX Input.GetAxis("Mouse X") mouseSensitivity Time.deltaTime mouseY Input.GetAxis("Mouse Y") mouseSensitivity Time.deltaTime Horizontal Looking playerBody.Rotate(Vector3.up mouseX) Vertical Looking xRotation xRotation mouseY xRotation Mathf.Clamp(xRotation, 90f, 90f) transform.localRotation Quaternion.Euler(xRotation, 0f, 0f)
|
0 |
Character bobs when moving Whenever I try to move a character in unity, the character kind of, like, bobs around when walking. Is there any way to remedy this? I have tried the trick of putting the inputs into update and the outputs into fixedupdate, if that's any consolation. Also please ignore the fact that I've used the arrow keys instead of getaxis. using System.Collections.Generic using UnityEngine public class MovePlayer MonoBehaviour public bool upArrow true public bool downArrow true public bool leftArrow true public bool rightArrow true public float speed public bool test false void Update() if (Input.GetKey(KeyCode.UpArrow)) upArrow true else upArrow false if (Input.GetKey(KeyCode.DownArrow)) downArrow true else downArrow false if (Input.GetKey(KeyCode.LeftArrow)) leftArrow true else leftArrow false if (Input.GetKey(KeyCode.RightArrow)) rightArrow true else rightArrow false void FixedUpdate() if (upArrow true) transform.position new Vector3(transform.position.x, transform.position.y speed, 0) if (downArrow true) transform.position new Vector3(transform.position.x, transform.position.y speed, 0) if (leftArrow true) transform.position new Vector3(transform.position.x speed, transform.position.y, 0) if (rightArrow true) transform.position new Vector3(transform.position.x speed, transform.position.y, 0) void OnTriggerEnter2D(Collider2D bump) if (bump.gameObject.tag quot Wall quot ) test true else test false
|
0 |
How can I give a MonoBehaviour field a default value that depends on the object? In Unity3D, I have a MonoBehaviour which gets added to game objects. I'm adding a string "name" field to it. I'd like the default value for the name to be the name of the game object the component is added to. Is there an easy way to do this? Some more details The component is an existing one to which I'm adding the name field. In old versions, the name was always the name of the game object, and this is a new feature to allow them to be different. The common case is (still) for the name to be the name of the game object, so having that as the default would simplify the process of adding the component to a new object. Ideally, deserializing an old scene will fill in the default, so updating scenes takes zero effort. I'm less concerned about this than about newly created scenes objects. The component already uses a CustomEditor. I don't care about updating the name in the component if the game object's name is changed, or if the component values are pasted into a different game object. One way I can think of is to add a bool "override name" to the object. If the bool is unchecked, it uses the default name (the game object) if it's checked, it uses the new field. But I'd like to avoid adding complexity to the GUI to support it. The whole point of my request is to add the new functionality (overriding the name) without adding steps to the creation workflow.
|
0 |
How to make dynamic DOF from mouse position in Unity 5? I found a video a while ago for how to make a dynamic DOF in unity. It fires rays from the camera and positions an empty at the location that the ray first hit. How can I change this so that it doesn't fire rays from my camera but rather from my mouse position, and then positions the empty from there? Code public Transform origin Raycast origin public GameObject target public CameraMovement cameraMovement void Start () void Update () Ray ray new Ray(origin.transform.position, origin.transform.forward) RaycastHit hit new RaycastHit() if(Physics.Raycast(ray, out hit, Mathf.Infinity)) Debug.DrawRay(Input.mousePosition, origin.transform.forward, Color.cyan) target.transform.position hit.point else Debug.DrawRay(Input.mousePosition, origin.transform.forward, Color.red)
|
0 |
Unity won't slice images properly Okay, so I am very new to Game Development and I imported a .png file(made in Paint) to the assets and that file contains just a circle and an oval, not touching and far apart from each other, both of them coloured blue. When I open the sprite editor and click on splice, then select Automatic and Delete existing options and then click slice, I do not get different sprites, one containing the circle and the other containing the oval. The image isn't sliced at all. I have also set the sprite mode to Multiple, but to no avail. Can someone help me and tell me what I am doing wrong? The engine I am using is Unity. This is the image.
|
0 |
Unity LoadLevelAdditive and baked light scene settings I am a programmer for a small game. For our levels, I separated the UI from the level data, so one scene is a scene which contains only the UI, the other scene has all the gameobjects and models and ... the light. So when loading a level, I first load the UI scene (LoadLevel), then the actual play scene (LoadLevelAdditive). Now that our graphics guy wants to bake some lights, he is telling me it doesn't work, because whatever his settings in the play scene, Unity ignores them and uses the settings of the UI scene. He also tells me we cannot just ignore the light settings of the UI scene ... So my question is, how do I make Unity ignore the light settings of a certain scene (UI scene in my case) or how can I enable a settings override? Thanks.
|
0 |
Per object screen space uv issue I am currently trying to sample a texture in screen space. This works well float4 positionCS vertexInput.positionCS vertexInput.positionCS.w screenPos ComputeScreenPos(positionCS).xy float aspect ScreenParams.x ScreenParams.y screenPos.x screenPos.x aspect But I would like to be able to constrain uv position and scale based on object's position and distance from camera. I found some example but I also faced some issues and for the moment I don't see how to fix them. Here's the code float4 positionCS vertexInput.positionCS vertexInput.positionCS.w screenPos ComputeScreenPos(positionCS).xy float aspect ScreenParams.x ScreenParams.y screenPos.x screenPos.x aspect float4 originCS TransformObjectToHClip(float3(0.0, 0.0, 0.0)) originCS originCS originCS.w float2 originSPos ComputeScreenPos(originCS).xy originSPos.x originSPos.x aspect screenPos screenPos originSPos You can match object's distance like this float3 cameraPosWS GetCameraPositionWS() float3 originPosWS TransformObjectToWorld(float4(0.0, 0.0, 0.0, 1.0)) float d distance(float4(0.0, 0.0, 0.0, 0.0), cameraPosWS originPosWS) screenPos d And here's the issue I am facing. You can notice that when the object is near screen edges the texture starts to move. Is there a way to avoid that ? https thumbs.gfycat.com HairySpryArawana mobile.mp4 I am using URP but this doesn't really matter.
|
0 |
RTS Pathfinding without collision between units Options Ever since I made my units move to a certain location a problem has popped up that of course if I try to make two or more units go to the same place they fight for the same spot. Am I just being stupid and unity already has a way around this or do I need to do something specific? I have looked into flow field path finding but no way on how to implement it. I dont want to have to use a ready made script but some pointers and other options are more than welcome.
|
0 |
How to force a translation to go through an exact point? I have a camera object with a script that will whether translate it with a set speed, or stop it. I also have 7 "checkpoints", where there are 7 different quads, who will stop the camera whenever the camera reaches them. The problem here is that in my code void Update() if (scoreholder.CheckScore() lt scoretimer) if the current score is less than set X score if (killcam.transform.position.y quadholder.y) and if the camera's position equals the position of the generic quad PROBLEM HERE killcam.GetComponent lt cameraUp gt ().SetCam (true) stop the cam while (scoreholder.CheckScore () lt scoretimer) do stuff offset mr.material.mainTextureOffset offset.y offsetSpeed 0.1f mr.material.mainTextureOffset offset break else once the score is not less than the desired X score, move the cam killcam.GetComponent lt cameraUp gt ().SetCam (false) So my problem here is that this line of code if (killcam.transform.position.y quadholder.y) never happens, the translation skips some values, and the camera doesn't hit the exact quad spot. I tried to use gt instead of , but I ran into another problem, is that after the 3rd quad, since my camera speed increases in time, the code apparently doesn't get processed fast enough, and my camera goes beyond the 4th,5th,6th, and 7th quad without stopping. I have already tried Vector3.Lerp, and it gives me almost the same result, if I lerp between the beginning and the end of the track, I have to do it with an extremely small fraction, and I can't have my camera move at that speed.
|
0 |
How to create temp folder to store a file from external directory and use it in a game I would like to copy a 3D model from external library and save it in temp Resources StreamingAssets folder to instantiate an object in unity scene. public class FBXOBJLoader MonoBehaviour string src Use this for initialization void Start () src EditorUtility.OpenFilePanel("Select Model", "", "fbx") Output the Game data path to the console Debug.Log("Path " src) StartCoroutine("CopySomething") IEnumerator CopySomething() print("Start") string path path Application.temporaryCachePath FileUtil.CopyFileOrDirectory(src,path) yield return null It's creating some unknown file format in the asset folder. can anybody please help me to complete this task. Thanks in advance
|
0 |
Raycasting from an object to the center of the screen (crosshair) without clipping through objects Am trying to learn about Raycasting, and I thought I would start with something simple, and that was a laser that would come out of an object (think laser pointer in your hand) and always go to the crosshair. Using ViewportToWorldPoint I found it easy to cast a ray from the center of the camera, but this had an issue as you can see in this GIF below. The line would clip through because the ray was coming from the center, not off to the side where the laser pointer would be. Am not sure how to solve this. void Update() Vector3 ray Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0f)) line.SetPosition(0, transform.position) RaycastHit hit if(Physics.Raycast(ray, Camera.main.transform.forward, out hit, raylength)) if(hit.collider ! null) line.SetPosition(1, hit.point) else Vector3 pos line.GetPosition(0) line.SetPosition(1, ray (Camera.main.transform.forward raylength)) The closest thing I could find that I am trying to replicate for this exercise is the No Man's Sky mining tool
|
0 |
Post Processing effects not visible with LWRP in Unity3D I'm are running into an issue when setting up Post Processing effects for the new Lightweight render pipeline. Post processing effects are visible in scene and Game view, but not in Play mode. The project is using single pass rendering for VR We are using the LWRP 3.0.0 and the Post Processing package 2.1.2 (both are up to date) It seems like the Post processing volume and layer settings are working fine, as the effects are visible in scene and game view We tried Tweaking the quality and graphics settings Creating a new camera and setting the post processing settings again Removing all additional cameras in the scene Setting the exiting UI Canvas in the scene to Screen Space (Camera) instead of Screen Space (Overlay)
|
0 |
Combining several animations into a single FBX I'm trying to figure out a workflow for preparing character animations for Unity so that they are all combined in a single FBX file. The advantage as far as I see it is that it then uses only a single skeleton where multiple animation files would each have their own skeleton (which I think is unnecessary and would increase size considerably). I've tried using Maya for this but haven't been successful so far. Then I tried Motionbuilder and I can get the animations (takes) together into a single file but many of the animations don't look right afterwards. So I was wondering does anyone know of a solid workflow to achieve this? I'm having a hard time finding information about what I'm trying to achieve. This is probably a piece of cake for experienced animators but I'm just starting with animation now. So how do you combine several animation FBX files into single one (whith either Maya, Motionbuilder, or 3DSMax) and make sure that the animations are all properly retained like they should? I'm sure there are some additional things to take care of but I don't know exactly what they are.
|
0 |
Blurred sprite in Scene view The thread between the tree and the spider here is a LineRenderer. When the BackgroundLandscape or the Tree objects are selected it has this blur around the thread between the tree and the spider. When anything else is selected, it renders correctly. It always renders correctly in the Game view. What's causing this?
|
0 |
Retrieving an array of images from Firebase Storage As title says I'm trying to get all images on firebase storage and save them to an array which later on i will be using to load them into the scene. i can manage downloading on image so far but I'm unsure of how to make them into an array. This is the code I'm using now to download one image by name and assigning it into a texture variable storage FirebaseStorage.DefaultInstance storageRef storage.GetReferenceFromUrl( url) storageRef.Child( resourceName).GetBytesAsync(1024 1024).ContinueWithOnMainThread(task gt if (task.IsCompleted) Texture2D texture new Texture2D(1, 1) byte fileContent task.Result texture.LoadImage(fileContent) Debug.Log(texture.name.ToString()) selectedText texture if (task.IsFaulted) Debug.Log( quot faulted DOWNLOAD quot ) ) now through that i want to replace my current function which loads all images through the inspector. if (LevelSystemManager.Instance.CurrentLevel lt source.Length) selectedText source LevelSystemManager.Instance.CurrentLevel Source being the array i use from the inspector to load those images into the game scene which then are selected into the selectedTex Texture2D and loaded based on the level, so 0 element in array level0 , 1 level 1 etc. etc. So i was wondering if i have a couple of folders inside firebase with 10 to 20 images each how can i make that source array pull from that folder? And as a result remove the need to have them in the game and of course not setting them through the inspector.
|
0 |
Unity C Change color, or material of specific line segments on Line Renderer We're making a game that plays with a LineRenderer, and we want to give it a different visual feedback relative to the side of the screen that it's on. We want to change the feedback of the specific line segments that are on the other side (when they past the middle point). The API lets you map the segments positions, but isn't there a way that you can change the material color of that specific segment? I just see that you can do it, but only for the whole Line Renderer, not segment by segment.
|
0 |
Unity 2D play animation with flipX then enabling and disabling GameObject "locks" flipX I have a GameObject with an Animator that contains many different animations. In C I switch between these animations with animator.Play("AnimName"). Some of the animations have the flipX property checked, so I can use the same sprite for two different directions. This works well, but I have one animation where after it is done I call gameObject.SetEnabled (false) then re enable it a short while later. I achieve this through an event at the end of the animation which calls a method in my script. For some reason, if the last animation I played before disabling the object had the flipX property checked, then all the other sprite animations will be flipped after it is reenabled. I can fix this by adding the flipX property to the other animations then unchecking it, but I don't want to have to go through all my animations to add an unchecked property. This seems like a bug to me, but if it's not, is there some way I can change the behavior?
|
0 |
Inserting into the first available inventory slot Hello my inventory system picks up one item but does not pickup any more to fill the other two slots. It is saying the whole inventory is full when it should be one slot is full. Here is my code for the inventory and this is attached to the player. public class MedInventory MonoBehaviour public bool isFull public GameObject MedkitSlot public GameObject BandageSlot public GameObject CoffeeSlot This next script is attached to the items you pickup. public class MedPickup MonoBehaviour private MedInventory medInv public GameObject itemButton private void Start() medInv GameObject.FindGameObjectWithTag( quot Player quot ).GetComponent lt MedInventory gt () itemButton.SetActive(false) void OnTriggerStay2D(Collider2D other) if (other.CompareTag( quot Player quot )) GameObject targetSlot new GameObject 0 bool validItem true switch (gameObject.tag) case quot medkit quot targetSlot medInv.MedkitSlot break case quot bandage quot targetSlot medInv.BandageSlot break case quot coffee quot targetSlot medInv.CoffeeSlot break default validItem false break if (validItem) for (int i 0 i lt targetSlot.Length i) if (!medInv.isFull i ) medInv.isFull i true itemButton.SetActive(true) Instantiate(itemButton, targetSlot i .transform, false) Destroy(gameObject) break
|
0 |
Basic billiards game Can't detect collision between cuestick and cueball I have a basic Unity project on GitHub. Basically, I have a Cuestick that aims and shoots using the mouse. You can rotate around the cueball with your mouse and when you're ready to shoot, you can hold down the right mouse button and move the mouse forward. The game came follows the cuetip. However, the collision between the cuestick and cueball is wonky. The cuestick protrudes through the ball and only pushes the ball forward only a little bit. I've created rigid bodies and colliders for both cuestick and cueball. I've set the cuestick's rigid body to kinematic (if it's unchecked, the poolstick will barely dent the ball). I've tried using OnCollisionEnter and a Debug.Log statement to no avail. Any help would greatly be appreciated. You can find my scripts in GameLogic (they're F sharp scripts whose binaries get compiled and outputted into the assets folder).
|
0 |
how to prevent a ball from bouncing only vertically I am trying to make a ball bounce off (and also sideways) when it gets into contact with another object. I am having an issue shown in the image below, where the ball rests on the triangle instead of falling off sideways. I tried playing round values for the bounciness and friction, but that didn't solve my issue. How can I solve this issue. I've added the inspector settings on the ball.
|
0 |
How can I destroy particles on collision with specific a GameObject? I wrote a script to manage my Particle System emission. The starting lifespan is set to infinite so that the particle never dies until it reaches a specific collider. I didn't find any method to destroy a specific particle in the Unity Manual. How can I do this? Here's the code (updated to show the partial fix) using UnityEngine using System.Collections.Generic public class PlayerDamage MonoBehaviour private ParticleSystem ps public List lt ParticleCollisionEvent gt collisionEvents public int attackValue 1 Range(0.0f, 100f) public int maxParticles public float particleLife public bool neverDies public float particleSpeed 8.0F void Start() ps GetComponent lt ParticleSystem gt () collisionEvents new List lt ParticleCollisionEvent gt () var collision ps.collision collision.enabled true collision.type ParticleSystemCollisionType.World collision.mode ParticleSystemCollisionMode.Collision3D void OnParticleCollision(GameObject other) int numCollisionEvents ps.GetCollisionEvents(other, collisionEvents) Rigidbody rb other.GetComponent lt Rigidbody gt () int i 0 while (i lt numCollisionEvents) if (rb.CompareTag( quot Enemy quot )) BaseHealth baseHealth other.GetComponent lt BaseHealth gt () if (baseHealth ! null) Vector3 pos collisionEvents i .intersection Vector3 force collisionEvents i .velocity 10 rb.AddForce(force) baseHealth.TakeDamage(attackValue) i void Update() var collision ps.collision collision.maxKillSpeed particleSpeed Debug.Log( quot Particles Alive Count quot GetAliveParticles()) ps.Emit(maxParticles) var main ps.main main.maxParticles Mathf.RoundToInt(maxParticles) main.startLifetime particleLife if (neverDies) particleLife float.PositiveInfinity else particleLife 5f int GetAliveParticles() ParticleSystem.Particle particles new ParticleSystem.Particle ps.particleCount return ps.GetParticles(particles)
|
0 |
Three button combination to open next scene I have thirty (30) buttons in a trivia game, they are laid out in the following configuration with three rows ( A, B, C, D, E, F, G, H, I, J) ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) (00,01,02,03,04,05,06,07,08,09) Using these combinations of buttons and clicking one and only one from each row I have a thousand (1000) three (3) button combinations. E.g. A27 would be one combination of the thousand possibilities. These are not random combinations each opens a very specific scene. What I am trying to do is create a C script that when I click any of these three (3) button combinations it will open a new scene. Once that scene is open I m okay because then have my own scripts attached to the single buttons in the new scene to continue to a further scene. What I can t figure out is the syntax, should I use if Statements such as if (Btn A) amp amp (Btn 1) amp amp (Btn 01) then load scene such and such? Then do I attach the script to the canvas then to each of the three button combinations (A 1000 Scripts combinations)?
|
0 |
Change center point and size with the help of the Matrix in Unity Let us suppose I have an array of Vector3, it contains vertices. Now I want to scale the vertices and or change the center point of the texture (move texture relatively). I have a Vector3 which is a new center point and I have a Vector3 which is vector for scaling along x, y and z. How can I construct a needed matrix in Unity? I am very new to all this, so, please, in case of any misunderstanding ask me about it. Here is what I was able to find on my own. The problem with it, though, is that I can not infer what I need from it. I need a little bit more peculiar thing.
|
0 |
How to "properly" display a 2d sprites in a 3d environment? I would like to show "the classic" missile lock viewfinder (the target symbol) of a war aircraft. So the target symbol must follow the enemy, and became red when "lock" it. So i thought simply to Show the 2d sprite centered on screen (x and y screen.height and width 2 ) but, depending of the Z , the sprite became bigger (near camera) or smaller (far from the camera). How to display a 2d sprite indipendent from Z axis ? Thanks
|
0 |
Unity Best Random Movement Strategy? As of now, to get random movement of my enemies, I am adding a Rigidbody and a BoxCollider then "throwing" them (i.e. adding velocity) in a random direction for a random amount of time and making them choose a new direction if ever they get outside of their designated area. This does not seem to work that well all the time. Sometimes they manage to get themselves stuck inside obstacles which should be impossible. The more I add guys, the more it seems the physics can't keep up or something with the collisions. Is there a better method to random movement or is "throwing" them perfectly valid? Is my method expensive and terrible? I might have around 50 guys active at a time and perhaps a few hundred to a thousand static obstacles each with their own colliders.
|
0 |
Handling accelerate in different devices I am adding tilt controls to my game. The sensor values I get are different in different android devices which results in random behavior. Anyone knows how can I tackle this situation? I tried normalizing acceleration but it is still the same.
|
0 |
Rewarded video ads for two different functions Unity I'm implementing reward based video ads in my game. There are two functions that provide the reward. One is a ReceiveLife() function where once the player dies, if they click on the revive button the game restarts and the score is set to score before the player dies instead of 0. The other function is ReceivePoints(), where if the player clicks on the add points button, they are rewarded with 100 extra points. Here are the functions in the game manager script public void ReceiveLife() savedScore (int)playerScore SceneManager.LoadScene(1) public void ReceivePoints() playerScore 100 gameOverPanel.gameOverScoreText.text quot Score quot ((int)playerScore).ToString() Here is the unity ads manager script public void OnUnityAdsDidFinish(string placementId, ShowResult showResult) if (showResult ShowResult.Finished) gameManager GameObject.Find( quot GameManager quot ).GetComponent lt GameManager gt () gameManager.ReceiveLife() if (showResult ShowResult.Finished) gameManager GameObject.Find( quot GameManager quot ).GetComponent lt GameManager gt () gameManager.ReceivePoints() Once they watch the ad successfully, both the functions are being called. If the player clicks on the ReceiveLife(), he should only get one extra life and not the additional 100 points and vice versa. I'm not sure how to call each function separately. Do I have to create two separate admanagers in order to call these functions or is there a better method?
|
0 |
Divert gameobject around mesh surface I am trying to find a way to divert a vector3 position around the surface of a mesh which doesn't have a collider. I have a function (found online) that calculates the closest position on the surface of the mesh but it only works if the position is outside the mesh. In the diagram below, the red arrow represents whats currently happening. It works great when it's outside the mesh and will give a position on the surface of the mesh, but once it moves forward and enters the mesh, it just keeps walking straight. The green line shows what i would like to happen.
|
0 |
Unity sizeDelta of an Image update opposite to what it should I have an IEnumerator coroutine in which I call the UIManager script to update the Image size to fit the text size but it doesn't happen. when I use yield return new WaitForEndOfFrame() it sometimes solve the problem. but I don't want to use it. edit I tested the code like I was suggested in an empty unity project and it still happens, the width should change according to the text size but it happens opposite (when the text is small the width of the image is large and when the text is large the width of the image is small) (it only happens correctly at the first time the width of the image fits the text width) public class Example MonoBehaviour public Image image public Text text private int k 0 public void ButtonClick() text.text (k 2 0) ? "10" "10 10" image.rectTransform.sizeDelta new Vector2(text.rectTransform.rect.width, 30) k edit Solved! thanks for the help, Canvas.ForceUpdateCanvases() did the trick
|
0 |
Why is anti aliasing not being applied to my 2D objects in Unity? I am drawing 2D objects in Unity. Some of these objects are drawn using the standard sprite method that is built into Unity. Others are computed as distance functions in a shader. In both cases I can't get Unity to apply anti aliasing despite the setting being set. Is there an extra step that I am missing that is required to get anti aliasing to work properly? Would it be better to implement my own form of AA in a shader?
|
0 |
Creating animation by script with animation assets I'm very new to Unity (not to C and programming as well) but I managed to achieve some goals very fast. But some concepts I still don't get in their full aspects. I'm developing a small multiplayer game called skeet. It's about clay pigeon shooting. I have a static 2D scene, with 3 assets A gun, a bullet and a pigeon. These sprites I'm able to deploy on the scene by an event driven script and I'm able to react on collisions between objects. I reached the point I have to animate the pigeon and the bullets. First I have to animate the pigeon moving from border to border in a random direction on a random height. Second if a player presses its key to shoot its bullet must be animated from the bottom of the screen straight upwards. My current idea is to create some animations as assets and to assign them to the sprites I'm creating dynamically. But I don't know what I need in the Unity GUI and in the script. I'm not looking for a ready to run solution but an ordered list of concepts and advices I have to take a look into. Edit The bullets and pigeons are created dynamically and should be destroyed after the animation finished (by reaching any border of the screen or a collision). So I need to create an animation with assignable position parameters.
|
0 |
How to efficiently spawn instantiate a large amount of objects from a prefab I am trying to make a game where the whole world is consists of a very large amount of cubes (sort of a Minecraft Trove clone), but I keep running into huge performance issues due to the large amount of objects vertices being rendered at once. Just to clarify, the problem appears to be caused by the rendering, not the instantiation. I think so based on the fact that when I look away from the cubes, the frame rate will return back to normal ( 60). Is there any way to optimize this? Many answers to similar questions suggest disabling colliders, but that does not really seem to make much of a difference for me. I have also tried making the prefab static, but the problem still remains. Currently I keep getting 40 FPS with 10000 cubes (just the built in cube shape stored as a static prefab with a disabled collider). I believe there should be a way to have a larger amount of objects on screen without having such a performance drop. Does Unity have any way of storing information about a prefab in graphics card memory that would allow it to mass render its instances in a more performance efficient way (much like modern OpenGL uses vertex buffers)?
|
0 |
How can i display a nice big gui text in the middle of game view screen? The same idea like the message "Display 1 No cameras rendering" I'm trying to do it too but i don't see anything when running the game. In the Hierarchy i have a empty GameObject and in the Inspector attached to it the script and two components GUI Text and GUI Texture This is the script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class SwitchCameras MonoBehaviour Header("Cameras Init") public Camera cameras public Vector3 originalPosition HideInInspector public Vector3 currentCameraOriginalPosition, currentCameraPosition Space(5) Header("Cameras Switch") public string currentCameraName public Vector3 lastCameraPosition private int currentCamera 0 Space(5) Header("Gui Text") public GUIText myGUItext public GUITexture texture public int guiTime 2 void Start() cameras Camera.allCameras lastCameraPosition new Vector3 cameras.Length if (cameras.Length gt 1) originalPosition new Vector3 cameras.Length for (int i 0 i lt cameras.Length i ) originalPosition i cameras i .transform.position if (cameras.Length 1) myGUItext.text "Need more then 1 camera for switching.." myGUItext.gameObject.SetActive(true) texture.gameObject.SetActive(true) StartCoroutine(GuiDisplayTimer()) else Debug.Log("Found " cameras.Length " cameras") for (int i 0 i lt cameras.Length i ) cameras i .enabled false cameras 0 .enabled true currentCameraName cameras 0 .name currentCameraOriginalPosition originalPosition 0 void LateUpdate() if (Input.GetKeyDown(KeyCode.C)) cameras currentCamera .enabled false if ( currentCamera cameras.Length) currentCamera 0 cameras currentCamera .enabled true currentCameraName cameras currentCamera .name currentCameraOriginalPosition originalPosition currentCamera lastCameraPosition currentCamera cameras currentCamera .transform.position currentCameraPosition lastCameraPosition currentCamera IEnumerator GuiDisplayTimer() yield return new WaitForSeconds(guiTime) myGUItext.gameObject.SetActive(false) texture.gameObject.SetActive(false) I used a break point and it's getting to the line myGUItext.text "Need more then 1 camera for switching.." But not showing it on the game view when running the game.
|
0 |
RectTransform Button Start shaking with Vector3.MoveTowards() I have a RectTransform Button that i want to make it move to a de terminated vector3. To move the button i use this code (it is inside Update()) int i 1 foreach (RectTransform Button in Buttons) i Vector3 NewPosBtns new Vector3(StartButtonsVect i .x, (StartButtonsVect i .y 192.5f), StartButtonsVect i .z) Vector3 CurPosBtns StartButtonsVect i Button.localPosition Vector3.MoveTowards(CurPosBtns, NewPosBtns, AnimationSpeed) Buttons is a array and i add the button to the list using unity editor StartButtonsVect is of vector3 that i add the using this code void Start() foreach (RectTransform Button in Buttons) StartButtonsVect.Add(Button.localPosition) For some reason the button start shaking instead of going to the target position (NewPosBtns)
|
0 |
Does destroying object at List element make it null? I'm using a list in Unity and I'm adding objects to it as they are collected through the game. But they will then be used and destroyed. My first question is do I use Destroy(), or should I just use List.Remove()? I'm not sure what happens to an object once it is removed from a list and not used anymore. Does garbage collection get it? My other question is, when I check the list (I will always be checking the first index), if that object was just destroyed or removed, will that element now be null? I've tried reading about this but it's hard to find an exact answer. Thanks for the help. For reference, here is the code that I came up with based on my current assumptions about lists public List lt BasePickUp gt pickUpQueue new List lt BasePickUp gt () public bool pickUpActive false void Update () if (pickUpQueue 0 ! null amp amp !pickUpActive) pickUpActive true pickUpQueue 0 .ActivatePickUp() Edit I have been playing with the if statement conditions, and even if I change pickUpActive to true, it somehow still manages to get inside the if statement to the breakpoint there. How is that possible? The condition says pickUpActive must be false, and yet it blows right by it. When I set the first condition to pickUpQueue ! null, I get an error for index out of range once, when it is set to check the first element, as it is in the above code, I get an index out of range every frame. I finally changed it to pickUpQueue.Count ! 0, and that finally kept it from getting into the if statement. If anyone can help me understand what is going on with my bool, and to understand exactly how to handle this list, I would greatly appreciate it! Thanks!
|
0 |
specific function of class Time Is there a function that according to the name of the object, its tag and the time taken since the beginning of the game(for example time Time.deltaTime), gives the position of this object? if yes which one? thanks from a rectilinear trajectory unknown to a randomly translated object, I need to press a Q key to know its direction vector. For this, I get the position of the object to the object. Q support and if I get the position of the object in the lapse of time preceding the moment of this support, the difference of these 2 positions gives me the direction sought of the trajectory at this moment. When I have perfectly resolved this script, I will create another very similar one that will give me the vector direction of the rectilinear trajectory of the object at each collision on another object Here is my script Blockquote using System.Collections using System.Collections.Generic using UnityEngine public class script5 MonoBehaviour public GameObject sphere public static float t public float laps time public static float temps public float difftime float temps appui float x1,y1,j1 float x2,y2,j2 float x3,y3,j3 Vector3 cat transform.position struct vecteur public float k1 public float k2 public float k3 Use this for initialization void Start () temps Time.deltaTime fonction retournant la position d'un objet un instant pr cis vecteur function script6(float t) vecteur v v.k1 0 v.k2 0 v.k3 0 Vector3 cat transform.position if (temps t) v.k1 cat.x v.k2 cat.y v.k3 cat.z return v Update is called once per frame void Update () float temps appui public float difftime public float laps time t Time.time donner les coordonn es de la sph re au temps o la touche Q est appuy e if (Input.GetKeyDown (KeyCode.Q)) donner les coordonn es de la sph re au temps o la touche Q est appuy e temps appui temps difftime temps appui laps time function script6 (temps appui) donner les coordonn es de la sph re au temps juste avant l'appui de la touche Q function script6 (difftime) x1 function script6(difftime).k1 x2 function script6(difftime).k2 x3 function script6(difftime).k3 j1 function script6 (temps appui).k1 j2 function script6 (temps appui).k2 j3 function script6 (temps appui).k3 donne le vecteur de la trajectoire de la sph re l'appui de la touche Q y1 function script6 (temps appui).k1 function script6 (difftime).k1 y2 function script6 (temps appui).k2 function script6 (difftime).k2 y3 function script6 (temps appui).k3 function script6 (difftime).k3 print ("(position appui " j1 "," j2 "," j3 ")") print ("(position difftime " x1 "," x2 "," x3 ")") print ("(vecteur trajectoire " y1 "," y2 "," y3 ")") print (" ") almost everything is good except for the position of difftime which is always null. Why?
|
0 |
Debug.DrawRay() does not draw rays in game view Here is the relevant code protected override void Update() base.Update() Debug.DrawRay(this.transform.position, this.transform.forward 100f, Color.red, duration 2f) When running the game, I can see the ray being drawn in Scene View. However, in Game View, no ray is displayed. As you can see from the screenshot below, I have already enabled gizmos in Game View. What should I do to ensure that rays are being drawn in Game View when debugging?
|
0 |
Why my dynamically generated Sprites overlap? I'm trying to dynamically generate scene representing chess board made from sprites. I'm using two textures for these pieces.png (taken from here http opengameart.org sites default files chess 2.png) tiles.png (drawn by hand, consists of two 128x128 squares filled with different colors) The best result I achieved so far is a board with overlapping tiles The sprite mode for these textures is "Single" and pixels per unit are set to "128" (unsure whether I should've done this or not) The textures are being sliced to sprites in my MonoBehavior.Start var tiles new Dictionary lt int, Tile gt () var sprites new Dictionary lt int, Sprite gt () Load all tilesets foreach (var externalTileset in map.tilesets) var tilesetAsset (TextAsset)Resources.Load ("Boards " externalTileset.source) var tileset (Tileset)tilesetSerializer.Deserialize (new StringReader (tilesetAsset.text)) Texture2D texture (Texture2D)Resources.Load ("Boards " tileset.image.source.Replace (".png", ""), typeof(Texture2D)) Debug.Log ("Texture for " tileset.image.source " loaded " texture.width 'x' texture.height) int tilesPerRow tileset.image.width tileset.tilewidth int totalTiles (tileset.image.width tileset.tilewidth) (tileset.image.height tileset.tileheight) for (int tileId 0 tileId lt totalTiles tileId ) float x tileset.tilewidth (tileId tilesPerRow) float y (tileId tilesPerRow 1) tileset.tileheight sprites externalTileset.firstgid tileId Sprite.Create (texture, new Rect (x, texture.height y, tileset.tilewidth, tileset.tileheight), new Vector2 (0.5f, 0.5f)) if (tileset.tiles ! null) foreach (var tile in tileset.tiles) tiles.Add (externalTileset.firstgid tile.id, tile) And when sprites are added to newly created game objects float minX 4 float maxX 4 float minY 4 float maxY 4 for (int i 0 i lt map.height i ) float y minY i (maxY minY) map.height for (int j 0 j lt map.width j ) float x minX j (maxX minX) map.height if (pieces i, j ! null) GameObject piece new GameObject (pieces i, j .properties "Color" ' ' pieces i, j .properties "Type" ) SpriteRenderer renderer piece.AddComponent lt SpriteRenderer gt () renderer.sprite piecesSprites i, j piece.transform.position new Vector2 (x, y) if (tileSprites i, j ! null) GameObject tile new GameObject ("Tile") SpriteRenderer renderer tile.AddComponent lt SpriteRenderer gt () renderer.sprite tileSprites i, j tile.transform.position new Vector2 (x, y) I believe I can hack something to make this work, but I want to know how to do it properly What's wrong with my code or scene resources setup?
|
0 |
How can I send commands to only certain clients? I am building a multiplayer game server with Unity. In the game there are players moving around the map. Now, because this map is quite large compared to the number of players, I was thinking to have the server send each clients' position only when they are nearby, and then slow the rate down when they are far away. At first I was using the convenient SyncVar to do sync everyone's position, until I discovered its shortcomings, that is there is no conditional way to either sync or not a certain value. I came out with this player synchronization class so far (I removed all optimizations for simplicity) public class PlayerSyncPositionConditional NetworkBehaviour Vector3 lastPos void FixedUpdate () TransmitPosition() ClientCallback void TransmitPosition () CmdProvidePositionToServer(transform.position) Command void CmdProvidePositionToServer (Vector3 pos) transform.position pos Now, what this code does is nothing more than sending its position to the server when I am looking at the dedicated server instance, each players' position is correct. Also, as expected, each client will not receive any updates. From my research, I found that instead of SyncVar, I can use Server and ClientRpc to dispatch commands from the server to all clients, so this Server public void MoveTo() RpcMoveTo(transform.position) ClientRPC void RpcMoveTo(Vector3 newPosition) transform.position newPosition this will run in all clients would move all clients to the transform current position whenever needed. Now, the problem is that those commands, apparently affect every client, while I only want to affect ones that are near each other. I know how to have the server issue the MoveTo at any rate I want, setup more than one interval, etc. but I don't know how to have it send only to certain clients at a single time. I am not asking for the code itself, but I am getting really confused with all these client server architecture concepts, which class does what, etc. so any heads up will be greatly appreciated.
|
0 |
Unity TextMeshPro bounds.size is wrong when hovering first time over gameobject I have this weird issue, which I am not able to fix. This is my third attempt and I need some help. Basically I have a hover element which spawns when I hover over a gameobject. The height of the element is determined by the amount of text (TextMeshProUGUI). The issue happens only when I hover first time, also not always (I have no clue how to reliably to reproduce it). Here is what happens (sec 10 ) https vimeo.com 449387131 I have tried to add these everywhere and different combinations LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() Canvas.ForceUpdateCanvases() txtMeshPro.ForceMeshUpdate() They dont seem to help. I assume the problem is here float bgHeight txtMeshPro.bounds.size.y 25 The bounds.size.y is wrong the first time I hover, but I have no clue why. Here is the whole code for spawning the GUI element public static void SpawnGeneralHoverElement(string descText, RectTransform hoverOverRect, float guiWidth) Canvas hoverCanvas instance.hoverElementGeneral.GetComponent lt Canvas gt () EnableCanvas(hoverCanvas) TextMeshProUGUI txtMeshPro hoverCanvas.GetComponentInChildren lt TextMeshProUGUI gt () RectTransform hoverElementRect hoverCanvas.GetComponentsInChildren lt RectTransform gt () 1 float scale hoverCanvas.GetComponent lt RectTransform gt ().localScale.x txtMeshPro.text descText Need this to be dynamic, if I change hover element size, it will still work float hoverElementWidth guiWidth Forces canvas update because of stackoverflow.com questions 55417905 why is textmeshpro not updating textbounds after setting text Canvas.ForceUpdateCanvases() LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() txtMeshPro.ForceMeshUpdate() Need this because otherwise the element spawns too far away on smaller resultions float spawnOffset (txtMeshPro.bounds.size.y hoverCanvas.GetComponent lt RectTransform gt ().localScale.x) (Screen.height 0.022f) float bgHeight txtMeshPro.bounds.size.y 25 hoverElementRect.position new Vector3(hoverOverRect.position.x, hoverOverRect.position.y spawnOffset, hoverOverRect.position.z) hoverElementRect.sizeDelta new Vector2(guiWidth, bgHeight) Debug.Log(hoverElementRect.sizeDelta) LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() Canvas.ForceUpdateCanvases() txtMeshPro.ForceMeshUpdate() Slide in form left to right if off bounds, need for traps for example float leftOffset hoverElementRect.position.x ((hoverElementRect.sizeDelta.x scale) 2) if (leftOffset lt 0) hoverElementRect.position new Vector2(hoverElementRect.position.x (leftOffset 1) 15, hoverElementRect.position.y) Slide in form right to left if off bounds, need for traps for example float rightOffset Screen.width (hoverElementRect.position.x ((hoverElementRect.sizeDelta.x scale) 2)) Debug.Log( quot Screen width quot Screen.width quot nrightOffset quot rightOffset) if (rightOffset lt 0) hoverElementRect.position new Vector2(hoverElementRect.position.x (rightOffset 1) 15, hoverElementRect.position.y) LayoutRebuilder.ForceRebuildLayoutImmediate(hoverElementRect) hoverElementRect.ForceUpdateRectTransforms() Canvas.ForceUpdateCanvases() txtMeshPro.ForceMeshUpdate()
|
0 |
Prefabs scaling change also the original prefab I want to work with a prefab as local and global variable? something like that. So my question is how to change a prefab scale without affecting the original prefab.
|
0 |
Attaching objects on collision in Unity? I'm trying to make a game where the player can connect objects Lego style with objects becoming children of any object they come into contact with, so if the parent object is moved the child is moved too, but the child object can be dragged away to disconnect it. What is the best way to go about doing this?
|
0 |
Match 3 should pieces store their location in the matrix? I'm making a match 3 game. I have a TileManager script which stores all the tiles in a matrix, it's a singleton and it handles tile swapping and basicly everything regarding the management of tiles. I have a variable called selectedTile. I have a method called SwapSelected which swaps the currently selected tile with the one you just clicked on. As pieces don't know their location in the matrix I can only loop through the whole thing to find them but it feels extremly stupid I just feel like there's gotta be a better way. If pieces stored their location and I kept that updated all the time that'd feel stupid too. What could I do to make this method work nicer and more optimalized? Is there a way or there is no problem with how I do it? public void SwapSelected(Tile tileToSwap) Vector3 tempPos selectedTile.transform.position selectedTile.transform.position tileToSwap.transform.position tileToSwap.transform.position tempPos Vector2Int tileToSwapPosition new Vector2Int( 1, 1) Vector2Int selectedTilePosition new Vector2Int( 1, 1) OPTIMALIZE!!!!!!!!!!!!!!!!!!!!!!!!!!!!! for (int x 0 x lt tileMap.GetLength(0) x ) for (int y 0 y lt tileMap.GetLength(1) y ) if ( tileMap x, y tileToSwap) tileToSwapPosition new Vector2Int(x, y) if ( tileMap x, y selectedTile) selectedTilePosition new Vector2Int(x, y) tileMap selectedTilePosition.x, selectedTilePosition.y tileToSwap tileMap tileToSwapPosition.x, tileToSwapPosition.y selectedTile UpdateTileName(tileToSwap) UpdateTileName(selectedTile)
|
0 |
How can I make natural rain drops on screen? I'm trying to make rain effect drop with metaballs and trail on screen.I find a clue in shadertoy but I didn't understand how implemented https www.shadertoy.com view ltffzl unfortunately it have many math calculations and i can't use it in unity because it produces a lag.obviously I should use textures but how can I have trail effect?! my idea is using a texture and trail renderer for droping but how can I have metaballs effect? Update I could Implement Metaballs by This Article https github.com smkplus RainFX tree master but I haven't Idea about trail
|
0 |
Unity my game starts in windowed mode, but the fullscreen box is checked When I open my game the fullscreen box is checked, but the game is windowed. If I uncheck and check the box it will go into fullscreen. What is the fix? public class Settings MonoBehaviour public void SetFullscreen (bool isFullscreen) Screen.fullScreen isFullscreen I save the current display resolution when the player hits the quit button public void Quit() if UNITY EDITOR UnityEditor.EditorApplication.isPlaying false else Application.Quit() endif
|
0 |
Making an enemy follow player (Unity) I'm working on coding enemy ai for a star fox esqe shooter and I need the enemy to approach the player, stay a certain distance away and stay in front of them until destroyed. I can get the enemy to approach the player and I can get the enemy to stay a certain distance from the player but I'm not sure how to get the enemy to actually stay in front of the player. For a bit of extra information, the player makes a number of sharp turns and the like throughout the level. Also, as a stand in I tried simply causing the enemy to parent to the player within a certain radius but that causes clipping issues with buildings and the ground. public class EnemyCar MonoBehaviour public float safeDistance 20f How close the enemy can get to the player ... Update is called once per frame void Update() transform.LookAt(player.transform) Vector3 targertLocation player.transform.position transform.position float distance targertLocation.magnitude Decrease our speed as we get closer rb.AddRelativeForce(Vector3.forward Mathf.Clamp((distance 30) 50, 0f, 1f) thrust)
|
0 |
Unity Default Shader Greyed Out I created a pland in Unity 3D and then tried to alter the material. I looked at it's material component, but all the options are greyed out! how do I fix this problem?
|
0 |
Unity Matrix4x4 to rotate a point around a pivot axis I need the Matrix4x4 to rotate around a given axis that does not go through (0,0,0). Is there some built in straightforward way to do this in the Unity libraries, or do I need to build and maintain my own? Below is the formula I'd use to build my own in case somebody needs it We will define an arbitrary line by a point the line goes through and a direction vector. If the axis of rotation is given by two points P1 (a,b,c) and P2 (d,e,f), then a direction vector can be obtained by u,v,w d a,e b,f c . ... Assuming that u,v,w is a unit vector so that L 1, we obtain ... Source I do need the rotation Matrix, not just the rotation. If I didn't need the Matrix I could use (not tested, may contain flaws, but you get the idea) public Vector3 RotatePointAroundAxis(Vector3 point, Ray axis, float rotation) return Quaternion.AngleAxis(rotation,axis.direction) (point axis.origin) axis.origin So far the best I've got is the equivalent of the above (not tested, may contain flaws, but you get the idea), but it looks quite wasteful public Matrix4x4 RotationMatrixAroundAxis(Ray axis, float rotation) return Matrix4x4.TRS( Axis.origin, Quaternion.AngleAxis(rotation, Axis.direction), Vector3.one) Matrix4x4.TRS(Axis.origin, Quaternion.identity, Vector3.one)
|
0 |
DontDestroyOnLoad() doesn't work in Unity I have a problem with DontDestroyOnLoad() in Unity. It does not work! My code private static PlayerSpawningScript instance public void Awake() Debug.Log ("PlayerSpawningScript awake") Debug.Log ("Instance " instance) if (instance null) Debug.Log ("Initializing PlayerSpawningScript instance") instance this DontDestroyOnLoad (gameObject) if (instance ! this) Debug.Log ("PlayerSpawningScript instance exists. Destroying new copy.") Destroy (gameObject) Debug.Log ("PlayerSpawningScript instance " instance) public void OnDestroy() Debug.Log ("Destroying PlayerSpawningSceript instance " instance.ToString ()) Basing on the console output, I successfully create an instance in scene1, but when I change the scene, it gets destroyed I know this because I get "Destroying PlayerSpawningScript (...)" before the new scene is loaded, and the same script set up in scene2 does not find an existing instance (which held data saved in scene1) and sets up itself as the instance instead of getting Destroyed. What am I doing wrong?
|
0 |
When an animation involves movement, where is the movement better to implement? For context, I am using Blender and Unity. Regarding the question, as an example, in some games, when you get hit, your character tucks a bit and gets knocked back a few distance. The tucking animation I want to implement in Blender but how about the knockback distance? Do you move your model in Blender (tuck and knockback), or do you do the tuck animation only (tuck in place) and then handle the knockback in Unity (basically triggering the tuck animation and then moving the model backwards a bit). My question basically is, what's commonly done and if there's any specific reason, why?
|
0 |
How to use a .cube LUT file with Color Lookup? I have used quot Image 2 LUT quot to create a LUT for Unity from a certain movie. However, currently quot Image 2 LUT quot only outputs quot .cube quot files. For HDRP, this is great, but for some reason, URP doesn't accept .cube file. URP expects specially laid out .png LUT file. Is there any way to convert a .cube LUT file to a PNG that I can put into the slot of Color Lookup gt Lookup Texture with URP? Unity expect this format The tutorial that Google finds and recommends is this. However, I don't have Photoshop. Also, the tutorial deals with a square LUT that looks like this So even if I had Photoshop and I would follow the tutorial, I would still have a square LUT which is not laid out as Unity would expect it, so I did not use that tutorial. How do I create a LUT png from a .cube file that I can use with URP? Thank you.
|
0 |
Modify the effect of a card being played I'm trying to recreate a simple card game. Each played card has an action (draw extra cards, peek at draw stack, eliminate an opponent card, etc). Once played, it goes on a stack, and the card effect is executed in order. Cards added by effects are added at the end of this stack as well, and executed once it is their turn. Each player also has a different unique influence on exactly one type of cards that changes the effect (enhances it like draw 4 instead of 2 or taking cards instead of trashing them to graveyard). So far a card has a simple interface with value, type and doAction. While I could on each card do a check if a player influence would take effect, this seems like a hard coded noodle salad and makes it difficult to add new cards or influences. And more than once influence can take effect on the same card (for example, one effect could be steal 2 instead of 1 and the second effect, you can steal only a certain type of card from a second influence instead of free choice) I'm looking for a way to react on a method call (played card that gets executed) and change it accordingly. I'm investigating using delegates for this purpose.
|
0 |
Unity3d Get a direction vector parallel to plane I need to send a raycast from my camera which is parallel to the plane (Ground) and in the same direction of its forward vector (Represented by the black color vector) I cant use world space direction because the global forward vector of the camera points at the same direction no matter how much I rotate it (Since its a VR camera) I tried to use Vector3.ProjectOnPlane, but not sure how it works. Can someone help me?
|
0 |
How to prevent a duplicated shadow? It's a blob shadow which is built in Unity's standard asset package. As you see in the figure below, a shadow that is created by the Unity Projector is duplicated at the floor below. How can I prevent this duplicated shadow?
|
0 |
How to make one material on object with many parts inside? I have a weapon witch have many parts, it also have many materials. Do I really need to make it like that? It's like about 8 mats! (
|
0 |
Low Res Atlas Texture vs. Many different materials without textures So I have recently started to look into optimizing a medium complex 3D scene, more specifically i am looking to improve the performance i get from a fairly realistic bus. I am currently using the Unity3D standard shader. There are a lot of different objects within the scene, most of which are repeated and instanced. While many individual objects require only limited color variance often enough just a solid color and no texture at all. I have read a lot about batching and atlasing but can't quite find an answer on the trade off of using textures when no textures are required. I understand that reusing the same material allows for batching and can greatly reduce the amount of draw calls, however how does this compare to the complexity of texture mapping if this could be avoided entirely? Is it still good practice to atlas solid colors on very low resolution atlas textures and thus combine materials together? How does it look if i intend to use metallic and smoothness maps as well? Does it all come down to scene complexity and a number game or is there a straight answer? I have the same uncertainty when it comes to objects which are made up of an arbitrary single digit number of solid colors given supporting geometry, is it better to assign different materials with solid colors to regions of the object or create low resolution textures? In general what is the point at which atlasing becomes the worse choice? Thanks in advance!
|
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 can I model a star? I'm trying to model a star in Unity, and it, sort of works, but it's not ideal. Currently, I'm using a large sphere with a self illuminating material containing a star texture applied to it's surface, and a spotlight to create the effect of starlight, like this While it works, it doesn't look the greatest. I'm looking for an effect more along the lines of how Kerbal Space Program models a star How can I achieve this effect?
|
0 |
Rotate around moving object I'm using the function Transform.RotateAround in order to make my player rotate around objects in my game, it's the main feature. The thing is, when I'm making my levels harder and make the objects (that the player rotates around) dynamic and add some movement on the X amp Y axis, the rotation movement is inconsistent, obviously, since the function recalculates each frame a different pivot to rotate around, the player distance from the object changes and not staying static throughout the rotation cycles. The question is, is there a way to get around this and make the player rotate around the object in a static, permanent distance from the object even though it's moving? Maybe by predicting the movement of the object or somehow quot diffusing quot the effect of the object movement..? Any comment would be helpful. Thanks in advance!
|
0 |
Vector2.Distance on different resolutions firstTouchPos Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position) endTouchPos Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position) the height of the background(previously scaled to fit the screen) 10 minSlidedDistance (int)(SpriteRend.bounds.size.y 10) if (Vector2.Distance(firstTouchPos, endTouchPos) gt minSlidedDistance) do smth This way I check if the player has slided into any direction with a slided distance longer than minSlidedDistance. It works perfectly for different size devices. Is unity going to make the calculations itself if I simply write minSlidedDistance 100? I.e. is it still going to work same way on all devices? P.S. this is not the full code, there are many other IF checks, like the ones for assigning the value to firstTouchPos amp endTouchPos
|
0 |
Unity launches both Visual Studio and Monodevelop simultaneously When I open a script for editing from Unity, both Visual Studio and Monodevelop are launched, resulting in two instances of the same solution to be open in two different script editors. I am presently running the latest version of Unity 5.50fs (though I also experienced this issue in the previous build prior to installing Unity's latest update), in conjunction with Visual Studio Community Edition 2015, and Visual Studio Tools For Unity 2.3.0. I also have my external script editor set to VS in the preferences window of Unity. While investigating this issue I came across a forum thread of someone experiencing a similar problem, where MD opens instead of VS. This seemed to be a result of a hard coded reference to MD for redundancy in cases where VS might fail to load, which I thought sounds like a plausible explanation for my situation as well. The general consensus was that when VS takes a little too long to open, Unity reverts to MD under the assumption that their is a problem with VS. This explanation seems even more likely in my case because this issue only occurs when I first open Unity for the day if I have had VS open recently MD does not open, and VS opens quite quickly, likely a result of being cached in my computers memory. The work around offered to avoid MD launching instead of VS in that thread, was to change the name of the MD executable, so that Unity would be unable to launch MD, giving VS time to finish loading. I was however hoping to find a better solution. I like the fact that Unity has that redundancy in place and would rather keep it intact, and I don't know why but changing the executable solely for that purpose makes me feel a little OCD. Other ideas I have tried include reinstalling Unity, running both Unity and VS as an administrator, and launching VS prior to opening the script in Unity (in this case Unity opens a second instance of VS). Has anybody else experienced both script editors being launched simultaneously and or have any other ideas on how to resolve it? It's obviously not a critical issue or anything, but it is a bit annoying.
|
0 |
Vertex position problem for connected lines I m trying to generate a mesh to display connected segments representing street lines in a mini map. I have problem with vertex orientation that my math knowledge has hard time to resolve. Let s consider 3 points p0, p1 and p2. I use this code to create the vertices from the segment between p0 and p1 (the same code is then used for the segment from p1 to p2) height 2.0f desired line thickness vertices 0 new Vector3(p0.position.x, p0.position.y height 2.0f, 0) vertices 1 new Vector3(p1.position.x, p1.position.y height 2.0f, 0) vertices 2 new Vector3(p0.position.x, p0.position.y height 2.0f, 0) vertices 3 new Vector3(p1.position.x, p1.position.y height 2.0f, 0) The result looks like this Not that bad, except that the "thickness" of the line is not constant. If you look closely to the segment left and right borders, they are aligned (going from bottom to top). The problem comes from the height variable that is added or subtracted too naively to the positions. What I d like to have is something like this, with oriented borders vertex. However I don t know how to proceed. Any help or comment would be appreciated. Thanks for your time. EDIT Thanks to wondra's solution I managed to do what I needed to. Here is how Returns point of intersection TODO check if lines are parallel public Vector3 LineIntersection(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4) float ma (p2.y p1.y) (p2.x p1.x) float mb (p4.y p3.y) (p4.x p3.x) float ba p1.y (p1.x ma) float bb p3.y (p3.x mb) float x (ba bb) (ma mb) float y ma x ba return new Vector3(x, y) LOOPING THROUGH POINTS wondra's solution Vector2 dir (sec node.position prim node.position).normalized Vector2 perp new Vector2(dir.y, dir.x) vertices vert idx prim node.position (perp height 2.0f) vertices vert idx 1 sec node.position (perp height 2.0f) vertices vert idx 2 prim node.position (perp height 2.0f) vertices vert idx 3 sec node.position (perp height 2.0f) if ( vert idx gt 4 ) int vert idx bis vert idx 4 vertices vert idx LineIntersection(vertices vert idx , vertices vert idx 1 , vertices vert idx bis 1 , vertices vert idx bis ) vertices vert idx bis 1 vertices vert idx vertices vert idx 2 LineIntersection(vertices vert idx 2 , vertices vert idx 3 , vertices vert idx bis 3 , vertices vert idx bis 2 ) vertices vert idx bis 3 vertices vert idx 2 END LOOP
|
0 |
FBX model from Blender doesn't show it's surface in Unity3D I've create a model from Blender and exported it as .FBX file. However when I import this into Unity, the surface is missing.how can i fix? Screenshot attached in Blender it look like this in Unity it look like this which only shows it inside
|
0 |
Why does the size extents of a bounding box of a BoxCollider in Unity show the Z element being double what it is? As you can see from the picture below, I fetch the BoxCollider inside CollisionHandler and Debug.Log() it to the screen. In this case, I'm logging the size, but the same thing happens with extents. There are 4 logs because I have 4 instances of the object in the scene. The Z value of the Vector3 is double what it should be, whereas the other values are, for the most part , normal. Also, it seems that each object prints a slightly different value for extents.z. Most stay around 1.3, but one gave me 1.07 . Additionally, it inverts the order for 2 of the objects. I don't know why. None of the objects are scaled and all use the exact same values for their collider. I tried drawing a cube with the same size as the BoxCollider's bounding box, and here's what I got I'm not entirely sure if the misalignment with the Collider in the scene is a sign of a problem or just how Gizmos.DrawCube() works. Here's the code that does this private void OnDrawGizmosSelected() Vector3 origin coll.bounds.center transform.TransformDirection(new Vector3(0f, 0f, 0.675323f skinWidth)) The hardcoded number above is Z extent of the box. Vector3 direction transform.TransformDirection(Vector3.forward) 2 Gizmos.color Color.red Gizmos.DrawRay(origin, direction) Gizmos.DrawCube(origin direction, coll.bounds.size) Where coll is a reference to the BoxCollider, cached in Awake(). Unity version 2019.3.15f1. For the X value of 2.286476, it rounded to 2.1 in the 3rd log for some reason. And in the first log, it rounded the doubled value of Z to 2.4 rather than 2.6...
|
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 |
How to trigger onclick for Unity Selectable by script? As title, I know Button can be triggered onclick by button.onClick.Invoke() But how to simulate onclick event of Selectable? Thanks for the help.
|
0 |
How can I handle two collisions in the same frame? My problem is that I have a player with collisions, and enemy can collide with players collision and execute Hurt function in players script. But the problem is enemies can overlap and can hit the player in the literally same frame. So they both execute Hurt function. In my Hurt function I change players collision layer for a 2 seconds, and he is no longer be able to seen by enemies. But it doesnt matter because of the same hit by two or more enemies in the same frame. How can I solve this? I tried bool to check if Hurt function is executed but it doesnt work too... Here is Code on Enemy IEnumerator OnCollisionEnter2D(Collision2D collision) if (collision.gameObject.CompareTag("Player")) buras kediler st ste bindiginde birden fazla kez calisabiliyor charMovementRef.StartCoroutine(charMovementRef.Hurt()) Debug.Log("hasar yedi") Code on Player Hurt should only works one at the same time public IEnumerator Hurt() layer de i tirerek d man collisionlar ndan ka gameObject.layer 9 can azalt health HeartUI() show the new health on UI karakter g r nt s yan p s ns n gameObject.GetComponent lt SpriteRenderer gt ().color new Color(1f, 1f, 1f, 0.5f) player z plat rb2D.velocity new Vector2(rb2D.velocity.x, 0) rb2D.AddForce(new Vector2(0, jumpPower 1.2f)) 2 saniyeli ine colliderlar kapal kals n, sonra eski haline evir yield return new WaitForSeconds(2) gameObject.layer 0 gameObject.GetComponent lt SpriteRenderer gt ().color new Color(1f, 1f, 1f, 1f)
|
0 |
Unity Instantiate an object respecting the prefab's default rotation Simple question, I hope. I've built a variety of prefabs for an isometric shooter game (hazards, enemies, health indicator bars, popup texts, shots, explosions). All of these prefabs were constructed with default rotations appropriate for the gameplay. My problem is that Instantiate() will overwrite the default rotation of the prefab with whatever is specified as the rotation parameter. So I'm left with hard coded rotations in my Instantiate() calls to get things oriented correctly in the X Z plane. (0,180,0) and (90,0,0) are common ones. I'd much prefer to Instantiate prefab gameObjects consistently with "no change to their default rotation," but I'm not sure how to accomplish this. Thanks for the help, Mike.
|
0 |
Autonomous robot moving from 1 object to the next object This question falls in line with my last question Unity 3D create autonomous moving robot in house first person camera movement What I have I have a 3D model of a house a first person camera with movement through the house a robot that autonomously moves. What I want I want the autonomously moving robot to search the house for certain objects. I have placed 4 guns (same model) in the house. This is the code I have now. This works for 1 gun not multiple game objects using UnityEngine using System.Collections public class MoveTo MonoBehaviour public Transform goal void Start () NavMeshAgent agent GetComponent lt NavMeshAgent gt () agent.destination goal.position What I want extra If possible, I want it to communicate with the person navigating the "game" with the first person camera. For example, if it finds a gun, I want it to say to the person "playing" the game I found a gun. If it finds the next one I found 2 guns I found 3 guns etc etc. For that, I used the following code for the player using UnityEngine using System.Collections public class UGV MonoBehaviour public Player player assign this variable in the inspector, or using another method public void CallMethodBInPlayer() if(player ! null) player.MethodB() public void MethodA() do something (Robot) And the same for the robot (but changed accordingly). I will be honest with you that I have very little understanding of programming or Unity. I want you to know I've been looking for an answer for many hours but even though the idea might be too complicated for me just yet, I still hope you can (and want) to help me )
|
0 |
Is Update() called on the very first frame in Unity? I'm calling Time.frameCount inside Update() and then immediately Debug.Break() to pause the simulation before Update() is finished. This of course happens (supposedly) on the very first frame, and yet Time.frameCount returns 1, as if one frame had already been rendered by at that point. Also, I'm calling Time.deltaTime the same way, on the first frame inside Update(), and it returns a value too, as if a previous frame had been rendered and took X milliseconds. Considering Time.deltaTime returns the value of the "time it took to complete the last frame", and I'm calling it on the first frame and it's returning a value, is there an "invisible" first frame that Update() doesn't run on? I couldn't find any reference to this specific issue on the Unity docs.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.