_id
int64
0
49
text
stringlengths
71
4.19k
0
Why in the dialogue system it's showing in the conversation only 2 sentences and not the whole 3 sentences? The first script the manager is attached to new empty gameobject I want the conversation to start automatic when running the game so i'm calling the method TriggerDialogue in the manager using System.Collections using System.Collections.Generic using UnityEngine public class DialogueManager MonoBehaviour public DialogueTrigger dialoguetrigger private Queue lt string gt sentences Use this for initialization void Start () sentences new Queue lt string gt () dialoguetrigger.TriggerDialogue() DisplayNextSentence() public void StartDialogue(Dialogue dialogue) Debug.Log("Starting conversation with " dialogue.name) sentences.Clear() foreach(string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() public void DisplayNextSentence() if (sentences.Count 0) EndDialogue() return string sentence sentences.Dequeue() Debug.Log(sentence) void EndDialogue() Debug.Log("End of conversation.") Next the DialogueTrigger using System.Collections using System.Collections.Generic using UnityEngine public class DialogueTrigger MonoBehaviour public Dialogue dialogue public void TriggerDialogue() FindObjectOfType lt DialogueManager gt ().StartDialogue(dialogue) Last the Dialogue using System.Collections using System.Collections.Generic using UnityEngine System.Serializable public class Dialogue public string name TextArea(3, 10) public string sentences In the editor I filled the all 3 TextAreas each one with a sentence. Hello world Hi everyone I have woke up When running the game it's showing only to the Hi everyone it's not showing the I have woke up. And it also not showing the "End of conversation." in the log.
0
Overcoming float limitations for planet sized worlds in Unity As far as I know, going further than 1M units from the world origin in Unity is hardly possible due to floating point precision issues. Making a world more than 1M units in radius would require either using double vars for coordinates or utilizing some space division technique to divide a massive scene into hierarchical chunks with the smallest of them being around 10 000 units, i.e. each world space position would be expressed by the chunk hierarchy the object's in and a bunch of float vars representing its local position (and possibly rotation and scaling) inside the last chunk. Either way, doing this would require implementing a completly new coordinate system, so I'd like to know whether or not that is possible in Unity, and if so, how may I make it work with existing Unity systems like physics and so on. P.S I can't just move the world into origin as the player moves since I want to have things going on simultaneously around the planet. Thanks!
0
How is entering cover animation done for cover system? I am trying to create a cover system for my 3rd person shooter game in Unity. My implementation is a basic one On Player enter Trigger Player move to preset cover position Player play Enter Cover animation (eg dash to cover) This is fine without root motion enabled, when it is enabled (so the movements look natural), instead of dash amp stop behind the cover, the Player will dash and stuck himself inside the cover (due to root motion). So I am curious, what is a good way to do the animation for cover system?
0
Draw GUI.Button on certain position on a scrollable background Problem is in a 2D game I have a large background around 2 screens wide. And on there I got 4 buttons placed on top of background all over complete width. Now when I swipe of move my mouse around I scripted that the camera will move with it. So for the GUI.Buttons (Unity4.5) to stick on their place I used a variable drawX drawX Camera.main.transform.position.x 100 The 100 is for calculating it to pixels. I then add this to my buttons when drawing. scaleX Screen.width 1920f scaleY Screen.height 1200f if (GUI.Button(new Rect((500 drawX) scaleX, 700 scaleY, 325 scaleX, 425 scaleY), "")) Now the problem is that under 1920x1200 my target resolution everything works exactly pixel perfect. But when changing the resolution or aspect ratio to something else the drawX increases to much or not enough so the buttons don't move on the same pace as they did in the 1920x1200 version. Somebody got the solution for me?
0
How I randomise a list of audio clips in Unity and remove it from the list once the clip is finished? I have 4 audio clips. When I play a press a certain button in Unity, the data is sent to MAX MSP and the audio is played. I created a list a signals (As shown below in the code). What I want is that, the signal list is randomised. The user presses a button to listen to the audio (which works fine). Once the clip is finished the user presses Next Trial button. Once the Next Trial is pressed. The previous clip is removed from the list. Once all the clips are finished. A message is displayed in the Debug.Log( quot All trials finished quot ). I have the following problems One of the audio clips is repeated again. It appears that the audio clips are not removed from the list. How do I write the audioclip index to a csv file? Code public class SignalToMax MonoBehaviour private static int localPort private string IP define in init public int port 8050 define in init quot connection quot things IPEndPoint remoteEndPoint UdpClient client experiment case public string experimentCase quot A quot string strMessage quot quot public List lt int gt signals public static int stimIndex void Start() NextTrial GameObject.FindGameObjectWithTag( quot NextTrial quot ).GetComponent() signals new List lt int gt 1, 2, 3, 4 define IP quot 127.0.0.1 quot port 8050 Senden remoteEndPoint new IPEndPoint(IPAddress.Parse(IP), port) client new UdpClient() NextTrial.onClick.AddListener(Advance Trial) void Advance Trial() int signalIndex Random.Range(0, signals.Count) int currentSignal signals signalIndex stimIndex currentSignal signals.RemoveAt(signalIndex) string text signalIndex.ToString() byte data5 Encoding.ASCII.GetBytes(text) client.Send(data5, data5.Length, remoteEndPoint) Debug.Log( quot lt color magenta gt Current source signal is lt color gt quot currentSignal) if (signals.Count gt 0) Debug.Log( quot lt color blue gt Signal count before removal was lt color gt quot signals.Count) Debug.Log( quot lt color yellow gt Source signal removed lt color gt quot ) else Debug.Log( quot lt color green gt All Trials finished lt color gt quot )
0
Flatten transform hierarchy at build time Nested hierarchies cause a performance overhead when they include moving objects. Every time a GameObject moves, altering its transform, we need to let every game system that might care about this know. Rendering, physics, and every parent and child of the GameObject needs to be informed of this movement in order to match. As the scope of a game increases, and the number of game objects skyrockets, just the overhead of sending out all these messages can become a performance problem. However, nested hierarchies are useful in organising a scene and keeping logical groups of gameobjects separate. What options exist to save performance whilst keeping the hierarchy? Is there any pre existing solution to flatten a hierarchy when building only?
0
How to draw a 2D cross section of a 3D object? I am creating a game where I only want the user to see the 2D intersection of a plane with a 3D object. The goal of the game is to move this plane to a certain position and rotation, which gives a certain 2D shape. Here is a link to a website which illustrates the 2D slices of a 3D object. How do I approach this if I only want the player to see the slice. Just to be clear, the solution does not necessarily have to be in 3D, since the ui for the player is going to be 2D anyway
0
RigidBody or Character Controller for Zero Gravity first person shooter I am developing a single person, first person shooter that takes place in space. I want to be able to simulate zero gravity. Should I use a Rigid Body or a Character Controller?
0
Create a 2d circular maze How can I create a 2d procedurally generated circular maze like the following picture
0
Slowmotion except main player? My script works fine except I don't know how to not let the slow motion affect the main player. public GameObject player void Update () if (Input.GetKeyDown(KeyCode.A)) Time.timeScale 0.5 Time.fixedDeltaTime 0.02F Time.timeScale if (Input.GetKeyDown(KeyCode.Z)) Time.timeScale 1.0f
0
Unity Editor Scene View does not match built executable I'm trying to make my game resolution independent. I'm using Unity's 4.6 UI, and I've got custom resolutions defined at 1280 x 720, 1600 x 900, and 1920 x 1080. In editor, if I swap between any of these resolutions, the observed scene doesn't change. It looks like this I then build an executable (set to only allow 16x9 resolutions), and run this scene. On 1280 x 720 (as selected from the resolution dialog), I get this While on 1920 x 1080 (as selected from the resolution dialog), I get this Which matches the editor view. (Ignore the character sprites those are in worldspace on a separate camera and aren't relevant to this question). What is it about the executable that causes lower resolutions to be "zoomed in" like this, even if that lower resolution is the Reference Resolution for the Canvas Scaler?
0
Small health bar above entity is drawn differently when the entity is rotated differently Here is a simple positioning code for my health bar transform.position Camera.main.WorldToScreenPoint(target.position 0.2f target.up) Here is the prefab HealthBar is middle center anchored, and 0.5, 0.5 pivoted, Background and Fill are stretched and 0.5, 0.5 pivoted, but background is Left, Right, Top, Bottom 1 positioned. Here is how it should look (all images are zoomed in) And here is a video about the entity rotating around https i.imgur.com EOzFEvt.mp4 2 example rotations, in which the health bar is drawn incorrectly (see the border of the bar) Why? Edit Another interesting artifact If I'm moving the camera up, the healthbars are offsetted up a bit, and if I start moving down, it's instantly offsetted down, with left and right the same, etc. As soon as I stop, it's at the correct position, but as soon as I start moving, it becomes offsetted to the direction I'm moving. See gif https i.imgur.com K8mwzTW.mp4 Fix for this Place it in LateUpdate.
0
How do you write an unlit shader which supports Ambient Occlusion? For performance reasons, a scene might use Unlit shaders only. Is there an Unlit shader which supports Ambient Occlusion? What is the best way to achieve this look, for moving and static objects, while prioritising performance?
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
When serializing a class, can its fields take their defaults from the Unity editor? Can I have a custom serialized class whereby I set a value in the editor and that value persists into runtime, as happens with serialized monobehaviour fields? Currently it sets itself to 0 or a default hard coded from within the class. I noticed that using a struct actually works but using a struct breaks the events used in my actual use case (included below). Example code public class Class1 MonoBehaviour this variable can be set in the editor and persist into run time SerializeField private float testVar1 this variable can not SerializeField private Class2 class2 private void Start() class2 new Class2() Serializable public class Class2 SerializeField private float testVar2 My use case Serializable public class EditorFloat SerializeField public float value public EventProperty lt float gt eventProperty public EditorFloat(EventProperty lt float gt eventProperty) this.eventProperty eventProperty Object.FindObjectOfType lt CentralParams gt ().OnUiChange Update this.eventProperty.OnChanged UpdateEditor public void Update() eventProperty.Value value public void UpdateEditor(float valueFromEventProperty) value valueFromEventProperty Thanks!
0
Storing Type Game Data Within A Unity 3D Game Using An Offline Flatfile Database I've read several documents on how to manage game type data Would it be better to use XML JSON Text or a database to store game content? How to choose how to store data? Im developing an offline RPG game in Unity3D. I've made online games before, but with online we had an edge for the database. For the online game we used a MySQL database each time the player loaded the game, they would download the database (JSON setup) and we would parse it on the client side and it would be good to go. However for an offline RPG I don't have the luxury of storing my game type data online. To be clear when I say type data I mean things like Monster tables Item tables Ability tables etc What I liked about the MySQL database was that it was tabluar and I could edit rows and columns easily and not need to create hundreds of classes subclasses to manage the type data. My question is how can I mimic the MySQL database in Unity3D? I considered using an excel file but I feel that would be so easy for the user to hack. Just change the excel data and boom, you've hacked the game. Is there a way I can create an offline (secure ish) flatfile database that will let me avoid having to create tons of type data class files to manage all my game data?
0
Displaying Trajectory Path How can I display trajectory path exactly as in this image? I have used void OnDrawGizmos, but that only displays trajectory in the editor and without any arrows like shown below. Trajectory with void OnDrawGizmos Script public Transform someObject object that moves along parabola. float objectT 0 timer for that object public Transform Ta, Tb transforms that mark the start and end public float h desired parabola height Vector3 a, b Vector positions for start and end void Update () if ( Ta amp amp Tb ) a Ta.position Get vectors from the transforms b Tb.position if ( someObject ) Shows how to animate something following a parabola objectT Time.time 1 completes the parabola trip in one second someObject.position SampleParabola( a, b, h, objectT ) void OnDrawGizmos () Draw the parabola by sample a few times Gizmos.color Color.red Gizmos.DrawLine( a, b ) float count 20 Vector3 lastP a for ( float i 0 i lt count 1 i ) Vector3 p SampleParabola( a, b, h, i count ) Gizmos.color i 2 0 ? Color.blue Color.green Gizmos.DrawLine( lastP, p ) lastP p region Parabola sampling function lt summary gt Get position from a parabola defined by start and end, height, and time lt summary gt lt param name 'start' gt The start point of the parabola lt param gt lt param name 'end' gt The end point of the parabola lt param gt lt param name 'height' gt The height of the parabola at its maximum lt param gt lt param name 't' gt Normalized time (0 gt 1) lt param gt S Vector3 SampleParabola ( Vector3 start, Vector3 end, float height, float t ) float parabolicT t 2 1 if ( Mathf.Abs( start.y end.y ) lt 0.1f ) start and end are roughly level, pretend they are simpler solution with less steps Vector3 travelDirection end start Vector3 result start t travelDirection result.y ( parabolicT parabolicT 1 ) height return result else start and end are not level, gets more complicated Vector3 travelDirection end start Vector3 levelDirecteion end new Vector3( start.x, end.y, start.z ) Vector3 right Vector3.Cross( travelDirection, levelDirecteion ) Vector3 up Vector3.Cross( right, travelDirection ) if ( end.y gt start.y ) up up Vector3 result start t travelDirection result ( ( parabolicT parabolicT 1 ) height ) up.normalized return result
0
How to play sound in WebGL build in Unity? I have a project that works fine when I build for windows, but doesn't work when I switch platform to WebGL. The SerializeField AudioClip variables in the inspector are all 'missing', even after I check 'override for WebGL' convert to AAC. And when I try to link any audio file to an AudioClip within a WebGL build in the inspector, it doesn't seem to work. How do I get sound to play within WebGL? To recreate the problem Switch platform to WebGL. Create a new Script in any recent unity version, then add a SerializeField AudioClip x. Put that script on a new gameobject and try to link an audio asset to it (default import settings, however don't forget to check 'override for WebGL' to AAC, otherwise you will get compiler errors when you switch platform).
0
Add picture in the Hierarchy view in Unity How can I add a picture in the Hierarchy view in Unity? For example, Dragon bones does it automatically. Here it is As you can see there is a picture on the right of the gameObject name.
0
Getting player cube to move left or right in relation to camera based on camera's rotation Right now I'm trying to make the player cube move left, right, up and down in relation to the camera's rotation and position. I figured what I could do is create an empty game object, make the main camera the parent, and then get the vector pointing from the camera's child to another game object that follows the cube's exact position, and that would give me the direction the cube should roll towards. I have my example in profile view, but in 3D view the camera should be facing the cube with the cube at the center. So I have the following line of code code Vector3 forwardVector (position1.transform.position position2.transform.position).normalized If you look at the image on the right hand side, I Debug.GetLine'd the resulting vector from the cube's position and ended up with a vector pointing down. In theory though, it should be pushing off to the right hand side. Here's the rest of the code Vector3 perpendicularVector Vector3.Cross (Vector3.up, resultant).normalized if (Input.GetKey (KeyCode.UpArrow)) cube.rigidbody.AddForce ( forwardVector moveSpeed) if (Input.GetKey(KeyCode.DownArrow)) cube.rigidbody.AddForce ( forwardVector moveSpeed) if (Input.GetKey (KeyCode.LeftArrow)) cube.rigidbody.AddForce ( perpendicularVector moveSpeed) if (Input.GetKey (KeyCode.RightArrow)) cube.rigidbody.AddForce ( perpendicularVector moveSpeed) As a result, when I press the up arrow key, I end up with the cube flying upwards toward the sky, and the down key brings it back down towards the plane, but my intention is for the vector to move along the XZ plane. Also, with this line of code, I was hoping to get the line perpendicular to my intended vector and Vector3.up, but I naturally get wonky results from that. Vector3 perpendicularVector Vector3.Cross (Vector3.up, resultant).normalized If there's an easier method to achieving my goals, that's fine, but it would be nice too to figure out why the vector is pointing down instead of to the right. It's also might be worth noting that the camera already successfully rotates around the player cube.
0
What's a viable way to get public properties from child objects? I have a GameObject (RoomOrganizer in the picture below) with a "RoomManager" script, and one or more child objects, each with a 'HasParallelagram' component attached, likeso I've also got the following in the aforementioned "RoomManager" void Awake () Rect tempRect HasParallelogram tempsc foreach (Transform child in transform) try tempsc child.GetComponent lt HasParallelogram gt () tempRect tempsc.myRect blockedZoneList.Add(new Parallelogram(tempRect)) Debug.Log(tempRect.ToString()) catch( System.NullReferenceException) Debug.Log("Null Reference Caught") HasParallelgram is an empty script with a public Rect set in the editor and nothing else. Unfortunately, attempting to assign tempRect tempsc.myRect causes a null pointer at run time. I've done some more digging, and the reason for the null pointer is relatively simple the RoomManager script gets woken ("Awake") before the HasParallelagram script gets instantiated ("Start"). It's an issue of timing I need to wait until all objects have been instantiated before calling the RoomManager. Does Unity support a means of doing that? What's the proper way to get a child's component?
0
How can I move an object over linerenderer lines positions? I have 4 cubes the first 3 cubes connected with two lines one of the lines is curved. The fourth cube I want to move over the lines. The lines is built using linerenderer and in the linerenderer there are 397 positions. I created a small script that move an object over the positions. I checked and I have in the array 397 positions and the loop get to 397 but the object (Cube (3)) never moving all the positions only some. Or maybe the positions I get are not the same in the linerenderer ? This screenshot show some of the positions in the linerenderer this is the positions I want the object to move on Why the object is not moving over all the positions , only on some ? And this is the script I created that should move it using System.Collections using System.Collections.Generic using UnityEngine public class MoveOnCurvedLine MonoBehaviour public LineRenderer lineRenderer public GameObject objectToMove public float speed private Vector3 positions new Vector3 397 private Vector3 pos private int index 0 Start is called before the first frame update void Start() pos GetLinePointsInWorldSpace() Vector3 GetLinePointsInWorldSpace() Get the positions which are shown in the inspector var numberOfPositions lineRenderer.GetPositions(positions) Iterate through all points, and transform them to world space for (var i 0 i lt numberOfPositions i 1) positions i transform.TransformPoint(positions i ) the points returned are in world space return positions Update is called once per frame void Update() if(index lt pos.Length 1) objectToMove.transform.position pos index Time.deltaTime speed index Now I checked using a breakpoint the first position in the linerender at index 0 is X 30.57, Y 6.467235, Z 4.98 But in my script in the pos array I see that in index 0 the position is X 30.6, Y 6.5, Z 5.0 And the result is that the object that move Cube(3) is moving only some of the way and also it's not exactly on the line Why the object is not moving over all the positions , only on some ? Something is wrong in my script with getting the right positions from the linerenderer and maybe also the loop and the move is wrong. I can't figure out ho to do it.
0
problem on enable and disable GameObject I'm trying to enable and disable GameObject (canvas) using this code public int canvaslevel 1 public GameObject one public GameObject two public GameObject three void Update() if(canvaslevel 1) one.SetActive(true) two.SetActive(false) three.SetActive(false) if(canvaslevel 2) one.SetActive(false) two.SetActive(true) three.SetActive(false) if(canvaslevel 3) one.SetActive(false) two.SetActive(false) three.SetActive(true) but it doesn't work!!! error Cannot implicitly convert type int' tobool'
0
How to make a game object scale up from another game object I have a GameObject. I'm trying to make another GameObject grow in scale from touching this GameObject, and when a set amount of scale is reached, destroy this GameObject. My problem is that when I access ScaleUp, it dosn't add any scale to the other GameObject. How do I scale another GameObject? Here is my ScaleUp script using UnityEngine using System.Collections public class ScaleUp MonoBehaviour public GameObject Player public PlayerMovement PlayerScript private float playerScaleX private float playerScaleY public float scaleUp 10.0f void Start() Player GameObject.FindGameObjectWithTag ("Player") PlayerScript Player.GetComponent lt PlayerMovement gt () playerScaleX Player.transform.localScale.x playerScaleY Player.transform.localScale.y void OnTriggerEnter2D (Collider2D other) if (other.tag "Player") playerScaleX scaleUp playerScaleY scaleUp Debug.Log ("GROW")
0
Can both High poly model go with a low poly scene? I'm in the process of developing a game, and I've found a model that would go perfectly for the character. However, the scentre I already have is low poly and I can't find a good enough high poly to go with it. So tell me whether or not I should I should carry on with the art I have or find a low poly model.
0
How to create a wavy beam? I want to implement a wavy laser beam similar to the Proton Backpack in Enter the Gungeon. https youtu.be wl o6gbMqFM?t 58 It's easy enough to draw a line from one point to another, but how to get the undulating curviness and the lighting effects? I am working in Godot, but I could easily adapt techniques from Unity, if you know them, since Godot has similar resources. I asked a version of this question in a Godot forum, but am also asking it here
0
Lightmapped prefabs for procedural content I'm doing a game with procedural content from handmade prefabs, but I ran into a problem as Unity bakes the scene instead of objects when lightmapping with Beast. So when the prefabs are instanced they are without lightmaps. Is there a way to get lightmaps for dynamically created prefabs with Unity's built in lightmapper?
0
How can I change the script so it will not be with a while loop inside Update or using coroutine instead? The script is working fine as it is and I don't fell any performance problems and yet I wonder if it's a good idea to run a while loop inside the Update function ? The idea is to be able to move an object over a curved lines with a lot of positions in any speed. So I'm calculating how much positions there is next each time and it's working fine I just wonder about the while in the update. using System using System.Collections using System.Collections.Generic using System.Linq using UnityEngine using UnityEngine.AI public class MoveOnCurvedLines MonoBehaviour public LineRenderer lineRenderer public float speed public bool go false public bool moveToFirstPositionOnStart false private Vector3 positions private Vector3 pos private int index 0 private bool goForward true private List lt GameObject gt objectsToMoveCopy new List lt GameObject gt () Start is called before the first frame update void Start() pos GetLinePointsInWorldSpace() if (moveToFirstPositionOnStart true) transform.position pos index Vector3 GetLinePointsInWorldSpace() positions new Vector3 lineRenderer.positionCount Get the positions which are shown in the inspector lineRenderer.GetPositions(positions) the points returned are in world space return positions Update is called once per frame void Update() if (go true) Move() void Move() Vector3 newPos transform.position float distanceToTravel speed Time.deltaTime bool stillTraveling true while (stillTraveling) Vector3 oldPos newPos newPos Vector3.MoveTowards(oldPos, pos index , distanceToTravel) distanceToTravel Vector3.Distance(newPos, oldPos) if (newPos pos index ) Vector3 comparison is approximate so this is ok when you hit a waypoint if (goForward) bool atLastOne index gt pos.Length 1 if (!atLastOne) index else index goForward false else going backwards bool atFirstOne index lt 0 if (!atFirstOne) index else index goForward true else stillTraveling false transform.position newPos
0
How does Unity's QualitySettings.masterTextureLimit work? I'm trying to get to the bottom of how masterTextureLimit works, but my results have been inconsistent so far. I created a massive sprite (8192x8192), and I'd like to resize it at runtime to save performance. The idea is to start with large sprites and then resize based on the monitor's resolution. Here's what happens at different settings Texture import size 8192, masterTextureLimit 0, mipmaps off 2ms Texture import size 8192, masterTextureLimit 0, mipmaps on 1.5ms Texture import size 8192, masterTextureLimit 1, mipmaps on 1.5ms Texture import size 4096, masterTextureLimit 0, mipmaps off 0.9ms Texture import size 4096, masterTextureLimit 0, mipmaps on 0.9ms Texture import size 4096, masterTextureLimit 1, mipmaps on 0.83ms Looking at these results, I have a couple of questions If masterTextureLimit is supposed to halve the texture resolution, why did it not affect performance while setting texture size to 4096 did? Why did turning mipmaps on improve performance at 8192 texture size but not at 4096? My camera is orthographic, and it's only 1 unit away from the sprite.
0
Zoom into character upon collision When a character collides with an object in my game, there is a slow motion effect. That's coool, but how would I zoom into a sprite when it collides with another object? Here is my code currently... using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class GameManager MonoBehaviour public float slowness 2f public int index private AudioSource hitSource public Vector3 Target public Camera Cam public float Speed 0.012f public void Start() Cam Camera.main public void EndGame() Application.targetFrameRate 300 StartCoroutine(RestartLevel()) hitSource GetComponent lt AudioSource gt () IEnumerator RestartLevel() Cam.orthographicSize Mathf.Lerp(Cam.orthographicSize, 3, Speed) Cam.transform.position Vector3.Lerp(Cam.transform.position, Target 1 , Speed) Time.timeScale 1f slowness Time.fixedDeltaTime Time.fixedDeltaTime slowness yield return new WaitForSeconds(1.5f slowness) Time.timeScale 1f Time.fixedDeltaTime Time.fixedDeltaTime slowness SceneManager.LoadScene(2) private void OnCollisionEnter(Collision collision)
0
Why does Unity let you install iOS Build Support on Windows? When installing Unity on a Windows machine, you are allowed to select "iOS Build Support" as one of the components to install. However, it is not possible to make an iOS build from Windows. Why is this package available on Windows? What does it offer?
0
How to store information into the tile? I have made a map via TilePallete tool. Now I want to store information in certain tile. How I can do this? ForEx I'm hittin a certain tile and I need it to have info about health remaining. For first hit I change a tile. For second I set it to null.
0
Separate data tables for different item types? I have two types of items in my game, consumables, and equipment. For my database, should I store them in two different tables, or all in one big items table?
0
90 CPU on Profile Editor Throttle mainMessageLoop I have a big problem in my Unity game, in almost every sc ne of my game, my editor is laggy, when I record Porfile Editor deep profile editor, here is the result I have no idea what is this throttle MainMessageLoop, what can I do ? Thanks you !
0
How to convert Blender rotation angles to Unity rotation angles? I add news cameras in my game. I have a problem with rotation, the result is not alway the same as in Blender. I tried lot of ideas but today I do not have anymore. Cameras 1, 2, 4 good rotation Cameras 3, 5 bad rotation Cam 1 (Blender) Cam 1 (Unity) the fov is different Cam 4 (Blender) Cam 4 (Unity) the fov is different Cam 3 (Blender) Cam 3 (Unity) rotation is very different Cam 5 (Blender) Cam 5 (Unity) rotation is very different This problem appears if camera orientation is "vertical" Do you have a turn arround, a solution for me? My code using System.Collections using System.Collections.Generic using UnityEngine public class rotation cams MonoBehaviour private Vector3 cams loc private Vector3 cams rot void Start() cams loc new Vector3 5 cams rot new Vector3 5 cams loc 0 new Vector3(79.7771f, 21.7574f, 109.795f) cams rot 0 new Vector3(95f, 45f, 200f) cams loc 1 new Vector3(78.0048f, 21.9854f, 110.314f) cams rot 1 new Vector3(87.0958f, 1.34464f, 160.515f) cams loc 2 new Vector3(78.3154f, 18.9402f, 111.654f) cams rot 2 new Vector3(169f, 59.3947f, 110.242f) cams loc 3 new Vector3(78.023f, 18.7094f, 111.375f) cams rot 3 new Vector3(89.4105f, 16.7202f, 128.303f) cams loc 4 new Vector3(79.5798f, 19.7249f, 111.743f) cams rot 4 new Vector3(55.0461f, 74.0926f, 220.475f) int i 0 foreach (Vector3 vector loc in cams loc) string camName "cam" i.ToString() GameObject currentCam AddCamera(camName) currentCam.GetComponent lt Transform gt ().position new Vector3(cams loc i .x, cams loc i .z, cams loc i .y) Vector3 objRotation new Vector3(cams rot i .x 1, cams rot i .z 1, cams rot i .y 1) objRotation.x 90f currentCam.GetComponent lt Transform gt ().eulerAngles objRotation i 1 void Update() private GameObject AddCamera(string name) GameObject gizmoPhoto GameObject.Instantiate(GameObject.Find("cam")) gizmoPhoto.name name return gizmoPhoto
0
Unity3D Button Slicing Problem I'm having trouble getting my button to appear correctly, as you can see in the image below, the right and top sides are stretched out and not displaying properly. I cannot figure out if this is a problem with the image itself or something wrong in the way I'm setting up the button. Here are the settings in the inspector window Here is the original image UPDATE So everything looked fine when I just opened up Unity, so I tried to figure out what I did last time for it to make this switch. It happens when I build and export the scene to my Android device.
0
How to open two Animator views in Unity? How can I open two Animator views in Unity editor? What I tried so far is to lock an Animator view and go to Window Animator. That did not help.
0
(Unity) Shortest way to instantiate an object and obtain it script Normally I use ScriptName script ((GameObject)Instantiate( Resources.Load("Prefab"), new Vector3(x, y, z), Quaternion.identity )).GetComponent lt ScriptName gt () It is a little too long and too much of brackets, so I wondering if there is any other way to get instantiated object's script without break it in two statements.
0
Unity RTS Single Selection Problem I am trying to build an RTS game and I have managed to form a way to select a unit using Raycast and the tag system. I made it so that if the object the ray falls onto is of tag "TankUnit" Make so and so variable true and allow it to move to another place. However, Units of the same tag even when not selected also move. How do I fix this problem? The script is bound to each unit. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.AI public class UnitController MonoBehaviour bool clicked false public float speed 10f public float rotationSpeed 10f public LayerMask groundLayer public NavMeshAgent playerAgent Update is called once per frame void Update() if (Input.GetMouseButton(0)) Debug.Log("Clicked") FindClickPos() if (Input.GetMouseButton(1) amp amp clicked true) Debug.Log("I clicked right mouse") Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if (Physics.Raycast(ray, out hit)) MoveTo(hit) private void FindClickPos() RaycastHit hitInfo new RaycastHit() bool hit Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo) if (hit true) Debug.Log("I hit " hitInfo.collider.name) if (hitInfo.collider.tag "TankUnit") Debug.Log("I hit" hitInfo.collider.tag "!") clicked true else Debug.Log("I didnt hit a unit ") clicked false else Debug.Log("I didnt hit anything...") clicked false void MoveTo(RaycastHit hit) Debug.Log("Position " hit.point) playerAgent.SetDestination(hit.point)
0
GameObject not exiting through leftScreen I'm trying to wraparound game object so that, it exits through right screen and enters through left and vice versa. The code snippet below is what I'm working on. Vector3 Pos mainCam.WorldToScreenPoint(transform.position) Vector3 LS mainCam.ScreenToWorldPoint(new Vector3( 1, 0f, 0f)) Vector3 RS mainCam.ScreenToWorldPoint(new Vector3(1, 0f, 0f)) if (Pos.x gt Screen.width) transform.position new Vector3(LS.x, transform.position.y, transform.position.z) if (Pos.x lt 0) transform.position new Vector3(RS.x, transform.position.y, transform.position.z) So far, exit through right and re enter through left works, but the gameObject does not exit through the left screen, there seems to be a barrier preventing it, or maybe my parameters for the second if statement are wrong.
0
Unwanted rotations with transform.RotateAround I didn't tough i would have issues with this, but unfortunatly I did. I have a Character (which is more a pile of cube) with a body, a empty GameObject for each leg attached to the body with a join and 2 cubes for leg too. The body and the two empty gameobject are child of a Empty gamebject. The 2 cube that represent leg are both child of one of the empty gameObject. What I want to achieve is to rotate the leg around the position of its empty parent by doing this if(Input.GetKey("l")) l leg.transform.RotateAround(l leg.transform.parent.transform.position, new Vector3(1,0,0), 75 Time.deltaTime) unfortunatly, I only want it to rotate on x, but all of the axis are changing, which lead to unwanted rotation. Now, I know rotations aren't independant like translations, but I don't know how to fix this. If possible, i'd prefer to rotate locked joint via script but I have now idea how, I haven't seen anything about it when I looked up 2
0
Exclude removed objects from list counting? I want to count the number of objects on my list. But because I remove and add, my script keep count those empty elements. update This happen when I destroy the object when it inside the collider. This object does not get out from quot OnTriggerExit2D quot . public List lt GameObject gt Sorts public List lt GameObject gt ItemsInside public int NumSorts, NumItems Update is called once per frame void Update() NumSorts Sorts.Count NumItems ItemsInside.Count it doesn't give correct number void OnTriggerEnter2D(Collider2D other) if (other.CompareTag( quot Sort quot )) Sorts.Add(other.transform.gameObject) if (other.transform.name ( quot GameItem quot )) ItemsInside.Add(other.transform.gameObject) void OnTriggerExit2D(Collider2D otherOut) if (otherOut.CompareTag( quot Sort quot )) Sorts.Remove(otherOut.transform.gameObject) if (otherOut.transform.name ( quot GameItem quot )) ItemsInside.Remove(otherOut.transform.gameObject)
0
Touch a specific area on the screen in Unity 5 I am building a Roulette game in Unity 5. I want to place bets on a Roulette table when I touch specific areas on the screen with mouse(PC) and touch(mobile). For example when i touch Number 1 on the roulette table a bet should be placed on that number. I tried using box collider iwth trigger but I think thats for only colliders. Screenshot attached
0
Manually creating an instance of object derived from MonoBehaviour I'm currently "newing" an instance of a class I have that derives from MonoBehaviour and store it in a list. The value of this instance is "null" however, even though it has all the fields of my derived class in it so it passes as null in null checks. After more reading it seems it's a bad idea to manually new up an instance of an object that derives from MonoBehaviour. The class is an Actor class. I have a situation where enemy actors are 3D models in my scene and so I want them to derive from MonoBehaviour, but the player actors don't have world representations really. I just have a picture of them in the corner. Similar to Legend of Grimrock. I wanted the 1 Actor class since the data they need is all the same and I wanted to avoid having 2 classes for no seemingly reason other than not newing up a MonoBehaviour derived class. What are my options with this requirement when my player actors don't need MonoBehaviour but my enemy actors do but they all need to have the same properties?
0
error CS1069 The type name 'ZipArchive' could not be found in the namespace 'System.IO.Compression' When I build my project, which references the System.IO.Compression namespace, the build succeeds without issue inside Visual Studio. However, inside the Unity editor, I see the following error error CS1069 The type name 'ZipArchive' could not be found in the namespace 'System.IO.Compression'. This type has been forwarded to assembly 'System.IO.Compression, Version 4.0.0.0, Culture neutral, PublicKeyToken b77a5c561934e089' Consider adding a reference to that assembly. I added a csc.rsp file inside my Assets folder, with the following line r System.IO.Compression.FileSystem.dll Unfortunately, that did not resolve the issue. Here are the properties of the System.IO.Compression DLL that I reference inside Visual Studio How can I fix this error?
0
How to write a custom shader in Unity 3D that lights up a specific pixel or group of pixel? I'm making a FPS game in Unity, and I want the environment to light up as the player is shooting on his environment. The map would be entirely put in darkness at the beginning, but as the player shoots the environment, it would be rendered with its "real texture". So say I have a tree. First it is entirely black or greyish, but if I shoot somewhere, I would see some green. To accomplish this, I'm using a raycast to get the impact point and so I can access any renderer of the point that the player is shooting on. I guess the next step would be to write a custom shader to light the exact pixel that is shot. Do you have any idea how I could write this shader or another way of doing this effect? Regards
0
IL2CPP Vector.Dot inconsistency I get inconsistent results when I run this code as standalone Windows on Mono and IL2CPP backends. var a new Vector3( 1.26998901f, 0, 0.849998474f) var b new Vector3(20.0799999f, 1, 164.580002f) var dot Vector3.Dot(a, b) var mydot (float) ((double) a.x (double) b.x (double) a.y (double) b.y (double) a.z (double) b.z) Mono or Editor IL2CPP dot 165.394135 165.394119 mydot 165.394135 165.394135 Take a look at the dot result on IL2CPP backend in the table above. My mydot implementation should be equivalent to Vector3.Dot(Vector3, Vector3) according to dotPeek in Rider. Decompiled Vector3.Dot(Vector3, Vector3) lt summary gt lt para gt Dot Product of two vectors. lt para gt lt summary gt lt param name "lhs" gt lt param gt lt param name "rhs" gt lt param gt public static float Dot(Vector3 lhs, Vector3 rhs) return (float) ((double) lhs.x (double) rhs.x (double) lhs.y (double) rhs.y (double) lhs.z (double) rhs.z) Unity version 2018.4.12f1 What causes Vector3.Dot(Vector3, Vector3) to give a different result on IL2CPP?
0
translation and rotating at the same time and waiting before animation? I am having difficulties here. I want to move my character with the buttons and I want the character to rotate wherever he is going. Also I want to play an animation when there is no keys pressed. I am able to do that but I want the animation to play after 10 seconds of no key being pressed, and only once. Than after a movement that resets and again after 10 seconds of no key the animation plays. (The animation works but it happens right after I stop pressing a key and continuously.) IEnumerator Test() yield return new WaitForSeconds(10.0f) void Update() if (Input.GetKey(KeyCode.W)) counter Time.deltaTime transform.Translate((Vector3.forward) moveSpeed Time.deltaTime) Debug.Log("Pressing W key") if (Input.GetKey(KeyCode.S)) counter Time.deltaTime transform.Translate((Vector3.back) moveSpeed Time.deltaTime) Debug.Log("Pressing s key") if (Input.GetKey(KeyCode.A)) counter Time.deltaTime transform.Rotate(Vector3.down rotateSpeed) Debug.Log("Pressing a key") if (Input.GetKey(KeyCode.D)) counter Time.deltaTime transform.Rotate(Vector3.up rotateSpeed) Debug.Log("pressed D") if (!Input.GetMouseButton(1)) moveSpeed 20 if (!Input.anyKey) if (counter gt 2) StartCoroutine(Test()) anim.Play("Animation") counter 0 Debug.Log("A key or mouse click has been detected")
0
What's the proper way to use static objects and singletons in Unity? I have a GameObject in Unity, which I've attached this script to, in order to make it function as a Static Singleton using UnityEngine using System.Collections public class SceneStatics MonoBehaviour private static SceneStatics instance public static SceneStatics Instance get if (instance null) instance new GameObject ("SceneStatics").AddComponent lt SceneStatics gt () DontDestroyOnLoad(instance) return instance public void OnApplicationQuit () instance null I have two other scripts that I'd like to be able to access from scene to scene. What's the proper way to do that? Do I attach my Inventory and Room scripts to the same game object as the SceneStatics? If so, how do I access them? Can I go from SceneStatics.Instance to one of the other scripts directly via GetComponent? Alternatively, what happens if I add two child gameObjects (each containing one of the other scripts) to the SceneStatics? Or is the intended use that I simply make any other static items I need properties of the SceneStatics class? (I.e., add in a Public static Inventory and Public static Room attributes)?
0
How do I ensure consistent behaviour when using Unity's Collider2Ds for triggers and collisions? I am experiencing inconsistent behavior using Unity's 2D Physics engine and their Collider2Ds to detect collisions and triggers on my projectiles. I will classify it into two problems. The first is that occasionally the projectile will pass through walls objects it should collide with. The second is that occasionally the projectile will pass through enemies that it should hit without triggering. I will try to elaborate in detail below. A projectile is organized into a container Projectile GO and two children GO a PhysicsColliders GO and a HitBoxColliders GO. The PhysicsCollidersGO job is to hold the colliders that define the solid regions of the projectile using Collider2D components. It's GO is on a Projectile layer which is set to collide with other solid layers such as the ones my walls are on. Walls are static colliders. The HitBoxCollidersGO job is to define the a HitBox area. It's GO is on a HitBox layer and also uses Collider2D components that are set to be triggers. A HitScript on the GO listens for OnEnterTrigger. Projectiles are set in motion by setting the velocity of the RigidBody once upon firing. Here is a visual of the structure ProjectileGO PhysicsCollidersGO HitBoxCollidersGO Here are descriptions of the GameObjects and their components ProjectileGO RigidBody2D Component (collisionDetectionMode is set to Continious) PhysicsCollidersGO (Layer is set to Projectile) BoxCollider2D Component HitBoxCollidersGO (Layer is set to HitBox) BoxCollider2D Component (IsTrigger is set) HitScript Component Problem 1. Projectiles will sometimes not collide with walls solid objects etc... Problem 2. Projectiles will sometimes not trigger a hit. What could be causing these inconsistencies? How can ensure that collisions and triggers will consistently behave correctly?
0
Collider does not call callback functions I have a script that will create new GameObjects and will place it where the mouse is placed on the terrain. Now I need to have a check for collision on other already placed GameObjects on the field. I check different tutorials and documentation and cannot find a way to do this in code. My code looks like objectToPlace (GameObject)AssetDatabase.LoadAssetAtPath("Assets Game 3D Models Buildings " objectName ".fbx", typeof(GameObject)) objectToPlace.SetActive(true) objectToPlace.transform.localScale new Vector3(1, 1, 1) objectToPlace Instantiate(objectToPlace) objectToPlace.transform.Rotate(Vector3.right 90) BoxCollider collider (BoxCollider)objectToPlace.AddComponent(typeof(BoxCollider)) collider.isTrigger true In the same class as the above code I have OnTriggerEnter function. But that function is not called. How can I link the Collider to that function in Unity 5.6? I also tried using the Physics.CheckBox for checking if my new create gameObject does not collide to any other object. But without any succes.
0
Draw trajectory arc predictor in game I found this tutorial on youtube and it works pretty well, but I want to add more to it. How can I draw a smooth arc path in the game view (right now the path is only visible in the editor)? Here is the code public class BallLauncher MonoBehaviour public Rigidbody ball public Transform target public float h 25 public float gravity 18 public bool debugPath void Start() ball.useGravity false void Update() if (Input.GetKeyDown (KeyCode.Space)) Launch () if (debugPath) DrawPath () void Launch() Physics.gravity Vector3.up gravity ball.useGravity true ball.velocity CalculateLaunchData ().initialVelocity LaunchData CalculateLaunchData() float displacementY target.position.y ball.position.y Vector3 displacementXZ new Vector3 (target.position.x ball.position.x, 0, target.position.z ball.position.z) float time Mathf.Sqrt( 2 h gravity) Mathf.Sqrt(2 (displacementY h) gravity) Vector3 velocityY Vector3.up Mathf.Sqrt ( 2 gravity h) Vector3 velocityXZ displacementXZ time return new LaunchData(velocityXZ velocityY Mathf.Sign(gravity), time) void DrawPath() LaunchData launchData CalculateLaunchData () Vector3 previousDrawPoint ball.position int resolution 30 for (int i 1 i lt resolution i ) float simulationTime i (float)resolution launchData.timeToTarget Vector3 displacement launchData.initialVelocity simulationTime Vector3.up gravity simulationTime simulationTime 2f Vector3 drawPoint ball.position displacement Debug.DrawLine (previousDrawPoint, drawPoint, Color.green) previousDrawPoint drawPoint struct LaunchData public readonly Vector3 initialVelocity public readonly float timeToTarget public LaunchData (Vector3 initialVelocity, float timeToTarget) this.initialVelocity initialVelocity this.timeToTarget timeToTarget I found a way to Instantiate projectile along the path. Now I just need to know how to convert that line in debug mode to make it visible in game mode
0
Drawing rectangle around a target on screen I am just started with Unity and C . I need in my work to do rectangle on a scene. I have a 3D scene, say some warehouse and there is an object. Camera is animated and moving towards the object. Is it possible to draw a rectangle around the object on the camera screen while the camera is moving unless the object on the screen? The task is like keeping target in war flight games. This is my code, where I tried to draw rectangle anywhere using System.Collections using System.Collections.Generic using UnityEngine public class MY getting images MonoBehaviour Start is called before the first frame update public GameObject pallet public Camera color cam public Vector3 pos LineRenderer l void Start() pallet GameObject.Find("PalletWood01") l pallet.AddComponent lt LineRenderer gt () List lt Vector3 gt ps new List lt Vector3 gt () ps.Add(new Vector3(0, 0)) pos pallet.transform.position ps.Add(new Vector3(10,10)) l.startWidth 1f l.endWidth 1f l.SetPositions(ps.ToArray()) l.useWorldSpace true Finding camera in a scene tag needed camera, for example "Player", and then GameObject.FindWithTag("Player").GetComponent lt Camera gt () Tag the camera another way for deployment color cam GameObject.FindWithTag("Player").GetComponent lt Camera gt () pos color cam.transform.position pos pallet.transform.position Debug.DrawLine(Vector3.zero, new Vector3(0, 0, 5), Color.red) Debug.Log(pos) Update is called once per frame void Update() Debug.Log(pos) pos color cam.transform.position Debug.Log(pos) The scene now looks like on the image above I want 2d rectangle around the pallet drawn on the screen.
0
How can I make the objects to move at the same speed as the lines? void Update() if (animateLines) counter for (int i 0 i lt allLines.Length i ) Vector3 endPos allLines i .GetComponent lt EndHolder gt ().EndVector Vector3 startPos allLines i .GetComponent lt LineRenderer gt ().GetPosition(0) Vector3 tempPos Vector3.Lerp(startPos, endPos, counter 500f speed) allLines i .GetComponent lt LineRenderer gt ().SetPosition(1, tempPos) instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, counter 500f speed) else counter 0 foreach (GameObject thisline in allLines) thisline.GetComponent lt LineRenderer gt ().SetPosition(1, thisline.GetComponent lt LineRenderer gt ().GetPosition(0)) The lines are LineRenderer. void SpawnLineGenerator(Vector3 start, Vector3 end, Color color) GameObject myLine new GameObject() myLine.tag "FrameLine" myLine.name "FrameLine" myLine.AddComponent lt LineRenderer gt () myLine.AddComponent lt EndHolder gt () myLine.GetComponent lt EndHolder gt ().EndVector end LineRenderer lr myLine.GetComponent lt LineRenderer gt () lr.material new Material(Shader.Find("Particles Alpha Blended Premultiply")) lr.startColor color lr.useWorldSpace false lr.endColor color lr.startWidth 0.1f 0.03f lr.endWidth 0.1f 0.03f lr.SetPosition(0, start) lr.SetPosition(1, start) So I have lines each new gameobject have a LineRenderer component and inside Update I'm animating the lines with some speed. Now I want to move the instancesToMove (GameObject ) with the same speed as the lines but the instancesToMove are moving much slower then the lines. I tried instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, speed) Then instancesToMove i .transform.position Vector3.MoveTowards(endPos, startPos, speed Time.deltaTime) But it's never moving with the same lines speed.
0
Encapsulating parameterised prefabs I'm currently using the following general pattern for most of my configurable components (i.e. MonoBehaviours) public class MyComponent MonoBehaviour Configurable fields SerializeField private bool someParameter SerializeField private int anotherParameter Fake constructor to act as a replacement for GameObject.AddComponent with additional parameters. public static MyComponent AddTo(GameObject gameObject, bool someParameter, int anotherParameter) var myComponent gameObject.AddComponent lt MyComponent gt () myComponent.someParameter someParameter myComponent.anotherParameter anotherParameter return myComponent Public properties and other methods ... This works around the lack of constructors for MonoBehaviours but still encapsulates the parameters in such a way, that they can only be set at the time the object is created, or through the Inspector (which is effectively the same thing once the game is built). Unfortunately, this approach doesn't help once I want to use my component inside a prefab. When I instantiate the prefab, the component has already been created, and I can no longer touch those parameters. And as far as my google fu can tell, there's no way to pass parameters into prefab instantiation (much like there isn't a way to pass a parameter into AddComponent). It seems like everyone just instantiates their prefabs and then fiddles with some public properties to configure them. So the question is, is there any way to set things up, such that I can configure some fields on my prefabs, but without exposing them publicly and breaking encapsulation? (I realise that I could add a similar static "factory" method which instantiates a specific prefab and then configures the component inside that prefab, but a) this means adding one such method for each prefab and b) it breaks down once I want to configure multiple components within the same prefab.)
0
I want camera to be positioned on the player also x axis should move continuosly by .05f in unity 2d I am creating an 2d platformer and I am newbie to Unity any help will be highly appreciated. I want the camera to be positioned on the player and also the X axis should move continuously by .05f. And if player is not moving or stuck somewhere and if player is behind camera player (because X axis is automatically moving by .05f) then player should die. Is it doable? I am using Cinemachine and any script logic will be appreciated.
0
Set the start orientation of the gyroscope to initial phone orientation I am making a mobile VR project in Unity, and I have a 360 degree video that starts playing where I can look around using a VR headset. I am trying to set the start rotation of the video to the same rotation as my phone. So no matter where I look when I start the video, that should be my start rotation. I used Input.gyro.attitude in the start but that did not fix my problem. I think I am using it wrong. This is my code (on the camera inside the sphere) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class Gyroscope MonoBehaviour private bool gyroEnabled private Gyroscope gyro private GameObject cameraContainer A camera container for my main camera private GameObject videoSphere The sphere my video is in private Quaternion rot private void Start() videoSphere GameObject.FindGameObjectWithTag("Video") cameraContainer new GameObject("Camera Container") gyroEnabled EnableGyro() cameraContainer.transform.position transform.position put the cameracontainer into the sphere cameraContainer.transform.rotation Input.gyro.attitude here I want to set the cameracontainer to the rotation of my phones gyroscope transform.SetParent(cameraContainer.transform) make my main camera a child of the camera Container videoSphere.transform.localRotation cameraContainer.transform.rotation Here I wanted to set my sphere rotation to the camera rotation Debug.Log(videoSphere.transform.localRotation) private bool EnableGyro() if (SystemInfo.supportsGyroscope) Input.gyro.enabled true turn on my gyroscope cameraContainer.transform.rotation new Quaternion(0, 90, 90, 0) rotate my camera container so the video shows good rot new Quaternion(0, 0, 1, 0) set the variable rot so that you can turn your device return true return false private void Update() if (gyroEnabled) transform.localRotation Input.gyro.attitude rot this makes you turn the device and it recognizes the input of the phones gyroscope
0
2 cameras that each player sees through a different one Im very new to Networking in Unity 5. Im trying to bring the finished basis for my 2 player, 1 vs 1, turn based game I made for local multiplayer (both players on same computer) to an online matchmaking system. In the game currently (for local), there are 3 cameras. 2 centered on separate canvases for selecting attacks for each player. that once p1 chooses his attacks and presses continue, the camera is deactivated and the 2nd camera for p2's attacks is activated. Once p2 presses to continue the 2nd cam is also deactivated and the 3rd cam is put on, this camera is set on the battle arena and plays out in turns the moves picked by the 2 players through a turn determining system. What I want to do for the online is have both canvas cameras activated at the same time and each player to be assigned to a different camera. So is there a good way i should do this? NetworkView on one of the cams? Hope I explained the premise enough P
0
How to use Input.GetAxis("Mouse X Y") to rotate the camera? I want to make a first person camera that rotates with the mouse. I looked at the Input.GetAxis Scripting API page and found a sample code, which I have included at the bottom of my post. Upon trying it out, I realized that although it has the same basic functionality I hoped it would have, it does not keep the camera parallel to the xz plane, particularly when moving the mouse in circles. After a while the camera would be at an odd angle, and the player would be completely discombobulated! Is there a quick fix to this code that would restrict the camera movement somehow, or is there a better way to rotate the camera? using UnityEngine using System.Collections public class ExampleClass MonoBehaviour public float horizontalSpeed 2.0F public float verticalSpeed 2.0F void Update() float h horizontalSpeed Input.GetAxis("Mouse X") float v verticalSpeed Input.GetAxis("Mouse Y") transform.Rotate(v, h, 0)
0
How can I rig an object to animate from two different orientations? As an example Say you're animating a skateboard. The board has a nose and a tail. Normally, the nose points forward and the tail points backward. Now say you have two animations idle and trick. The idle is animated with the nose pointing forward. The trick, however involves the board rotating 180 , ending with the nose pointing backward, functionally swapping the nose and tail. Now, if you were to blend the trick animation back into idle, the blend would rotate the board back around so the nose points forward, which would not be the intended behavior. The intended behavior would be for the animator to somehow know that the tail is now the forward facing orientation and animate as if the tail were the nose. I'm competent but no expert with rigging animation and I've been racking my brain trying to come up with either a way to cleverly rig the object to somehow work as intended or to be able to modify the animations procedurally in code or something, but I haven't been able to figure it out. This seems like a problem that must come up somewhat frequently with game animation, but I haven't been able to find any specific resources. I'm using Blender and Unity. Edit To be clear, I'm not talking about root motion or the animating object's position rotation in the world, just the orientation of the bones being animated.
0
How to make the camera follow the mouse in first or third person camera I currently I have a game made of a few small scripts, the PlayerController, PlayerStats, and CameraChange (each below). My question is how do I get the camera to follow the mouse movement? I want the player to be able to switch between each camera and look around with the mouse. Any idea as to how I'd go about doing this? My current theory is I would some how have to access the current active camera and make it follow the mouse but not sure how to do that. PlayerController using UnityEngine public class PlayerContorller MonoBehaviour Update is called once per frame void Update () var x Input.GetAxis("Horizontal") Time.deltaTime 150.0f var z Input.GetAxis("Vertical") Time.deltaTime 3.0f transform.Rotate(0, x, 0) transform.Translate(0, 0, z) PlayerStats using System.Collections using System.Collections.Generic using UnityEngine public class PlayerStats MonoBehaviour public int Health 100 public int Stamina 100 public int magic 100 Use this for initialization void Start () Update is called once per frame void Update () if () CameraChange using System.Collections using System.Collections.Generic using UnityEngine public class CameraChange MonoBehaviour public GameObject ThirdCam public GameObject FirstCam public int CamMode Update is called once per frame void Update () if (Input.GetButtonDown("Camera")) if (CamMode 1) CamMode 0 else CamMode 1 StartCoroutine(CamChange()) IEnumerator CamChange() yield return new WaitForSeconds(0.01f) if(CamMode 0) ThirdCam.SetActive(true) FirstCam.SetActive(false) if(CamMode 1) FirstCam.SetActive(true) ThirdCam.SetActive(false)
0
Unity Custom Inspector Platform dependent property section I want to make a custom inspector for one of my scripts that builds UI elements at runtime. This requires small changes to the default values depending on what platform I'm targeting. How do I add something that is similar to the graphics settings where there is a default option but each platform is able to override the default setting for a platform specific value? I'm looking for the same kind of thing that Unity has for the player settings (Edit Project Settings Player). This allows you to set the details for each one but you can override them for each platform if they need to be different.
0
How do I dynamically use the rect tool in Unity2D? The rect tool in Unity2D (I honestly do not remember if it is present in Unity3D) allows you to scale down scale up an object in just one direction (what it does is it simultaneously increases decreases the height of an object in transform.scale and transform.position. I was trying to scale down an object while keeping its position the same using this code (P.S. I took the first four lines of code from here The Best Way To Generate a Random Float in C ) float range (double)float.MaxValue (double)float.MinValue float sample scaleRand.NextDouble() float scaled (sample range) float.MinValue float f (float)scaled if (f gt 0.6f) f 0.6f gameObject.localScale new Vector2(gameObject.lossyScale.x, (gameObject.lossyScale.y f)) However, this code does not work. So, how can I recreate the effect of using the rect tool in Unity Editor using C ?
0
Press and hold camera movement with mouse in new Input System? I am transitioning to the new movement system and am having trouble figuring out how to move the camera when a mouse button is pressed and held. Here's how I did it before private void Update() Get the position of the mouse when a middle click occurs if (Input.GetMouseButtonDown(2)) dragOrigin cam.ScreenToWorldPoint(Input.mousePosition) If the MMB is still held down, calculate the distance and move the camera if (Input.GetMouseButton(2)) Vector3 difference dragOrigin cam.ScreenToWorldPoint(Input.mousePosition) cam.transform.position difference I have tried doing something similar in the new input system but it doesn't work public void OnMMB(InputAction.CallbackContext context) if (context.phase ! InputActionPhase.Started) Get the position of the mouse when a middle click occurs dragOrigin cam.ScreenToWorldPoint(Mouse.current.position.ReadValue()) else If the MMB is still held down, calculate the distance and move the camera Vector2 newPosition cam.ScreenToWorldPoint(Mouse.current.position.ReadValue()) Vector3 difference dragOrigin newPosition cam.transform.position difference Here is how I set this up inside the Input editor The Action Type of the action is Button.
0
Creating a delay by using Invoke Is it possible to delay the effects of a script that is attached to a game object? I have 2 characters in a scene, both receiving live motion capture data, so they are both animated identically. I have rotated one by 180 degrees and placed it in front of the other one, to create the impression that they are copying mirroring each other. Each has several scripts attached to them, of course... Now, I would like to be able to delay one character a bit (e.g. 1 sec) to make it look more realistic, as if one character is observing the other character and then copying its exact movements. Is it possible to do this by somehow using the Invoke method on the other character's Update perhaps? Or any other possibilities to achieve what I described? EDIT I used a buffering mechanism, as suggested by all the helpful comments and answers, instead of delaying, because delaying would have resulted in the same network data being used, except after a delay, but I needed the same old data being used to animate a second character to create the impression of a delayed copying... private Queue lt Vector3 gt posQueue private Queue lt Quaternion gt rotQueue int delayedFrames 30 void Start() posQueue new Queue lt Vector3 gt () rotQueue new Queue lt Quaternion gt () void Update() Vector3 latestPositions Quaternion latestOrientations if (mvnActors.getLatestPose(actorID 1, out latestPositions, out latestOrientations)) posQueue.Enqueue(latestPositions) rotQueue.Enqueue(latestOrientations) if ((posQueue.Count gt delayedFrames) amp amp (rotQueue.Count gt delayedFrames)) Vector3 delayedPos posQueue.Dequeue() Quaternion delayedRot rotQueue.Dequeue() updateMvnActor(currentPose, delayedPos, delayedRot) updateModel(currentPose, targetModel)
0
Flare (particle system) showing weird semi transparent rectangles instead of smoke when there's fog in the scene I'm making an FPS game with some fog in the scene. I've added a flare particle system (from the standard assets' prefabs) but it looks like it has some weird collision with the fog. Whenever the fog is enabled I get these weird rectangles on top of the flare like in this screenshot I've noticed that when I turn off the fog they disappear, also I've noticed that when I turn off the Emission part of the particle system the rectangles disappear, but of course, also most of the wanted effect is gone.
0
How do I make a rainbow hue shift over time on text? What I'm trying to do is make a Text object have an animation that allows for the hue of the color to go all the way up and loop back around, so it creates a cool rainbow thing. I've looked on google for a solution but the solution I found only worked in older versions of Unity, which were used back in 2015. What I found Any help would be appreciated!
0
Problem with Factory Method Pattern when I try to create a Weapon MonoBehaviour I'm learning about Design Patterns using Unity and I'm not sure about how to solve the following problem with the Factory Method Pattern I want to read a XML file and using the Factory Method Pattern to create a Component (a Weapon) to add it to a GameObject which will be cointained on a Pool Manager, but Weapon "Is A" MonoBehaviour and for that reason It can't be instantiated using a "machineGun new MachineGun() " public abstract class WeaponFactoryMethod protected string fileName "weapons.xml" public abstract Weapon CreateWeapon() public class MachineGunFactoryMethod WeaponFactoryMethod public override Weapon CreateWeapon() string filePath Path.Combine(Application.streamingAssetsPath, fileName) Weapon machineGun null XmlReader xmlReader new XmlTextReader(filePath) if (xmlReader.ReadToDescendant("Weapons")) if (xmlReader.ReadToDescendant("Weapon")) do I CAN'T DO THIS machineGun new MachineGun() machineGun.ReadXml(xmlReader) while (xmlReader.ReadToNextSibling("Weapon")) else Debug.LogError("There aren't definition for Weapon") else Debug.LogError("There aren't definition for any Weapon") return machineGun public abstract class Weapon MonoBehaviour, IXmlSerializable public float AttackRange get set Every weapons Shoots in a different way public abstract void Shoot() Serialization public XmlSchema GetSchema() return null public void ReadXml(XmlReader reader) XmlReader childReader reader.ReadSubtree() while (childReader.Read()) switch (childReader.Name) case "AttackRange" childReader.Read() AttackRange childReader.ReadContentAsInt() break public void WriteXml(XmlWriter writer) public class MachineGun Weapon public override void Shot() Raycasting.. At the end I want something like GameObject (player) Component (A Weapon script with the data from the xml) Should I just create a GameObject (player) and do an "AddComponent lt MachineGun " and later copy the info from the xml file instead using the Factory Method Pattern?? Is there a better way?? Any suggestions, corrections or advice will be very grateful. I'm sorry by my English.
0
Aspect ratios for sprites in Unity3d I'm using Unity3D version 5.0. I'm wondering what the best way to deal with changing resolutions in Unity is. In Swift I can just use the x2 x3 in order for it to pick the correct sprite for it to use. Is there a similar mechanism in Unity? Thanks
0
Unity Inaccurate rotation if object is rotated on two axis at once I have an object which i want to rotate relative to world space. I have three variables (one for every axis) which store the rotation. By pressing buttons on my controller I add or subtract 90 to these variables (rotX, rotY, rotZ). Then I rotate my Object like this transform.Rotate (rotX delta, rotY delta, rotZ delta, Space.World) As this is called every frame the object would spin forever so i subtract the ammount I've allready rotated afterwards rotX rotX delta rotY rotY delta rotZ rotZ delta This works fine as long as I don't rotate two axis at once. Then the object rotates rotates only partially to the desired position (e.g. 83 if I want to rotate to 90). I can't see what I've done wrong. It actually seems like the moment I start an rotation around an axis all other axis get canceled. But if I monitor the variables they look exactly as they should. Thank you in advance and have a amazing day!
0
Configurable Joint how to create a FixedJoint, and Rotating it? I have 2 rigidbody, in 2d view, non kinematic, and with no gravity, and want to connect them with a Configurable joint. I don't want the joint to be spring (I want the same distance always). But I would like to move the blue object left right (rotating it around the red one) How can I setup my Configurable Joint ? Thanks you !
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
Disabled script works anyway I have a simple code that will be enabled when I kick, so I disable it right away but even though it is disabled, it works somehow. can it be because of his parent or something else I dont know of? this is the script Kick Test, i dont reach it from anywhere else private GameObject ball private Rigidbody2D rg2d public int power 30 void Start() ball GameObject.FindGameObjectWithTag("Ball") rg2d ball.GetComponent lt Rigidbody2D gt () this.enabled false private void OnTriggerEnter2D(Collider2D col) if(col.tag "Ball") Debug.Log("K CK") Vector2 pos (transform.position col.gameObject.transform.position).normalized rg2d.AddForce( pos power, ForceMode2D.Impulse)
0
Can a prefab of a complete Unity scene be created? Can we create a prefab out of a complete unity scene, so that we can instantiate the complete scene like we instantiate gameobjects in unity.
0
How to play an animation backwards in Unity? I know this question has been asked before but it all involves using the Animation(?) component, so that is no longer any good in Unity 5.3.1f1, I explain a bit more later. I'm trying to simply get an animation to play backwards. On the object that I want to have an animation play backwards on, I have an animator. private Animator anim ... anim GetComponent lt Animator gt () If I do animator.speed 1.0f It tells me Animator.speed can only be negative when Animator recorder is enabled. Animator.recorderMode ! AnimatorRecorderMode.Offline So I try putting on an Animation component on the game object, and making the clip the animation. Every time I do anything with the Animation component in script, it tells me the component must be marked as Legacy. That is no good, because when I tried making it Legacy it caused multiple problems including not being recognized by the Animator. Also GetRef errors. The entire Animation component seems like it's treated as legacy now or is just broken. So I decided well maybe I could just try to get the animation to play backwards in the animator and having the animator record it, and then using that backwards recorded animation in the actual game. I cannot figure out how to this, even if I click record in the Animation view anim.recorderMode ! AnimatorRecorderMode.Record. I don't know what to do. All I want to do is play the same animation backwards without having to copy and paste an animation in the Project and moving all of the keys around so that they are reversed. Please help. Unity's animation system seems so convoluted in script.
0
UI clicks hitting game objects below I have a canvas with a panel with set width height inside. The canvas rendermode is set to ScreenSpace Overlay. My clicks on the panel are falling through and hitting the game objects below triggering their mouse events. The little green circle is a Sprite with the following event public void OnMouseDown() Debug.Log("click") Vector3 newPos Camera.main.WorldToScreenPoint (this.transform.position) newPos.x panel.GetComponent lt RectTransform gt ().rect.width 2.0f newPos.y panel.GetComponent lt RectTransform gt ().rect.height 2.0f panel.transform.position newPos I've been reading through the docs but I'm missing something... How do I stop my clicks hitting the game objects below the panel?
0
Follow a path in Unity I want to know how I can make this game object follow the specified path in unity
0
Photon2 billboards take a long time to face the camera I'm using PUN2 and trying to use nametag billboards for my players, but they are not facing forward correctly and I have to wait more than 20 seconds to make the name tag of player return to facing forward. here's my code for my BillBoard Script public class BillBoard MonoBehaviour protected Transform ThisCameraPlayerBillBoard private void Start() ThisCameraPlayerBillBoard GameSetup.GS.ThisCameraToBillBoard.GetComponent lt Camera gt ().transform private void FixedUpdate() transform.LookAt(transform.position ThisCameraPlayerBillBoard .rotation Vector3.forward, ThisCameraPlayerBillBoard .rotation Vector3.up)
0
How to block the player from moving left and right from two empty game objects? I made the game space shooter in that game my spaceship move left and right but its not stop in right and left corner. When its move to left its go out of the screen. how i stop block in the left and right screen edges. using UnityEngine using System.Collections public class PlayerMovement MonoBehaviour public float speedMove 3 public float bonusTime private Rigidbody rb private float limit 3 1 for right and 1 for left. private float direction 1 You can call it as speed private float speed 0.01f private bool toLeft false private bool toRight false public GameObject shield public GUIText bonustimeText private bool counting true private float counter private Weapon addWeapons public Sprite strongShip public Sprite normalSprite public Sprite shieldSprite private SpriteRenderer sRender private Weapon weaponScript void Start () counter bonusTime rb GetComponent lt Rigidbody gt () sRender GetComponent lt SpriteRenderer gt () addWeapons GetComponentsInChildren lt Weapon gt () foreach (Weapon addWeapon in addWeapons) addWeapon.enabled false weaponScript GetComponent lt Weapon gt () weaponScript.enabled true Update is called once per frame void Update () transform.position Vector3.MoveTowards (transform.position,new Vector3 (transform.position.x direction, transform.position.y, transform.position.z), speed) if (Input.GetMouseButtonDown (0)) direction 1 void OnCollisionEnter2D(Collision2D coll) if (coll.gameObject.tag "StrongMode") Destroy (coll.gameObject) counting true StrongMode() Invoke ("Downgrade", bonusTime) if (coll.gameObject.tag "ShieldMode") Destroy (coll.gameObject) counting true ShieldMode() Invoke("Downgrade", bonusTime) if (coll.gameObject.tag "Life") GUIHealth gui GameObject.Find ("GUI").GetComponent lt GUIHealth gt () gui.AddHealth() SendMessage("AddHp") SoundHelper.instanceSound.PickUpSound() Destroy(coll.gameObject) if (coll.gameObject.tag "Enemy") SendMessage("Dead") void Downgrade() SoundHelper.instanceSound.BonusDownSound () counting false bonustimeText.text "" counter bonusTime sRender.sprite normalSprite weaponScript.enabled true foreach (Weapon addWeapon in addWeapons) addWeapon.enabled false weaponScript.enabled true shield.SetActive (false) void StrongMode() SoundHelper.instanceSound.BonusUpSound () sRender.sprite strongShip foreach (Weapon addWeapon in addWeapons) addWeapon.enabled true weaponScript.enabled false void ShieldMode() SoundHelper.instanceSound.BonusUpSound () sRender.sprite shieldSprite shield.SetActive (true) void OnDestroy() bonustimeText.text ""
0
How do I pause and unpause gameobjects on is own in the scene without pressing keys in unity3d I can't get my gameobject to pause or unpause in the scene in Unity3d. I need the game to pause for a couple of seconds maybe longer than unpause by itself. Here is my script using UnityEngine using System.Collections public class hu MonoBehaviour GameObject pauseObjects public bool isPaused void Start () pauseObjects GameObject.FindGameObjectsWithTag("Player") Update is called once per frame void Pause () if(Time.timeScale 1) Time.timeScale 7f else if (Time.timeScale 8f) Time.timeScale 1
0
How to remove a scene after the another one has loaded 2 3I'm having this problem in Unity where I load a new scene, but the original is still overlapping it. How would you remove the original scene?
0
Unity, Cannot See Items on the Scene I am new to unity. I have created an asset by using Blender and managed to put it in the scene. But somehow now I can only see one item at a scene. For example I can only see camera when I clicked "Main camera" at the Hierarchy toolbar. When I clicked the asset, the camera is hidden from the scene along with lighting etc. This is difficult for me since I need to put my asset in front of the camera. Where can I toggle back the views for everything in the scene?
0
How to tilt an object(2D) after collision and the rotate continuously I am having trouble rotating and object after collision. The object only transforms to the given angle of rotation once and stops. I would like to achieve in a way that after it has collided with the player object it rotates continuously till its killed after exiting the screen. The OnCollisionEnter2D(Collision2D collision) can't achieve this. How can I achieve it using the FixedUpdate function? Here is the code namespace Assets.scripts public class Barmovementscript MonoBehaviour public float Tilt private void FixedUpdate() upon collision the object rotates in a clockwise direction. void OnCollisionEnter2D(Collision2D collision) if (collision.collider.tag "Player") Tilt Time.deltaTime 10 gameObject.transform.rotation Quaternion.Euler(0, 0, Tilt)
0
How to display custom UnityEvents in the editor? I recently stumbled upon the UnityEngine.Events.UnityEvent class, and it seemed pretty cool so I started using it in a project. Then I decided that I wanted to add some parameters to the event using its generic variants, like so System.Serializable public class BarkEvent lt GameObject gt UnityEvent lt GameObject gt public class MyOtherClass MonoBehavior public BarkEvent lt GameObject gt bark ... Other stuff ... But now it doesn't show up in the editor, making it harder to wire up my subscribers. Is there a way to make unity events with extra arguments show up in the Unity editor?
0
With a Texture Atlas that has 128x128 tiles, how can I use that in Unity3D? So I've got a working texture atlas that has tiles fitting 128x128. However, I can't quite figure out how to use them. I know it's probably got something to do with TileRenderer.material.SetTextureScale(" MainTex", new Vector2(0.25f, 0.25f)) TileRenderer.material.SetTextureOffset(" MainTex", new Vector2(0 0.25f,0)) but I'm not sure where to take it from there. Can anyone offer some advice? The size of the image is 1024x128 if that helps, which I think it might.
0
Unity5 using non convex meshcollider with rigidbody I want to build a car using wheel collider, mesh collider and rigidbody. The problem is that unity wants the meshcollider to be convex, and that cannot happen because my base model is bigger than 255 poly's.
0
How to make an expanding radial search in Unity? I am currently working on a City Builder Game and I often come across the problem of having to decide wich location to use. Examples The citizen has a job and needs a home. There are several buildings with open slots. The citizen is at a positon and is hungry. There are several restaurants on the map. How can I choose the right building to go to? I don't really wan't to check the distance for each, because there could potentially be hundreds of buildings and that decision problem occurs quite often. I also don't care for the optimal solution, any nearby result is fine. Currently all buildings register them self in a LinkedList. When searching for something I'd start at the beginning and the first occurrence that was 'good enough' would be returned. Citizen now drive across the map for something that was right next to them if the one far away was built earlier in the game. Any suggestions?
0
How to seamlessly handle multiple procedural 2D levels in Unity3D? I have a dungeon generating algorithm, but I would like to generate X levels, which are all connected somehow. I have a few approaches, but all of them has problems and questions, and I wonder how i.e. Diablo II handles them so seamlessly. 1. Approach Upon leaving a level, generate the next one on the fly. This would be the easiest, but would result in a relatively long loading screen everytime the player enters a new level. So generating the levels should be at the beginning of a new game, thus the next level will just have to be loaded, which is much faster. In theory not even a loading screen is necessary. 2. Approach Generate every level at the beginning of a new game and store them. Okay, now levels just have to be loaded, which could be done under half a second. No loading screen is necessary, maybe just a fade out fade in. How do I store them? Make custom files (i.e. scriptable objects) for them, or is there a simpler way? 3. Approach Generate and load every level at the beginning. Zero loading time, because everything is already generated and loaded into the tilemap. But how do I guarantee that levels don't collide, and the player can't see level Y from level X if there are lots of levels? And wouldn't it affect the performance? Because everything is loaded all the time. Yes, renderers, rigidbodies, scripts, etc can be turned off, improving the performance a lot... but still... this seems wrong. What is the best way to solve this problem?
0
How to check if a test ad is ready I was going through UnityAds for Unity3D, and came across this setting AD TEST MODE Force all So as I understood it states that I will be able to see real ads, in test mode, without monetizations on my testing tool, which in my case is Unity3D IDE, but I am still getting that blue sample ad screen quot Here would be your ad screen quot . Is there anything that I can do to check if any ad is placed for my app, and check this via code before Advertisement.Show() statement? Or am I missing something?
0
What is the most efficient technique for range detection? I have a bunch of patrolling enemies that fire projectiles when the player is in projectile range a specific radius. Which method is the most efficient and elegant? overlapSphere sphereCast triggers square magnitude anything else? I am using Unity.
0
Trouble with Inventory System and Item References I'm currently trying to get a simple inventory system to work but I'm having a lot of trouble. This isn't the exact code I have, but it's a shorter version that I'm pretty sure would function the same public struct ItemSlot public Item item public ItemSlot(Item item) this.item item public class Item MonoBehaviour public string itemName public class Accessory Item public class Inventory MonoBehaviour public ItemSlot itemSlots new ItemSlot 1 public void AddItem(ItemSlot slot) itemSlots 0 slot public class Player MonoBehaviour public Inventory inventory private void Update() if (Input.GetKeyDown(KeyCode.E)) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hitInfo if (Physics.Raycast(ray, out hitInfo, 20)) GameObject target hitInfo.collider.gameObject inventory.AddItem(new ItemSlot(target.GetComponent lt Item gt ())) Destroy(target) if (Input.GetKeyDown(KeyCode.G)) print(inventory.itemSlots 0 .item) For a bit more prefacing I have a capsule object with the Player script on it, an empty with the Inventory script on it, which is then attached to the Player script (I'm not sure if I want to make the inventory a scriptable object which is why I've done this), and then lastly I have a cube object with the Accessory script on it. So, when I press E and pick up the item it gets added into the player's inventory and then destroyed from the scene. Then, when I press G to display that item in the inventory the console just says null. Not Null, which is what an actual null would show up as, but the string "null". If I use visual studio's debugger and have a look at what the accessory's base is, it also says null, but for some reason if I then try and print the accessory's name then that works fine, even though that variable is defined in the Item class. If I instead do this in the Inventory class public void AddItem(ItemSlot slot) ItemSlot 0 slot print(ItemSlot 0 .item) It works fine and prints Item (Accessory) in the console. Even if I print it right after I destroy target in the Player class, that also prints Item (Accessory), so I have no idea why it doesn't work on the next block of code. Sorry this is so long and maybe an easy fix, but I'm lost. Edit I think everything should be fixed now.
0
How to clip what is outside scroll view when using a custom UI element? I have created a custom UI element (that use CanvasRenderer). Here is code Mesh mesh new Mesh() Rect drawArea GetComponent lt RectTransform gt ().rect using (VertexHelper helper new VertexHelper()) helper.AddVert(new Vector3(drawArea.xMin, drawArea.yMin), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMin, drawArea.yMax), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMax, drawArea.yMax), Color.white, Vector2.zero) helper.AddVert(new Vector3(drawArea.xMax, drawArea.yMin), Color.white, Vector2.zero) helper.AddTriangle(0, 1, 2) helper.AddTriangle(2, 3, 0) helper.FillMesh(mesh) var canvas GetComponent lt CanvasRenderer gt () canvas.SetMesh(mesh) canvas.SetMaterial(Material, null) It creates a simple rectangle that is same size as rect transform. It works great. However if I put this inside a scroll view, everything that is outside scroll area viewport is rendered (while it should be clipped). The scrolling works as it should (rectangle get scrolled by changing position when scrollbar is used). I have tried to call canvas.EnableRectClipping(...) but without success.
0
When using IK the player head is looking at down the ground instead looking at the object target up what can be the problem? This script is attached to the player using UnityEngine using System using System.Collections RequireComponent(typeof(Animator)) public class CharController MonoBehaviour protected Animator animator public bool ikActive false public Transform lookObj null public float lookWeight 2f void Start() animator GetComponent lt Animator gt () a callback for calculating IK void OnAnimatorIK() if (animator) if the IK is active, set the position and rotation directly to the goal. if (ikActive) Set the look target position, if one has been assigned if (lookObj ! null) animator.SetLookAtWeight(lookWeight) animator.SetLookAtPosition(lookObj.position) if the IK is not active, set the position and rotation of the hand and head back to the original position else animator.SetLookAtWeight(0) When the lookObj is a sphere or a cube it's working fine but if the lookObj for example is a big spacecraft now the player head will look to the ground down and not to the spacecraft up The problem is that the center of the spacecraft is at the bottom this is a screenshot when it's showing the spacecraft at regular when it's in Pivot mode Now when I click on the Center button now the center of the object is at the bottom Is there any way to fix it maybe eve fix it ?
0
How to adjust Unity banner ads for IOS? I'm using Device Simulator from the package manager to test on mobile devices. I'm using a banner ad at the top center with the code Advertisement.Banner.SetPosition (BannerPosition.TOP CENTER) For andoid devices I can see it but on IOS devices it is blocked by its top notches or the safe area the Device Simulator calls it. Is there a way to reposition the y axis to fit on IOS devices? Thanks
0
SmothStop Function doesn't work as expected i'm trying to create a smothstop function i need it to control time variable on my lerp function used to move character and so on...what i have is this private float SmothStop(float t) return 1 (1 t t t t t) problem here is that will start slow then accelerate... same as smothstart function.. that i already tested and work on that way.. so.. what i'm missing up?
0
Limiting x and y movement so you can't go off camera So I want to make an on rails shooter like that of Star Fox in the Unity engine. What I would like to do is limit the ship from moving off the screen. You move along the X and Y axis so i wont have to keep these invisible colliders in their place but I cant get another way to work. and I know I have to find a way to convert camera space to world space I just can't find a way how. This is my current controller and I commented a few failed attempts. also I'm using a perspective camera and I'd like to keep the rigibody movement if possible. public float turnSpeed 10 Horizontal private Vector3 moveDirection Vector3.zero public Rigidbody rb void Start() rb GetComponent lt Rigidbody gt () void Update() Screen.width transform.position new Vector3(Mathf.Clamp(transform.position.x, holdMyRatio, holdMyRatio), Mathf.Clamp(transform.position.y, holdMyRatio, holdMyRatio), 0) CharacterController controller GetComponent lt CharacterController gt () rb.AddRelativeForce(Vector3.right turnSpeed Input.GetAxis("Horizontal")) rb.AddRelativeForce(Vector3.up turnSpeed Input.GetAxis("Vertical")) moveDirection.x Input.GetAxis("Mouse X") turnSpeed Time.smoothDeltaTime moveDirection.y Input.GetAxis("Mouse Y") turnSpeed Time.smoothDeltaTime controller.Move(moveDirection Time.smoothDeltaTime)
0
Unity problems with OnTriggerStay and Input.GetKeyDown Background information Some weeks ago, I start by creating my own platform game. You control a character, that can collect logs and should hold all the campfires on in the game. When the user has collect more then one log, the player have to use this log to hold the fire on. So you should walk to the campfire and should press E to give the log to the fire. Problem What the problem momently is, is that when I press the E key, it will fired the input more then one time. This is because I use a OnTriggerStay2D function, to check every second if my Player is collide with the campfire object. Do some search on the internet, results in people with the same problem. So one of the solutions was to create an bool and set it to true on OnTriggerEnter2D. But this isn't working for me. The same problem as before will occur. Is there another solution to fix this conflict. When the user press the button, it should be fired ones. Below script is linked to the campfire object. Also tried it with if(Input.GetKeyDown(KeyCode.E)) isTrigger true and the same for GetKeyUp, but then isTrigger false My current working code public Animator anim public int campfireStatus bool inTrigger false Use this for initialization void Start () anim GetComponent lt Animator gt () Update is called once per frame void Update () anim.SetInteger("Intensity", campfireStatus) void OnTriggerEnter2D(Collider2D other) inTrigger true void OnTriggerExit2D(Collider2D other) inTrigger false void OnTriggerStay2D(Collider2D other) If player comes in contact with gameObject if (other.gameObject.tag "Player") print ("player") if(Input.GetKeyDown(KeyCode.E)) print ("E Pressed") if (WoodBehaviour.count gt 0) campfireStatus So when the Player is collide with the campfire object AND the player pressed the E key AND you have more then one logs (this counter will be set in the WoodBehaviour script, that is linked to the player object ) than it should increase the campfireStatus with plus one. The problem is, that the if statements will fired more then one times when pressing the E key.
0
Managing shared dll correctly in Unity I'm developing a dll that is to be used in two Unity projects. I've read that the way to reference a dll is to drag it into a 'plugins' folder so that it is added to the Unity project's dependencies, as their is no "add reference" available for this project in Visual Studio. But doing that the Unity project does not take into account that the dll evolves (as it is still in development). What I'd like (if possible) is to set up an automatic way so that the Unity projects update their dependencies when the shared dll is updated. I've try the reimport option (right click on the dll in Unity) but it seems that it is not working. What is the best way to manage this situation?
0
Issues using NetworkServer.Spawn with Unity and Mirror Networking I am using Mirror to handle the networking aspect When I spawn an object on the network, I Instantiate it on the server and then use NetworkServer.Spawn to notify all clients to spawn the object. However, when this object is eventually spawned on the client side, it seems to be spawned at the wrong position for a few seconds and then corrected itself and move to the correct position as is reflected by the server. Is there something I am not doing? Is this normal? Also I noticed if I changed the Network Sync Mode to 0, then it will only spawn in the wrong spot for a split second. using System.Collections using System.Collections.Generic using UnityEngine using Mirror public class EnemySpawner NetworkBehaviour public uint theId public int maxNumEnemies public int spawnDelay public GameObject enemyToSpawn float curSpawnTime BoxCollider2D boxColl Start is called before the first frame update public override void OnStartServer() curSpawnTime spawnDelay boxColl GetComponent lt BoxCollider2D gt () void Start() if (!isServer) return theId netId Update is called once per frame void Update() if (!isServer) return if (transform.childCount lt maxNumEnemies amp amp curSpawnTime lt 0.0f) Vector2 spawnPoint new Vector2(Random.Range(boxColl.bounds.min.x, boxColl.bounds.max.x),Random.Range(boxColl.bounds.min.y, boxColl.bounds.max.y)) curSpawnTime spawnDelay SpawnEnemies(spawnPoint,netId) else curSpawnTime Time.deltaTime Server void SpawnEnemies(Vector2 spawnPoint, uint theId) GameObject gobj Instantiate(enemyToSpawn, new Vector2(60.7f,1.3f), Quaternion.identity) gobj.GetComponent lt EnemyController gt ().parentNetId netId NetworkServer.Spawn(gobj) The way I've organized things, in the hierarchy I have Enemies Area1 Spider(Clone) Spider(Clone) Area1 has the EnemySpawner script. The spider is registered a spawnable prefab. Both Area1 and the Spider have a NetworkIdentity with no boxes checked. Additionally, the Spider has a NetworkTransform and NetworkAnimator.
0
Drawing circles at the background of a 3D scene and updating their size So, here is what I am trying to do in Unity 5 (using C ). I want to draw a a 2D circle at the background of a 3D scene and apply a texture image to fill it. Just like it would be if the circle was in the GUI, but now being always behind everything else instead of always in front (think of a moon in the sky of a piloting game, or a distant planet in a space game, etc). What would be the fastest way to draw such a circle and, of course, update its radius depending on the camera distance? Of course, I don't want to use a sphere, I want to learn how to that with a simple circle that gets bigger or smaller depending on the distance of the viewer.