_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
Why would the same script attached to multiple scenes not work the same way in some of the scenes? I have 4 scenes in my Unity Project. And in each scene I have identical sliders, what I want to do when Advance Trial is called via a button press, the sliders' value resets to 0. However, this only works for two of the scenes. For remaining two it doesnt work, I checked if Advance Trial is attached to the button gameobject which calls it and it is (in all scenes). There are no errors messages in the console either. How do I correct it? Also, when the else portion is executed the sliders are not inactive meaning, the sliders are still visible. This happens for the same two scenes for which the sliders do not reset. Am I missing something? Or do I need to check something in individual scenes? Please see my code below. public Slider sliders public void Start() sliders FindObjectsOfType lt Slider gt () as Slider for (int s 0 s lt sliders.Length s ) Resets the sliders sliders s .gameObject.SetActive(false) public void Advance Trial() for (int s 0 s lt sliders.Length s ) sliders s .value 0 int stimIndex UnityEngine.Random.Range(0, signals.Count 1) string text stimIndex.ToString() byte data5 Encoding.ASCII.GetBytes(text) client.Send(data5, data5.Length, remoteEndPoint) Debug.Log( quot lt color yellow gt Signal played is lt color gt quot stimIndex) Debug.Log( quot lt color magenta gt NUMBER sent to MAX is lt color gt quot text) Debug.Log( quot lt color magenta gt Index removed was lt color gt quot signals stimIndex ) signals.RemoveAt(stimIndex) if (signals.Count gt index) Debug.Log( quot lt color orange gt Yay! Keep Listening! lt color gt quot ) index else Debug.Log( quot lt color green gt All Trials finished lt color gt quot ) for (int s 0 s lt sliders.Length s ) sliders s .gameObject.SetActive(false) EndSessionPanel.gameObject.SetActive(true)
|
0 |
Display object at different position Id' like to create impression of shaking holographic image of NPC in Unity 2018, but moving it with transform will cause unnecesary transform rigidbody syncing, and using Rigodbody.position isn't an option for other reasons (too long to explain). I could write custom shader for moving vertices by given vector, but I'd like to keep flexibility of Standard Shader. Is there any way to properly render object at different position than it's transform.position? I was thinking about passing custom matrix to shader, but not sure which matrix should I overwrite and if it's not gonna complicate things (like break shadows or something).
|
0 |
How do I link a GameObject activated state to a UI button being held? How do I go about this functionality When a user taps and still holds onto a UI button, a GameObject will be set active, when they release the UI button, the GameObject will be deactivated.
|
0 |
How to design prefabs in Entity Component Systems In Unity (and I presume other game engines) you can create "prefabs" which are blueprints for game objects. They contain a list of components, and default values for those components. Prefabs can be instantiated many times, which is an efficient way of creating many objects of the same kind. One feature in particular of prefabs is that you can modify an attribute on a single instance of a prefab, without modifying the prefab itself. Similarly, you can modify the prefab, which will propagate the change to all instances. I've been working on an implementation of the Entity Component System (for a high level description of ECS see this question How to implement n body in an Entity Component System), and I got stuck on how to implement prefabs efficiently in ECS. I think it's a powerful capability of EC design, and implementing this on native ECS would be awesome. I can come up with a few approaches Create archetypes, which are predefined lists of components (Unity approach). This does not let me set initial values for the components, nor override them (there is nothing to override). Easy to implement, but doesn't really do what I want it to do. Create a "prototype" entity from which other entities are cloned, including component values. With this design I can override individual attributes, but when I update the prototype, the clones don't get updated. Create entities with a reference to a "base" entity. When getting a component from an entity, first look in its component list, then try the base entity. This way when I update a base component, base instances change as well. To override a base component I can simply add it to the instance entity. Of these three approaches the third approach comes closest, but I don't see a straightforward way to extend it so I can override a single attribute. How can I make this work?
|
0 |
How to make a script work when clicked only on the given prefab? I am very new to unity but not to C . I am working in Unity 2D I made this prefab called LongLane. Its basically a collection of sprites of road, put together into a Gameobject. Now I wanted objects to spawn on the road when I ONLY click on the road, I can spawn the object on the road but they spawn regardless of where I click. I have written some code but they aren't clear and readable. So how do I make a script work only when clicked on that specific prefab
|
0 |
How do I handle loads of (prefab?) objects in Unity2D 3D? I have been looking around for information regarding this process but I was unable to come across anything that would help me out. Basically, in a game where you may have many items or enemies or player objects, how would one go about creating these objects? Am I supposed to be creating every single one of these objects as a prefab and then load them into the game when needed? Or is it possible to create one object that has references to the different variables needed to create the above objects and then load in from an external source all the necessary information? And then during run time, depending on what object I am looking at, the script will 'create' the object with the information from the external source. Meaning, if I decide to have 50 different enemies in my game, do I need to make 50 prefabs, one for each enemy? Or just one prefab that loads in data pertaining to the 50 different enemies and then build upon that information? Thank you!
|
0 |
Why does the Debug.DrawRay return these weird lines I am working on a small feature of a 2D mobile game where a indicator points towards a object in 2D space. I am trying to make the indicator turn towards the object, however the vector I am trying to construct that points towards the object is off a bit. When I decided to draw a debug ray from the indicator position to the objects position it was also off a bit. I then decided to draw the debug ray the other way around which gave me a different line. If my understanding is correct, if you switch the starting point and the end point of a ray the line should stay exactly the same right? using UnityEngine using System.Collections.Generic public class Tracker MonoBehaviour public GameObject goToTrack private List lt Renderer gt renderers new List lt Renderer gt () void Start() foreach (Transform child in transform) renderers.Add (child.gameObject.GetComponent lt Renderer gt ()) void Update () void OnGUI() Vector3 v3Screen Camera.main.WorldToViewportPoint(goToTrack.transform.position) if the target is within the viewable screen the indicator shouldn't be rendered) if (v3Screen.x gt 0.01f amp amp v3Screen.x lt 1.01f amp amp v3Screen.y gt 0.01f amp amp v3Screen.y lt 1.01f) foreach (Renderer renderableObject in renderers) renderableObject.enabled false else foreach (Renderer renderableObject in renderers) renderableObject.enabled false v3Screen.x Mathf.Clamp (v3Screen.x, 0.01f, 0.99f) 0.04f v3Screen.y Mathf.Clamp (v3Screen.y, 0.01f, 0.99f) 0.04f transform.position Camera.main.ViewportToWorldPoint (v3Screen) Debug.Log ("Target planet position " goToTrack.transform.position.ToString()) Debug.DrawRay(Camera.main.ViewportToWorldPoint (v3Screen), goToTrack.transform.position, Color.red, 5.0f) Debug.DrawRay(goToTrack.transform.position, Camera.main.ViewportToWorldPoint (v3Screen), Color.green, 5.0f) Debug.Log ("Tracker angle " angle) transform.Rotate(0,0, angle, Space.Self) Output UPDATE I have noticed that when i substract the second vector with the first vector of the Debug.DrawRay it draws the ray like i want it to. From this I am taking that the Debug.DrawRay function draws the second vector on top of the first vector. (kind of like the the first vector is Vector(0,0,0) and the second vector is the actual ray you want to draw)
|
0 |
How to implement Vector3.MoveTowards follow with random movement I want to implement an AI behavior where an enemy runs towards the player while sidestepping randomly and aggressively (like in this video https www.youtube.com watch?v 35Ut C4eL40) Currently I am just using Vector3.MoveTowards but that results in smooth movement which isn't exactly what I need. I've tried adding an offset to the target using Random.insideUnitCircle but it just doesn't work. If anyone could give me an algorithm to implement it'll be great. Thanks
|
0 |
How to stop jumping again when character is in air (double jump)? I'm using touch inputs in my game to control the character. I would like to know how to disable my character from jumping again in the air. if (FingerTouchy.phase TouchPhase.Ended) charcter.transform.Translate(Vector2.up speed Time.deltaTime) float jumpForce 250 charcter.GetComponent lt Rigidbody2D gt ().AddForce(new Vector2(0, jumpForce)) Update Im using Collision Detection void OnCollisionEnter (Collision col) if(col.gameObject.tag "Ground") grounded true And checking if charcter is grounded if(FingerTouchy.phase TouchPhase.Ended) float jumpForce 250 if (grounded) continue charcter.transform.Translate(Vector2.up speed Time.deltaTime) charcter.GetComponent lt Rigidbody2D gt ().AddForce(new Vector2(0,jumpForce)) grounded false using collision collision2d doesn't work too.
|
0 |
How do I wait to execute code? I'm trying to make a relatively simple elevator (which essentially teleports the player), but I don't want it to instantly teleport them. I want the player to enter the collider, wait 2 3 seconds, and then do it to take make it seem somewhat more natural. My code thus far using UnityEngine using System.Collections public class Teleporter MonoBehaviour public GameObject TeleportTo public Material NewSkybox void TimerInvoke() void OnTriggerEnter(Collider other) Vector3 displacement other.transform.position this.transform.position other.transform.position TeleportTo.transform.position other.transform.position displacement RenderSettings.skybox NewSkybox Also if possible I'd like to stray away from coroutines. How should I do this?
|
0 |
Difference between GUILayout and EditorGUILayout? Is it matter if I use GUILayout or EditorGUILayout for my custom editor? I need to use one of them in the OnInspectorGUI function. which one should I use? What are the differences between the two? Thank you in advance.
|
0 |
How to implement efficient Fog of War? I've asked a question how to implement Fog Of War(FOW) with shaders. Well I've got this working. I use the vertex color to identify the alpha of a single vertex. I guess the most of you know what the FOW of Age of Empires was like, anyway I'll shortly explain it You have a map. Everything is unexplored(solid black 100 transparency) at the beginning. When your NPC's other game units explore the world (by moving around mostly) they unshadow the map. That means. Everything in a specific radius (viewrange) around a NPC is visible (0 transparency). Anything that is out of viewrange but already explored is visible but shadowed (50 transparency). So yeah, AoE had relatively huge maps. Requirements was something around 100mhz etc. So it should be relatively easy to implement something to solve this problem actually. Okay. I'm currently adding planes above my world and set the color per vertex. Why do I use many planes ? Unity has a vertex limit of 65.000 per mesh. According to the size of my tiles and the size of my map I need more than one plane. So I actually need a lot of planes. This is obviously pita for my FPS. Well so my question is, what are simple (in sense of performance) techniques to implement a FOW shader? Okay some simplified code what I'm doin so far Setup for (int x 0 x lt (Map.Dimension planeSize) x ) for (int z 0 z lt (Map.Dimension planeSize) z ) CreateMeshAt(x planeSize, 3, z planeSize) Explore (is called from NPCs when walking for example) for (int x ((int) from.x radius) x lt from.x radius x ) for (int z ((int) from.z radius) z lt from.z radius z ) if (from.Distance(x, 1, z) gt radius) continue transparency x tileSize, z tileSize 0.5f Update foreach(GameObject plane in planes) foreach(Vector3 vertex in vertices) Vector3 worldPos GetWorldPos(vertex) vertex.Color new Color(0,0,0, transparency worldPos.x tileSize, worldPos.z tileSize ) My shader just sets the transparency of the vertex now, which comes from the vertex color channel
|
0 |
Can't Transform.SetParent in Unity i have a problem that i don't understand why is happenning and it's driving me mad. I'm trying to code a script to put the player in the car by disabling the third person controller and then Transform.SetParent. Here's the code public ThirdPersonCharacterControl Controller public GameObject Player public GameObject Car public void PutWheel() if(isInteractive) if(isCar) PlacePlaceables() Controller.enabled false Player.transform.SetParent(Car) The error is Assets Scripts Player Interactible.cs(361,34) error CS1502 The best overloaded method match for UnityEngine.Transform.SetParent(UnityEngine.Transform)' has some invalid arguments Assets Scripts Player Interactible.cs(361,44) error CS1503 Argument 1' cannot convert UnityEngine.GameObject' expression to type UnityEngine.Transform' Why is that happening? It doesn't make sense to me because everything seems correct.
|
0 |
Cursor is locked and hidden, and can't click UI I have a player with a third person character controller component. I have a problem with the cursor lock it hides the cursor so I cannot click UI buttons. protected virtual void CharacterInit() cc GetComponent lt vThirdPersonController gt () if (cc ! null) cc.Init() tpCamera FindObjectOfType lt vThirdPersonCamera gt () if (tpCamera) tpCamera.SetMainTarget(this.transform) Cursor.visible false Cursor.lockState CursorLockMode.Locked
|
0 |
Unity NodeJS Projectile synchronization I am working on a MOBA game similar to League of Legends. I am building the game server system in NodeJS Socket.IO but I'm running into issues on figuring out the best way to handle projectiles (aka player skill shot abilities) on the server side. The Main goal is to be able to spawn a projectile (or projectiles) on the server side and update the position in a certain direction (all on the server side separate from Unity) until I specify the projectile to be destroyed. This way, each time the projectile moves I can check with every single players current position and see if the projectile hit (thus allowing me to damage the player on the server side). How could I achieve this effect, or something similar?
|
0 |
Process Purchase Event get called on each App launch iOS At present when I launch the app, each time ProcessPurchase event get called in iPhone device. Though upto now I have not pressed any purchase related buttons. Yes I have setup subscription purchase within my app and before I have purchased subscription in sandbox environment two to three times but now their time period is expired. Here you have debug log for actual event happening As per my past experience, ProcessPurchase event require to call only two times when a user purchase something or at restore purchase time. So why its get called each application launch that I can't able to understand!!! Please give some help in this so I can complete my Unity IAP related thing. Source Code https pastebin.com bNpXsjHg
|
0 |
Ground texture comes up blurry using the UV Rect Tool Im trying to recreate the ground as this sample sprite sheet https opengameart.org content post apocalyptic expansion I downloaded the sprite sheet and extracted the top left block and saved it separately and added it as a default object not Sprite UI. I then added a UI Raw Image to my scene, added the imported texture. But as I expand it, it becomes blurry, even the UV rect does not seem to help. I though the UV rect was supposed to repeat the texture. Am I doing this wrong?
|
0 |
Why does my terrain turn white when I get close to it? When I zoom in on my terrain it goes white The further in I zoom, the greater the whiteness becomes. Is this normal? Is this to speed up rendering or something? Can I turn it off? I'm also getting these error messages in the console over and over again rc.right ! m GfxWindow GetWidth() rc.bottom ! m GfxWindow GetHeight() and GUI Window tries to begin rendering while something else has not finished rendering! Either you have a recursive OnGUI rendering, or previous OnGUI did not clean up properly. Does this bear any correlation on the issue? Update I create virtual desktops to flit between using the program Deskpot. Turning this program off and restarting has stopped the above errors appearing in the console. However, I still get white terrain when I zoom in. Not a single error message. I've restarted my computer to no avail. I have an Asus NVidia GeForce GTX 760 2GB DDR5 Direct CU II OC Edition Graphics Card. Any known issues? Update I don't think it's fog...
|
0 |
What is the difference of target frameworks for unity3d? In Visual Studio in properties I can change target framefork. I cannot find anywhere what means all of these magic titles. What does it all mean (full, micro base, subset, web base)? And...Can I use functionality of .NET 4.6.1 ?
|
0 |
How to synchronize a parent and child position? When watching this video of Unity development, I was following along trying to learn Unity and for the most part understood everything conceptually. Where I got lost was when I tried using some of the same code and setup in Unity. I got the code working fine, but I got in trouble when I tried to implement the parent child behavior seen in the video at around 7 minutes regarding the Enemy objects. The solution described is set up as follows (someone correct me if I didn't understand it properly from the video). Parent Object Contains the script which drives behavior and movement Is located at the origin of the scene (reset the transform in other words) Child Object Contains the graphics renderer which draws the actual sprite or 3D object Is located at the enemy spawn point For me to get this setup working, I had to run the Translate function explicitly against the child object transform.GetChild(0).Translate(dir.normalized distThisTurn) However, in the video, it appears to work just fine with only transform.Translate(dir.normalized distThisTurn) Once he fixes the rotation issue, at about 7 minutes in, this works beautifully, and the enemy travels the path exactly as expected. When I tried this exact same approach, my enemy sprite jumps all over the place. It took me several hours to figure out that I needed to add the .GetChild(0) part. The behavior I saw with the setup from the video is that the invisible parent object moved correctly along the path, and the child went crazy and followed some alternate version of the same path, as if the origin was different or offset, or the path was reflected across some axis. My question is what did I do wrong? Can anyone spot how my setup is different than the one used in the video? Did I miss some detail of how he set up his parent child objects, particularly for the enemies? Or could this be some different behavior due to the version of Unity he is using (I believe mine is newer as I installed it just this week). I think it could also be some small gizmo or feature he neglects to mention that allows you to synchronize the movement of a parent object with its children. The reason for this setup (at least as given in the video) is it allows you to easily swap out the graphics. The scripting is tied to the parent, so all you have to do is exchange the child for one with different graphics and you're done. That part makes sense, I just don't understand why the exact same code he uses did not work for me. I'm talking only about the Enemy object here the creeps that move along the path (it's a tower defense game). I just want to know because I may have to use this extra GetChild call quite a bit, and I feel like it shouldn't be necessary, especially after seeing it work so well in the video. Doing this would also make my scene design a little easier. I have already read the comments on that video for additional info, as well as looked through Unity forum posts, other posts here on Game Dev.SE, and Google results. It would seem as if this is either old behavior, or there is some small detail neglected to explain in the video of how to synchronize movement of parent and child objects.
|
0 |
How do you Draw a path and have a GameObject follow it? How would you go about creating a path that a gameobject would follow? I'm looking to create similar functionality that you see in some RTS games. most notability the Total War series does this well. here are a few screen shots for reference. https imgur.com a Zhi6pQu Goal. Click a Unit Hold the mouse button down and drag to draw a line Release the mouse button. unit follows path drawn
|
0 |
Can't Get .enabled to Work for Children Sprites. What Gives? So I have an object with a few children. I want to be able to disable enable 2 of their SpriteRenderers via one of my scripts. I feel like I'm doing things right, but apparently I'm not. And yes, my game objects have the appropriate tags that are being searched for in my code. I'll paste the relevant bits of code below public bool isAiming false Animator playerAnim GameObject arm GameObject weapon SpriteRenderer armRenderer SpriteRenderer weaponRenderer void Start() playerAnim gameObject.GetComponent lt Animator gt () arm GameObject.FindGameObjectWithTag("Arm") weapon GameObject.FindGameObjectWithTag("EquippedWeapon") armRenderer arm.GetComponent lt SpriteRenderer gt () weaponRenderer weapon.GetComponent lt SpriteRenderer gt () void Update() CheckIfAiming() void CheckIfAiming() if (Input.GetButton("Fire2")) Holding right click isAiming true armRenderer.enabled true weaponRenderer.enabled true playerAnim.SetBool("isAiming", isAiming) else isAiming false armRenderer.enabled false weaponRenderer.enabled false playerAnim.SetBool("isAiming", isAiming) What gives? I want to just enable the sprite rendering when I hold down the right mouse click. SetActive(false true) is not an option as I still want code to affect them while they're not visible. Am I just trying to access the SpriteRenderers incorrectly?
|
0 |
How to change the geometry of the scene in Unity? I'm trying to experiment with 3D spherical geometry in Unity, but it seems like Unity objects are inherently set in flat space. My first idea was to create a class inheriting from Transform that would override most of the methods, but I discovered that the transform member of a game object is read only so I cannot replace it with my custom class. I know this sort of thing is possible because the game Hyperbolica is being built in Unity using curved space. I have the math all figured out, I'm just not experienced with Unity. Anyone have other ideas for things I could try?
|
0 |
Recursively find neighbors I'm making a Bubble Shooter game in Unity. I came to the point where I can hit another bubble and it destroys all of its neighbors. Now I'm trying to use recursion to destroy all of its neighbors neighbors and it causes a stack overflow. private List lt Bubble gt FindAllRecursiveNeighbors(Vector2Int originPosition) List lt Bubble gt allNeighbors FindNeighbors(originPosition) List lt Bubble gt result new List lt Bubble gt () foreach (Bubble bubble in allNeighbors) if (result.Contains(bubble)) continue result.Add(bubble) Recursion starts here. foreach (Bubble bubble in result) List lt Bubble gt neighbors FindAllRecursiveNeighbors(FindPositionOfBubble(bubble)) foreach (Bubble neighbor in neighbors) if (result.Contains(neighbor)) continue result.Add(neighbor) return result
|
0 |
Can an iOS application have an explicit quit button? I've heard a rumor that you cannot have an explicit quit button on your app when it goes to the Apple App Store, can anyone verify this? It seems that most applications do not have one, and there is no explicit quit. How to developers handle quitting in general on iOS applications? Note I am using Unity, C , and Xcode to develop my game for the iPad.
|
0 |
Are lightmaps also considered textures? I want my game to support phones with max texture size of 1024 so my texture atlases are 1024. My question is are lightmaps also considered textures and their max size must be 1024? Or they can have higher dimensions like 4096?
|
0 |
Show hide soft keyboard on demand I'm writing simple chat app using Unity. The problem with Unity's default implementation of soft keyboard visibility is that it hides itself when i'm clicking outside of keyboard panel. What i want is that keyboard stays always shown until i explicitly tells otherwise. For a couple of days i tried to find similar questions but none of them helped me. I have very little experience in "native" android development (i.e. Java). So far i managed to create simple native plugin for Unity. I tried to manually open keyboard with this code imm (InputMethodManager)context.getSystemService(Context.INPUT METHOD SERVICE) imm.toggleSoftInput(InputMethodManager.SHOW FORCED, InputMethodManager.HIDE IMPLICIT ONLY) The result was fine, except the keyboard had InputType set to TYPE CLASS NUMBER. For my app i needed TYPE CLASS TEXT. So i tried to research how to set InputType and stumbled on fact that this property can only be changed inside EditText object. As i'm writing my app in Unity, i had no way of finding my InputField's inside native code. So i tried to create EditText inside my native plugin. I followed the logic that if i create custom EditText, place it inside main layout and set visibility to NONE or make background transparent, then i can set focus to that element and be fine FrameLayout myLayout activity.findViewById(android.R.id.content) focusedText new EditText(context) focusedText.setFocusable(true) focusedText.setInputType(InputType.TYPE CLASS TEXT InputType.TYPE TEXT VARIATION NORMAL) myLayout.addView(focusedText) focusedText.setFocusableInTouchMode(true) focusedText.requestFocus() focusedText.setBackgroundColor(activity.getResources().getColor(android.R.color.transparent)) imm.showSoftInput(focusedText, InputMethodManager.SHOW FORCED) The end result was a mess. Soft keyboard behaviour became undesirable. In order for keyboard to show, i first needed to select InputField, then i would see transparent EditText be created in the middle of my layout with all input characters visible. Even if all worked fine, it still looks like a wacky hack. Does anyone stumbled across similar issues?
|
0 |
Controlling screen and window size in Unity In Java I know how to make a window of a certain size and make it not resizable. How do I control my game's window size in Unity and prevent players from resizing it?
|
0 |
Should I use Unity for a "non game" mobile app? I have some experience with Unity but I always made games only. Right now I have an idea for an app but I don't think Unity is the most efficient way to do it. Probably Android SDK and OpenGL ES would be better but I have to learn them. So should I learn a new tool or should I stick with what I already know and get this thing done?
|
0 |
Resize sprite to match camera width? I'm trying to resize my small background sprite to match the screen width of the user's device. This is what I'm trying Use this for initialization void Start () Set filterMode SpriteRenderer sr (SpriteRenderer) GetComponent("Renderer") sr.sprite.texture.filterMode FilterMode.Point Get scaling float multiplier Camera.main.rect.width sr.sprite.bounds.size.x Scale transform.localScale localScale multiplier It seems there is a problem with the measure I get from the Camera width, I also tried Screen.width but it seems it returns the value in pixels.
|
0 |
how to check previous scene in scene manager in unity 3d I'm trying to make my first game using unity 3d and I'm trying to make a game over the scene that when you press the try again? button it should take you back to the previous scene, I was thinking of just making it with the code SceneManager.GetActiveScene().buildIndex 1)) then just place one after every level on the build index so that it takes to the previous level that the player was in, but I think this would just increase the file size (Idk if it actually does), so I was wondering if there is a more efficient manner on how to do this so that I could only have one Game Over Scene in the Build Index?
|
0 |
What is the physical interpretation of Input.GetAxis("Horizontal")? Actually I want to edit my previous question titled What is the geometrical interpretation of Input.GetAxis("Mouse X") and add a related question "What is the physical interpretation of Input.GetAxis("Horizontal")?" to it. However, I was asked to create a new question about it. The longer I press the key, the greater the value returned by Input.GetAxis("Horizontal"). If I don't press, it returns 0. The value seems to be a function of time interval the key is pressed. What is the empirical relationship between the relevant quantities?
|
0 |
My object just automatically "launch" or do stuff without me clicking on my mouse when it respawn? I've already set the ball (my object) initially at the start where I have to click for the ball to launch from the paddle (it's a ping pong game). private void LockBallToPaddle() Vector2 paddlePos new Vector2(Paddle.transform.position.x, Paddle.transform.position.y) transform.position paddlePos paddleToBall For the ball to stick to the paddle Launch the Ball private void LaunchBall() if (Input.GetMouseButtonDown(0)) hasStarted true rbBall.velocity new Vector2(Random.Range( 2f, 2f),speedVelocity) Both of which I put under Update() private void LaunchBall() if (Input.GetMouseButtonDown(0)) hasStarted true rbBall.velocity new Vector2(Random.Range( 2f, 2f),speedVelocity) Now the problem is when my ball hits a certain collider, I want it to respawn the position back to the paddle. So instead of Destroy the game object, I just copy and paste those same methods under collision if (collision.gameObject.tag quot bottom quot ) LockBallToPaddle() LaunchBalls() But now it just launches straight away from the paddle when hit the collision without me clicking anything like what quot Launchballs() quot intended to. What should I do?
|
0 |
How to distort 2d perlin noise? I am using Unity's 2D Mathf.PerlinNoise(x, y) function and I would like to make it distorted. What I mean is described with this picture I made How can I do that? What transformations should I apply to Mathf.PerlinNoise(x, y) to achieve this effect?
|
0 |
Mathf.Approximately should I use it for what cases? For comparing floats they recommend using Mathf.Approximately At the same time, they don't use it, for example, for comparing types such as vectors. From Vector3.cs public bool Equals(Vector3 other) return x other.x amp amp y other.y amp amp z other.z If I understand it correctly it wouldn't cause any problem when using operator to compare floats that are formed the same way (or copied from the same source). For example float x 10f 10f float a x or a 10f 10f float b x bool equal (a b) always true but it can cause a problem if floats are formed differently even if their results are supposed to be the same. For example float a 10f 10f float b 11f 10f bool equal (a b) result is unpredictable Is my understanding correct?
|
0 |
Chromium Embedded Framework and Unity3D? I have recently heard about the Chromium Embedded Framework and was over joyed as I want to use html as my GUI source. I did find a C version but it seems to be for Windows Forms. I'm not too terribly well versed but I was under the impression that it may cause it to be unavailable for cross platform use. Can anyone provide and insights? And if this will not work, any free alternatives?
|
0 |
Assets bundles have higher size than uncompressed sprites I've created a script that generates assets bundles by compressing sprites using LZ4 compression. I need this in order to generate smaller files that I'll download from a server at runtime but after taking a look at those bundles. I've found out that they actually have a higher size than the uncompressed sprites. For example, I've generated a bundle from three sprites that have a size of 201KB together, but if I take a look at its generated bundle, its size is 300KB. This is only one example, there are other bundles that are 6MB but their original files are only 500KB and that doesn't make any sense to me. Can someone point me in the right direction?
|
0 |
Photon Realtime, StripKeysWithNullValues cause heavy GC Alloc In our current project, we use Photon room properties to sync entities. and i noticed some heavy GC Allocs while deep profiling the game and it always ends down to this method. Have anyone faced this issue before ? or attempted to fix it ? here is the source code of that method. lt summary gt This removes all key value pairs that have a null reference as value. Photon properties are removed by setting their value to null. Changes the original passed IDictionary! lt summary gt lt param name "original" gt The IDictionary to strip of keys with null values. lt param gt public static void StripKeysWithNullValues(this IDictionary original) object keys new object original.Count original.Keys.CopyTo(keys, 0) for (int index 0 index lt keys.Length index ) var key keys index if (original key null) original.Remove(key)
|
0 |
Changing long float to number short scale I am looking to use a piece of code to take an extremely long number and convert it to decimal equivalent short scale. (i.e. 120100000000 would be 120.1 Billion) I am doing this with two separate scripts but this can be condensed into a single one. I am trying to look for a recurring process instead of the massive amount of if statements currently running in the script. This is being done with an external array in Unity that holds the strings for short scale. (billion,trillion, etc) Trying to find a recurring model that will look for the length, and attach it to the appropriate array object. using UnityEngine using System.Collections using UnityEngine.UI public class amountText MonoBehaviour public Text text public Text numberPref public string values public static float number 1000f private float numberLength private float remainder private float increaseAmount 5000f void Start () text GetComponent lt Text gt () void Update () text.text Mathf.RoundToInt(number).ToString() numberLength Mathf.RoundToInt(number).ToString().Length if(numberLength lt 9) text.text Mathf.RountToInt(number).ToString() numberPref.text (" ") if(numberLength gt 9 amp amp numberLength lt 12) text.text number 1E 9 numberPref.text (values 0 ) if(numberLength gt 12 amp amp numberLength lt 15) text.text number 1E 12 numberPref.text (values 1 ) if(numberLength gt 15 amp amp numberLength lt 18) text.text number 1E 15 numberPref.text (values 2 )
|
0 |
Why is the Enemy not changing direction when entering the collider? I'm really new to Unity, and I'm trying to make a 2.5D platform game. I want to make my enemies walk on a platform and turn when they reach the end of the platform so I placed two triggers at the beginning and at the end of it to change the direction of the enemy. public class BanditScript EnemyScript Start is called before the first frame update private Rigidbody rb private Vector3 moveDir private bool left void Start() left true speed 1 player GameObject.FindWithTag("Player") animator GetComponent lt Animator gt () minDistance 1 rb GetComponent lt Rigidbody gt () Update is called once per frame void Update() IsNear() if (near) attack animator.SetBool("isAttacking", true) animator.SetBool("isMoving", false) else MoveOnPlat() animator.SetBool("isAttacking", false) animator.SetBool("isMoving", true) void MoveOnPlat() animator.SetBool("isMoving", true) if (left) moveDir transform.forward else moveDir transform.forward rb.velocity moveDir speed private void OnTriggerEnter(Collider other) if (other.tag "platEndL") left false transform.rotation Quaternion.Euler(0, 90, 0) if (other.tag "platEndR") left true transform.rotation Quaternion.Euler(0, 90, 0) This is my class, the issue is that the enemy keeps moving in the same direction despite everything. Can you help me?
|
0 |
What is the Unity 2019.3.5 version of UnityEngine.UI.Text ? I was following a tutorial on how to create a dialogue Box in Unity, and in one part of the tutorial the tutor imports UnityEngine.UI and creates an object of type Text, but my version of Unity is 2019.3.5f1 and I learned through searching a bit online that this UnityEngine.UI doesn't exist anymore in this version, and that it was replaced with UnityEngine.UIElements, and this Text type doesn't exist anymore as well. I couldn't find a replacement for Text or what is the new nomenclature, nothing from trying stuff that popped in the auto complete or searching for answers in the Internet gave me answers. Maybe I just searched poorly, but if anyone happens to know, could you kindly answer?
|
0 |
How to create terrain made of small tiles? The terrain in my game must be created using tiled assets. I have unique textures for each tile (all with the same height and width that can be used to compose the terrain) and the information of each map is baked in binary files these binary files contains each tile height and texture. I'm thinking about creating the terrain at runtime (or create a tool to bake the terrains in unity's proper formats). Each tile would be an mesh composed by 2 triangles. This way I can represent individually each tile and associate a unique tile texture for each tile. My concerns is about performance as it will end up with several different meshes just for the terrain. Am I thinking in the right direction? Is there other better way to implement a tiled terrain like this in Unity3d?
|
0 |
How can I shoot an arrow if I know the shot power and target? I am trying to shoot an arrow at a target with a 100 success rate. Given the initial force applied to the arrow, the gravity, the location of the archer, and the location of the target, how can I do this in Unity? I have read How can I find a projectile 39 s launch angle?, and it contains the equation I am using However, this is only accurate when I am at the maximum distance from the object given its power. (Above the maximum distance means that the arrow cannot reach the target.) The closer I move to the target, the less accurate the arrow shot becomes, as it travels past the target. The angle is increased resulting in the arrow traveling a shorter distance as I'd expect, but it is not increased by enough. The script spawns an arrow (a simple sphere) and launches it towards a target. It fires once per second, but the closer to the target the archer is, the more inaccurate the arrow is. The case of the archer being too far from the arrow is not handled, but that is not my concern right now. using UnityEngine using System.Collections public class Archer MonoBehaviour public GameObject arrow Simple 3D Sphere public GameObject target Simple 3D Cube public float power 25.0f public Vector3 aim private void Start() StartCoroutine(ShootArrows()) private IEnumerator ShootArrows() while (true) yield return new WaitForSeconds(1.0f) Vector3 spawnPosition new Vector3(transform.position.x, transform.position.y, transform.position.z) GameObject arrowInstance Instantiate(arrow, spawnPosition, Quaternion.identity) as GameObject arrowInstance.GetComponent lt Rigidbody gt ().AddForce(Aim() power, ForceMode.VelocityChange) private Vector3 Aim() float xAim target.transform.position.x transform.position.x float yAim Mathf.Rad2Deg Mathf.Atan(((Mathf.Pow(power, 2) Mathf.Sqrt((Mathf.Pow(power, 4) ( Physics.gravity.y) ( Physics.gravity.y Mathf.Pow(HorizontalDistance(), 2) 2 VerticalDistance() Mathf.Pow(power, 2))))) Physics.gravity.y HorizontalDistance())) float zAim target.transform.position.z transform.position.z Vector3 aim new Vector3(xAim, yAim, zAim).normalized return aim private float HorizontalDistance() float xDistance target.transform.position.x transform.position.x float zDistance target.transform.position.z transform.position.z float distance Mathf.Sqrt(Mathf.Pow(xDistance, 2) Mathf.Pow(zDistance, 2)) return distance private float VerticalDistance() return Mathf.Abs(target.transform.position.y transform.position.y) My best guess is that I am using the equation correctly, but I am plugging the angle into Unity wrong. Why is my script giving me inaccurate results?
|
0 |
Unity 2D Current object force I'm working on a game with an entity firing a shot. This shot could destroy other entities as well as the entity who generated the shot. My first step was to apply a force to the rigidbody2D of the shot, but when my entity is too fast the shot destroy it (the speed does not match). I tried adding the speed to the force but the values mismatch by far (the force is a vector of like 150 magnitude, whereas the speed as a magnitude of 1). I wonder how one can achieve this, to add the current speed of the entity to the shot fired, and i wonder if there's any litterature concerning the way physics is actually handled in Unity, i find very little documentation on the Physics. Thanks.
|
0 |
How to manually kick players in new Unity Input System Using the new Unity PlayerInputManager, I'm trying to create a page in the pause menu of the game where players can remove other players from the game. It's a split screen game, and it seems to handle kicking the last player (i.e. if there were three players, kicking the third) just fine. However, if we have three players and we destroy the gameobject for player two, it seems like the player index and the screen index of player three do not automatically adjust, and the screen remains split three ways. Here's some of the code I've tried public void KickPlayer(int i) PlayerInput.Destroy(players i ) players i null for (int j i j lt 4 j ) if (j 1 4 players j 1 null) players j null else players j players j 1 players j 1 null PlayerInput pi players j .GetComponent lt PlayerInput gt () PlayerInput.Instantiate(players j , j, pi.currentControlScheme, pi.splitScreenIndex 1, pi.devices.ToArray()) PlayerInput.Destroy(players j 1 ) Although this code looks like it should rearrange and re assign the split screen, what I end up with when I spawn in three players and try to kick player two is player 0 with split screen index 0, then there suddenly are three other players, player 1, 2, and a second copy of player 2 all sharing split screen index 2. What would be the best way to go about this? Is there a way to reassign player index and split screen index?
|
0 |
No way to make asset store go online? I was trying to follow a tutorial for my first unity tests and I can't seem to convince unity that I indeed have an internet connection, short of a complete uninstall I tried about everything I could think of or find on google Running unity as an admin Reseting my TCP IP with a Microsoft tool Deactivating my firewall Deactivating windows 10 firewall for real and completelly (Because windows 10 sucks and I'd be using windows 7 if it weren't for docker) Deactivating my AV software Logging out and in from unity The browser will open the asset store no problem, I'm on windows 10
|
0 |
Two Army Battle Simulator I'm currently developing a small game project on unity (with purpose of learning C ) where each player controls a base and can build buildings, do research, build units, pretty much the basis. I arrived where the each player may send their army of different sizes to attack the other player's base. Each army can be composed of three different unit types, being Infantry, Archers and Cavalry. They work as a kind of rock paper scissors, meaning infantry beats cavalry given equal resources (horses cost more than warriors, so 1 on 1, cavalry still wins), cavalry beats archers and finally, archers beats infantry given a long distance. Every unit has different stats, health, damage, armor and range (mouvement speed exists but I do not want to consider it in battle). I want the battle to be split in rounds and that it is not because you have less soldiers than the other player that you should loose. What would be an interesting way of solving the battle taking account of all those variables ? Sort of solution I have is to give each player some decisions as to what would he do first (either archers attack first, cavalry waits for flanks, etc.) but nit seems too complicated and I still don't know how each parameter should be calculated. Should luck be included too ? Thanks, luisarcher. EDIT After comments, here is my question more clearly. What would be the best way to simulate a battle of two armies composed of those units (with their weaknesses and strengths) where both armies would loose troops in X amount of rounds ? I want the results to evolve with time so the players can react to it (either retreat, or maybe small commands). I'm not looking for a piece of code, but more of a guideline of how should I use every attribute of each unit (health, damage, armor and range). EDIT2 By best, I mean an interesting resolution where each unit feels unique to be built and where players won't feel forced to build only 1 kind of units since it has the most cost effective hp damage per amount of resource spent. I'm thinking of something like all those web based strategy games like Grepolis, Tribal Wars, oGame, etc.
|
0 |
How do I make gameobject flip and change position when player is facing left? I attached a a gameobject labeled "Gun" to my player's back and when the player is facing left I want the Gun to continue to look like it's still attached to his back. Right now when I play the game and the player is facing left, the gun stays in the same position it was in regardless of what direction the player is facing. How do I make the gun look like it's still on the players back if facing left? (sorry if it sounds like idk what i'm doing... I'm sorta new to game dev.)
|
0 |
Unity custom camera projection only working in scene editor I've found this article on Gamasutra on a custom camera projection to make 3D look more 2D and decided to implement it to make some gameplay tests. I had to make some changes to make it work on URP(on unity 2019.3.6f1) but it quot worked quot with the following code using UnityEngine using System.Collections using UnityEngine.Rendering This script is meant to be attached to your main camera. If you want to use it on more than one camera at a time, it will require modifcations due to the Camera.on delegates in OnEnable() OnDisable(). ExecuteInEditMode public class CustomProjectionTest MonoBehaviour private void OnEnable() RenderPipelineManager.beginFrameRendering ScenePreCull RenderPipelineManager.endFrameRendering ScenePostRender Camera.onPreCull ScenePreCull private void OnDisable() RenderPipelineManager.beginFrameRendering ScenePreCull RenderPipelineManager.endFrameRendering ScenePostRender GetComponent lt Camera gt ().ResetWorldToCameraMatrix() private void ScenePreCull(ScriptableRenderContext context, Camera cam) If the camera is the scene view camera, call our OnPreCull() event method for it. OnPreCull() private void ScenePostRender(ScriptableRenderContext context, Camera cam) Unity's gizmos don't like it when you change the worldToCameraMatrix. The workaround is to reset it after rendering. foreach(var camm in cam) camm.ResetWorldToCameraMatrix() private Camera cam private void Start() cam GetComponent lt Camera gt () Set the camera this script is attached to to use orthographic sorting order. Instead of using the euclidean distance from the camera, objects will be sorted based on their depth into the scene. cam.transparencySortMode TransparencySortMode.Orthographic public Vector4 up new Vector4(0, 1, 0, 0) This is a Unity callback and is the ideal place to set the worldToCameraMatrix. private void OnPreCull() var cam !Application.isPlaying? Camera.current cam First calculate the regular worldToCameraMatrix. Start with transform.worldToLocalMatrix. var m cam.transform.worldToLocalMatrix Then, since Unity uses OpenGL's view matrix conventions we have to flip the output z value. m.SetRow(2, m.GetRow(2)) Now for the custom projection. Set the world's up vector to always align with the camera's up vector. Add a small amount of the original up vector to ensure the matrix will be invertible. m.SetColumn(2, 1e 3f m.GetColumn(2) up) cam.worldToCameraMatrix m public static Matrix4x4 ScreenToWorldMatrix(Camera cam) Make a matrix that converts from screen coordinates to clip coordinates. var rect cam.pixelRect var viewportMatrix Matrix4x4.Ortho(rect.xMin, rect.xMax, rect.yMin, rect.yMax, 1, 1) The camera's view projection matrix converts from world coordinates to clip coordinates. var vpMatrix cam.projectionMatrix cam.worldToCameraMatrix Setting column 2 (z axis) to identity makes the matrix ignore the z axis. Instead you get the value on the xy plane. vpMatrix.SetColumn(2, new Vector4(0, 0, 1, 0)) Going from right to left convert screen coords to clip coords, then clip coords to world coords. return vpMatrix.inverse viewportMatrix public Vector2 ScreenToWorldPoint(Vector2 point) return ScreenToWorldMatrix( cam).MultiplyPoint(point) private void Update() if(Input.GetMouseButtonUp(0)) Debug.Log(ScreenToWorldPoint(Input.mousePosition)) Well, kinda. For some reason, it only works in the scene editor, but not in the game. I just have no clue why With Scene Editor In Game
|
0 |
OnInspectorGUI Custom properties are not displayed in the right order I basically made a lot of research and wasn t able to find any solution. So my problem I ve made some variables disappear appear depending on an enum with a custom editor script. But if they appear they do not appear at the position where the normal editor variables would appear override public void OnInspectorGUI() base.OnInspectorGUI() GunCard myScript target as GunCard EditorGUI.indentLevel switch (myScript.aimingControlType) case AimingControlType.Manual myScript.hasAimAssistance EditorGUILayout.Toggle("Has aim assistance", myScript.hasAimAssistance) break case AimingControlType.AutoTargeting myScript.targetPreference (TargetTypes)EditorGUILayout.EnumPopup("Target preference", myScript.targetPreference) myScript.requiresLineOfSight EditorGUILayout.Toggle("Requires line of sight", myScript.requiresLineOfSight) myScript.requiresPossibleTargetOnScreen EditorGUILayout.Toggle("requires possible target on screen", myScript.requiresPossibleTargetOnScreen) break EditorGUI.indentLevel Here is where they appear That are the raw variables in the scriptable object Header("Aiming Controls") public AimingControlType aimingControlType HideInInspector public bool hasAimAssistance HideInInspector public bool requiresLineOfSight TODO implement gt requires 180 HideInInspector public bool requiresPossibleTargetOnScreen TODO implement gt requires 180 HideInInspector public TargetTypes targetPreference HideInInspector public bool isAutoShootWhenAimOnTarget I know I m basically adding new variables to the inspector in my editor Script but it would be really useful to order them. Is there a way to do that? P.S sorry for the funny typo in the picture )
|
0 |
Moving spilling water inside a cup of glass I made a glass of water but there are somethings i didnt know how to do well, what i did is i put a mesh on the top of the glass to represent the surface of the water but it doesnt really work well with glass because if you look from the sides you wont really see that there is water in there, this is what i did the glass from the side as you can see it doesnt really work well in my case. I also tried putting an object that has the same shape as the cup inside to represent water but that would make it difficult for what i want to do next, because my next step would be to make the water rotate in the opposite rotation of the cup and make it spill if it reaches the top of the cup, and that is my second question how do i make the water spill from the cup? Any help is very much appreciated.
|
0 |
Exclude a certain folder from Unity? I work with a small team of three people, and we use the collaborate service within Unity to share our progress. One of the folders we have inside our Unity project is an "OffGame" folder, which includes a tool I created specifically to help with the creation of certain assets. It's not actually supposed to be part of the game, but since I'm often making changes to it, I figured I'd include it in the Unity project. The Unity project temporarily makes use of certain files inside said OffGame folder, however, once the game is done, those files will be moved outside of that folder and integrated into the game proper. Since that OffGame folder is not supposed to be part of the game and I only included it there to share it to my teammates over the collaborate service, I don't want it to be treated like a normal folder for the game. Specifically, I don't want Unity to create a bunch of useless meta files for each file in that folder, or to act like a stray .js file in there is part of the project. I actually got compile errors because Unity kept thinking it had to include all the .js files in that folder. How can I make Unity ignore that folder?
|
0 |
C invoke stops unity I'm making a game where in needs to randomly generate objects on a plane, so I setup a code to spawn Food, but whenever I run the code Unity uses up all my computers memory and 40 cpu. I have a fairly good computer and have no issue with anything else in the project. The code has worked when I called it in FixedUpdate but as soon as I try and call it in an invoke it just breaks everything. I have only started working with unity for less than 24 hours so I don't really know what could be wrong, since I didn't get any errors or warnings. using System.Collections using UnityEngine public class SpawnFood MonoBehaviour public Rigidbody Food public float x public float y public float z public Vector3 pos public float spawnTime void FixedUpdate() Start Invoke("FoodSpawn", spawnTime) goto Start void FoodSpawn() x (UnityEngine.Random.Range( 110f, 110f)) z (UnityEngine.Random.Range(0.50f, 0.51f)) y (UnityEngine.Random.Range( 50f, 51f)) Vector3 pos new Vector3(x, z, y) Instantiate(Food, pos, Quaternion.identity)
|
0 |
Apparent FPS drop despite clear CPU usage drop in profile window I have an unusual performance drop (or visual choppiness) that isn't showing in the profile window at all like I'd expect. When using Vegetation Studio Pro and AQUAS together, I get what looks like a serious FPS drop when I look up at the sky (away from terrain) or back down at the terrain. However, the moment always coincides with a major drop in CPU usage (seen in the following pic). I've never seen performance issues like drop cpu usage usually they appear as major spikes, reaching higher (meaning lower FPS) on this chart. I'm not used to the newer Unity profile window, so I may be missing some obvious clues, but what could cause such a perceived FPS drop when the cpu usage drops? Why does the VSync category seem to disappear for a period of time? I'm unable to reproduce the effects when I turn off VSPro or AQUAS. Whatever the real cause is, it seems related to them being used together. I don't see any indication of the same issue when I use them individually. Edit1 The issue goes away when I disable the Caustics system in AQUAS. It's a projector system. I still don't understand what specific issue the profiler is communicating to me.
|
0 |
How to render multiple projections of an object? I want to display multiple projection of an object on the same screen. The projection should also change as the body rotates, kind of a dynamic projection of the body. I am trying to make a character for pyramid hologram (as it has been named) which needs the projections. Here is an example found on the Internet (Image source)
|
0 |
Unity Problems with scene object orientation and rotation after updating my project from 5.0.0 to 5.2.2 Last year I made a large project on Unity 5.0.0, today I re opened it on 5.2.2 to do some work on it. I was given the message that the project needed to be updated, I allowed it to do the update. Now when I open up my scenes, many of my scene objects are misplaced, the rotation is completely wrong and positioned in the wrong place. My scenes are of a refinery and the most commonly broken object is the pipework, something that would take hours to correct manually. My pipework is created this way... All pipes are made in blender and each scene's pipes are saved as a single blender model (with each pipe make from a bezier curve and left as a separate object). Once imported into Unity (as a single .blend file), I've then dragged and dropped coloured materials onto all the individual pipes, so they are all coloured correctly. This has all been fine until updating the project to 5.2.2 now some of the pipes are in the right place, but many are rotated in completely the wrong direction, leaving it looking a mess. If I delete the pipes from Unity and reimport the pipe model back in, this would solve the problem, but then all the materials colours will be gone. Due to the sheer amount of pipes throughout the whole project, to re colour them all again would be an extremely problematic task, especially as it's critical that the pipes are the right colour. I am confused how some of the pipes within the same pipe model are fine and the others are wrong, it would be so much easier to sort if they had all changed rotation together, then I could just switch them all back in 1 go. I have a total of 13 scenes and so far all of them have suffered the same problem. Nothing whatsoever has been changed on any of the scenes, assets or indeed anything in the project folder. In fact I haven't touched a single file within the project since October last year, so it is certainly to do with updating to 5.2.2. Is there anything I can do to fix the problem without having to re import the models back in or manually rotate everything back? I have attached some screenshots to show the issue See how in the blender image, all the pipework is placed correctly and then in the Unity image, half the pipes have flipped and are facing the wrong way. I have removed the ground so this can be seen clearer. Any help would be much appreciated. Many thanks
|
0 |
Why is an empty Unity Iphone Build over 700 Megs? Is this Normal? So after 2 weeks of slaving over my first game I was finally done! I was entirely ecstatic....until I saw its file size. 770 Megabytes For a simple numbers game, that was way too much and I created an empty unity project as a test and that was also over 700 megs Why is an empty Iphone project this large?
|
0 |
SteamVR No Longer Opening With Unity Projects I'm trying to get Unity to open utilize SteamVR for development. Everything was working fine until today, but now Unity does not use SteamVR. I did not make any changes to SteamVR recently, and I get the same results on multiple projects and Unity installs. I also tried rebooting. It looks like Windows pushed an update today for KB4023057 but I can't uninstall it. It's not found within uninstall updates, not in add remove programs, and even using command prompt wusa uninstall kb 4023057 results in quot KB4023057 is not installed. quot So it seems I'm stuck with it. Any other ideas to either try to uninstall the update or else to somehow get SteamVR working in Unity again?
|
0 |
How can I make car respawn with temporary invulnerability i.e. no collisions? I'm using Unity's standard assets scripts to move my car, but the camera just follows the road. At certain moments when the car misses or overturns the player can press 'R' to reposition the car in the middle of the road in the position where I miss or turn over. When the car respawns, it should not collide with other cars in the race, for a few seconds. After those few seconds everything returns to normal. I thought about using layers, but I did not find how to modify the "Layer Collision Matrix" dynamically from a script. How do I do that?
|
0 |
Unity too many batches There are 64k cubes, 64k 1 's materials are assigned to sharedMaterial of first cube. But unity is not batching them together. Only cubes themselves are batched. Static color(but different per cube) Dynamic position and rotation per cube How can I force unity to batch them all so it sends all cube data with only an array then draw once instead of drawing 64k times? Each cube has a constructor as public class Test MonoBehaviour public static System.Random r get set Use this for initialization public static Material m null void Start () if (r null) r new System.Random() sayac if (m null) m GetComponent lt Renderer gt ().sharedMaterial else GetComponent lt Renderer gt ().material m GetComponent lt Renderer gt ().material.color new Color((float)r.NextDouble(), (float)r.NextDouble(), 1) var mesh GetComponent lt MeshFilter gt ().mesh var vertices mesh.vertices var colors new Color vertices.Length var i 0 while (i lt vertices.Length) colors i new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble()) i mesh.colors colors mesh.UploadMeshData(false) mesh.Optimize() and they are instantiated from a cube as for(int i 0 i lt 1024 64 i ) var pos new Vector3(i 64, (i 64) 64, (i 4096) 64) pos 2.5f var cu Instantiate(ref cu, pos, Quaternion.identity) cu .name "cube " i After deleting 'material.color' lines, batching has started. But now cubes are not easily seen as with different colors. I need them different colored but not changing. Static color but different per cube. How it looks now its not easy to see individual cubes. public class Test MonoBehaviour public static System.Random r get set Use this for initialization public static Material m null void Start () if (r null) r new System.Random() sayac if (m null) m GetComponent lt Renderer gt ().sharedMaterial else GetComponent lt Renderer gt ().material m
|
0 |
How do you get audio clips to play on all clients? I am new to networking with so this is probably a noob question. For context I am trying to get a gunshot sound effect to play and be heard by all players.
|
0 |
score and high score system for multiple levels I'm trying to create a scoring system for a game with multiple levels. For this I'm using the binary formatter instead of playerprefs (I read online that playerprefs are not that secure). I have created the system but whats happening is that the score is not resetting to 0 when I load a new level. If in one level the score was 10 and I start some other level, the score in this level starts from 10 instead of 0. This is the code I have so far public class ScoreIncrease MonoBehaviour public Text scoreTxt public int score void Start() LoadScore() void Update() if (Input.GetKeyDown(KeyCode.Space)) Save() public void Save() score scoreTxt.text "Score" score BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " scoreContainer.dat", FileMode.Create) ScoreContainer scoreContainer new ScoreContainer() scoreContainer.score score bf.Serialize(file, scoreContainer) file.Close() public void LoadScore() if(File.Exists(Application.persistentDataPath " scoreContainer.dat")) BinaryFormatter bf new BinaryFormatter() FileStream file File.Open(Application.persistentDataPath " scoreContainer.dat", FileMode.Open) ScoreContainer scoreContainer (ScoreContainer)bf.Deserialize(file) file.Close() score scoreContainer.score scoreTxt.text "Score" score Serializable public class ScoreContainer public int score How can I change this so that each level has a separate highscore and all levels have a start score of 0?
|
0 |
Visual Studio not updating files made in Unity In the past Visual Studio simply updated solution based on files added in Unity but now all of them have to be added manually and they are as miscellaneous when they are added. How can I fix it?
|
0 |
Can we create same name class for different objects in unity? I have four similar objects in my game. As they are all similar therefore I have created a single script that defines mash for all of them. The script that defines mash for these objects uses a variable called radius which I have imported from other file (by classname.radius). The radius updates on every frame and it is the only property that is different for all objects. To allow different radius for different objects, What I thought would work was, making four different classes of same name classname. Creating variable radius in all of them and giving them different values. Dragging first file to the first object, second file to second object and so on.. When executed, every time the script that generated mash considers classname.radius from the file which is dragged to that object. But that isn't working. What is wrong and how can I implement it? Seems I'm messing with OOPS concepts!
|
0 |
What file types should I exclude from my game's source control repository? I have started working on a personal project using Unity with a friend and we've set up our own source control system. I am aware of the fact that there are many types of files, namely those that are generated locally when you build (for example, Visual Studio files) and those that are specific to your particular machine that should not be added to source control, but I'm not exactly sure what these file types are. I don't want to exclude any generated files I should be including, such as .meta files. Would someone be able to list all, or at least all of the common file types that should not be added to version control, specifically for a Unity project?
|
0 |
How to split a group of tiles in a grid into separate groups if a break occurs between tiles? I have a grid where objects can be placed down by the player. Each object that gets placed down is added to a dictionary where the key is the grid position. Each object that gets placed down either gets added to a new zone, or added to an existing zone if any of the neighbors are in an existing zone. If there are multiple zones, then it just picks the first one it finds and adds it. The issue I am struggling with is how to handle splitting up zones if an object is removed from the grid. In the first image I have 2 zones. In the second image, I add a new object to the grid, because that tile contains 2 neighbor tiles that are in a zone, it merges the 2 zones into one. In the third image, I remove an object from the grid, which removes it from the zone, and in this case it creates 2 new zones (but could be more depending on neighbors). This is where I am struggling to work out the best way to efficiently do this. I have a grid array that holds all objects placed on the grid. A zone contains a list of tiles that are in that zone. Each tile in a zone also gets a zone id. What would be a fast efficient way of splitting up a zone into multiple zones? I thought about checking all the tiles in the zone by checking its neighbors, but thought that it could be quite slow, as a zone can grow to be very big over time (zones can auto merge as well). Also wouldn't there be a chance of an endless loop?
|
0 |
Raycast can't hit my player I have been trying for the past 5 hours to get this to work. So i have an enemy that has the following script private bool Look(StateController controller) Debug.DrawRay(controller.transform.TransformPoint(controller.mCombatant. CombatOffset), controller.transform.TransformDirection(Vector3.forward) 800, Color.green) RaycastHit hit if (Physics.SphereCast(controller.transform.TransformPoint(controller.mCombatant. CombatOffset), 360, controller.transform.TransformDirection(Vector3.forward), out hit, 800) amp amp hit.collider.CompareTag("Player")) controller.mCombatant.Target hit.transform controller.chaseTarget hit.transform return true else return false return false Now both my enemy (the one this script is attached to) and my player are on the default layer Here are some images that shows the gameview As you can see from the above picture The "Ray" should hit the player My Player prefab looks like this So my question is what have i done wrong? EDIT So after alot of time i managed to make the following code work (however its a normal raycast ( ) RaycastHit hit if (Physics.Raycast(controller.transform.position, controller.transform.forward, out hit) amp amp hit.collider.CompareTag("Player")) var g 0 This is good but not good enough since i want the vision of my enemy to be more than a straight line (
|
0 |
Shader Graph, add color outline to 2D Sprite I'm having trouble creating a shader in Unity Shader Graph (2D) that fills the image from the bottom to the top and adds a color outline along the visible part of the sprite. I can fill the image and that seems to be working. I can't however add the color outline. I figured it has something to do with using the inverse alpha of an image, but since i'm pretty new to shaders in general I find it hard to implement it. This is what i currently have As you can see I have the substract node there for the inverse alpha. I'm pretty stuck as to where to go next. I cannot seeme to find a relevant tutorial online. I tried implementing a Fresnel effect, but that seems to only apply to 3D images (i had tried to replace the Master with a PBR master and attaching the fresnel, but it had no effect). What would be the correct approach from here to add the color outline to the sprite, taking in account the vertical fill?
|
0 |
Unity Issue applying Render Texture to object imported from Blender I'm new to Unity and am trying to create a sort of CRT computer monitor terminal with text. To draw the text, I set up a Text Mesh Pro with its own camera, which renders to a Render Texture. I then designed a simple computer monitor model in Blender split into two objects one for the glass part of the screen, and another for the 'rest' of the monitor exterior case. I saved a copy of the .blend file into the Assets folder and imported this into Unity. My blender model (two separate objects, with the separate "screen" piece moved out of the screen) When I try to apply the Render Texture onto the screen object, the texture is rotated 90 degrees anti clockwise and is too zoomed in I can't seem to rotate the texture so that it is the right way up to read the text, and only some of the text is visible. I have tried rotating the object 90 deg. clockwise in Blender and "applying" the transform so unity then thinks the object is oriented correctly. this still caused the texture to be rotated. I also tried exporting as an .obj file, with "Up" set to "Y Up", but this didn't work. I then tried applying the Render Texture to a material, which I then applied to the screen object which didn't work either. If I apply the texture to a standard cube in Unity, it works fine and is rotated and scaled correctly to fit the cube. How can I get the blender object oriented correctly so that the Render Texture applies in the correct orientation and scales so the whole of the Render Texture fits and is not zoomed in? I'm using Unity 2019.3 and Blender 2.82.
|
0 |
How to detect a pinch in Unity? How do I detect a pinch motion on Unity for an android or Iphone? I need to also know whether the player pinches a certain character or not. How do i do that?
|
0 |
Unity2019 PrintDocument ignoring 'DefaultPageSettings.Landscape true' So I'm trying to print from Unity in landscape and while I can get it to print just not in landscape. So I create a PrinterSettings Object in 'void Start' and set the printer and tray from dropdowns... and that part appears to work but it's fully ignoring the Landscape property. public void ShowDialog(string filePath, bool isLandscape) PdfiumViewer.PdfDocument pdfiumDoc PdfiumViewer.PdfDocument.Load(filePath) printDocument pdfiumDoc.CreatePrintDocument() printDocument.DocumentName quot Print Document quot isLandscape isLandscape printPanel.SetActive(true) public void Print() int index paperSourcesStrings.IndexOf(SelectedPaperSource) printDocument.PrinterSettings printerSettings printDocument.DefaultPageSettings.Landscape isLandscape if (index ! 1) printDocument.DefaultPageSettings.PaperSource paperSources index printDocument.Print() printPanel.SetActive(false)
|
0 |
Trying to leave a trail of particle effects with a Particle system attached to an Object Unity C I have a particle system attached to my game object, which starts to emit particles when I press down the "W" key and stops when I release it. The particle system works fine, but when I rotate the object, the particles rotate with the object. I would like to have the particles leave behind a trail of the path of the object. Script below public class Motor MonoBehaviour public ParticleSystem EngineLeft public ParticleSystem EngineRight Use this for initialization void Start () Update is called once per frame void Update () if (Input.GetKey(KeyCode.W)) transform.Translate(Vector3.forward Time.deltaTime Speed) if (Input.GetKeyDown (KeyCode.W)) EngineRight.Play () EngineLeft.Play () if (Input.GetKeyUp (KeyCode.W)) EngineRight.Stop () EngineLeft.Stop ()
|
0 |
How can I implement an inventory that stores different types of items? Let s assume I want to create an RPG with collectible items my character can pick up and store in his inventory. One item could be a sword, with an attack, defense, and level attributes. Another item could be an apple, heal percentage, freshness, and servings attributes. Both items are collectible items, and both objects can be stored in the players inventory, but they share separate sets of attributes. I am trying to think of a way to set this up in the database. I originally looked to the EAV database model, so I could define a single collectible item entity, and bolt on separate attributes as I needed them, but I discovered EAV is slow because of multiple calls to the database to construct an entity, which wouldn't make it very suitable for a game in my eyes. I also can't find any game development tutorials that use EAV, so there must be a more common solution I'm not aware of.
|
0 |
Time passing display on UI in Unity in C How can I display the time and how many days on a UI in Unity. Time would be moving faster like a week in 7 minutes? Should I use Time.deltaTime and how do I excellerate the time it displays?
|
0 |
Is built in checking Android iOS permissions on runtime possible? I have a game with some levels, coded to both Android and iOS. One of the levels late in the game uses a Microphone, so the app asks the user at the start (at the start of the application) to accept the Microphone permission. If he does accept, everything is fine. If he doesn't, Microphone.Start() method doesn't really work and I can't do anything about it. What I should do is that in level's start() I should check if he has the permission and handle it, but... I can't find a built in way to check that on both Android and iOS. Is there any, or I should download two different libs (for both platforms) and check it natively? This is what I've tried audio.clip Microphone.Start ("Built in Microphone", true, 999, FREQUENCY) Debug.Log("CLIP " audio.clip) not null if(audio.clip null) GameManager.Instance().ForceComplete() return try audio.Play () catch(Exception ex) no exception here GameManager.Instance().ForceComplete() return ...
|
0 |
To Unity Rigidbody move like Character Controller on collision I want to a blue ball moving like a figure. in CharacterController, it was possible. but in Rigidbody, object was stucked. help me.
|
0 |
GameObject.Find() finds objects in the old scene I'm trying to create a simple scene transition. On entering a collider, there is a black canvas that's slowly faded in over the duration of 3 seconds. Then, a new scene is loaded, and the scene slowly fades from black to invisible. Now, I've almost finished it. However, I'm running into a small problem I cannot seem to fix. The animation consists out of two text elements and one image. The hierarchy looks like this SceneLoader is an empty object, SceneFader is a canvas. Image is a black image stretched across the screen, and RegionName and RegionSubtext are two text elements that are filled as soon as the transition begins. The code I'm using to load the scene is this private IEnumerator loadSceneWithTransition(string sceneToLoad, Vector3 spawnCoordinates, string regionName, string regionSubtext) this.screenFade.SetTrigger(SceneLoader.AnimatorTrigger) GameObject.Find("SceneLoader SceneFader Image RegionName").GetComponent lt Text gt ().text regionName GameObject.Find("SceneLoader SceneFader Image RegionSubtext").GetComponent lt Text gt ().text regionSubtext yield return new WaitForSeconds(4f) SceneManager.LoadScene(sceneToLoad) GameObject.Find("SceneLoader SceneFader Image RegionName").GetComponent lt Text gt ().text regionName GameObject.Find("SceneLoader SceneFader Image RegionSubtext").GetComponent lt Text gt ().text regionSubtext GameObject.Find("Player").GetComponent lt PlayerMovementController gt ().spawnCharacterToLocation(spawnCoordinates) Now, this doesn't work as I'd expect it to. The first part runs perfectly fine The animation is started, the text is displayed and the scene changes. However, that's the part where everything breaks. As soon as the scene loads, there is no text. Also, the player position is not set to where it should be. I really do not know why, the only reason I could think of was that the script was called in the first scene, and therefore, the GameObject.Find() calls return the elements in that scene, not in the currently used one (actually, I'm fairly sure of that because GetInstanceID() returns the same for both calls). Now, the problem at this part is that I do not know how to make that work properly. One idea I had was to do try and fetch a new instance of the script with something like GameObject.Find("SceneLoader").GetComponent lt BaseSceneLoader gt () and work with that, but then I remembered I still need GameObject.Find() for this, which would probably yield the result of the old scene, so it's not helping at all. On top of that, I'm not even sure if that is the actual problem. I'm kinda out of ideas here. I also do not know what's the best practice in that situation, and I couldn't find anything meaningful on DDG either. Lastly, I've created a small video clip showing off the problem. I hope this helps in identifying the issue. https imgur.com a 1eS8rcG
|
0 |
How to approach in game character creation system alike Sims I would like to implement an in game character creation similar to the Wii Mii system or The Sims using Blender and Unity. In what ways is this possible, other than (or in conjunction with) using shape keys? The ideal system would have 2 4 body types, 8 hairstyles, full RGB skin hair toning (I quite like Terraria's style), and a few styles for faces. I have been looking into this topic, but so far I have not found a good explanation as to how this would be implemented, and blender shape keys would allow for some aspects of this namely body and hair manipulation but would not work for coloring or styling the face.
|
0 |
Unity Check if object is facing Vector3 coordinates I am having a hard time figuring this out, I want to have objects that move around randomly, and when they get new coordinates to move towards, face them, and then move. Here's explained Target moves towards point A. Target reaches point A. Get new coordinates. Rotate towards the new coordinates WITHOUT moving When facing the new target coordinates, start moving I am trying it with Raycast, but it doesnt work, it tells me it always looks at them... if (Physics.Raycast(transform.forward, randomTargetCoords, out hit)) Debug.Log("spotted") I want to project the ray from the front of the object to the target coordinates (Vector3), and if true, do any code inside the if method. How can I do it? EDIT Here is the code for moving and rotating the object transform.position Vector3.MoveTowards(transform.position, targetCoords, moveSpeed Time.deltaTime) transform.rotation Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed Time.deltaTime)
|
0 |
Low Res Atlas Texture vs. Many different materials without textures So I have recently started to look into optimizing a medium complex 3D scene, more specifically i am looking to improve the performance i get from a fairly realistic bus. I am currently using the Unity3D standard shader. There are a lot of different objects within the scene, most of which are repeated and instanced. While many individual objects require only limited color variance often enough just a solid color and no texture at all. I have read a lot about batching and atlasing but can't quite find an answer on the trade off of using textures when no textures are required. I understand that reusing the same material allows for batching and can greatly reduce the amount of draw calls, however how does this compare to the complexity of texture mapping if this could be avoided entirely? Is it still good practice to atlas solid colors on very low resolution atlas textures and thus combine materials together? How does it look if i intend to use metallic and smoothness maps as well? Does it all come down to scene complexity and a number game or is there a straight answer? I have the same uncertainty when it comes to objects which are made up of an arbitrary single digit number of solid colors given supporting geometry, is it better to assign different materials with solid colors to regions of the object or create low resolution textures? In general what is the point at which atlasing becomes the worse choice? Thanks in advance!
|
0 |
How does Against The Wall create an infinite wall? There is a game called Against The Wall, developed by Michael P. Consoli. It's a fantastic game, as I've always been stumped at how the game creates an infinitely spanning wall. In the game, you can fall forever, and the wall will keep spanning. I can fall as long as I like, and still be able to climb back to where I was before. The game is developed in Unity. How can a game do this without crashing, or creating some kind of memory overload?
|
0 |
Prefab not working when I import maps form Tiled using Tiled2Unity I have correctly created the map using Tiled with no errors or warnings, then i imported the package from tiled2unity, imported the map then waited few seconds and the prefab from tiled2unity appears only after some minutes but not working. the tiled to unity package imported The error the map Basically i dont see the tiled map in unity after it's imported.
|
0 |
Access buttons individually made by a for loop (old Unity GUI, Unity Editor script) I've got a problem and I am struggling with this for a couple of days now. I am making an Editor script and I want to access buttons individually when created by a for loop. There is a public class ButtonNode which stores some variables of the button like name and size. public class ButtonNode public bool button public string name "O" public float sizeW 25f public void AlterButton() name "P" Then there is my Editor script in which I create the buttons. This is where I get stuck, how do I access these buttons individually? For example, I want to change the name of the button when that button is clicked. How do I do that? Because they are booleans (I don't really know why, this is the legacy GUI) I can't access the transform.name components etc). public static ButtonNode bn new ButtonNode 10 void OnGUI() GUILayout.BeginHorizontal() for (int i 0 i lt bn.length i ) bn i new ButtonNode() if (bn i .button GUILayout.Button(bn i .name i, GUILayout.Width(bn i .sizeW))) bn i .AlterButton() GUILayout.EndHorizontal()
|
0 |
Unity Timeline character transform initial values I'm trying to make a runtime cutscene in Unity using the Timeline editor. I have a humanoid character with an animation controller, track and a cinemachine track set up in the playable. The timeline starts playing onTriggerEnter() through script. Initially I applied the track offsets and the timeline plays perfectly in the editor but in play mode the player swaps to random positions in the world and it looks really ugly. So I changed the track offsets to scene offsets and it's almost works perfectly except that the position and rotation of the character are relative to the input just before the character enters the trigger (all input is disabled on trigger entered). What I intend to do is set a default position and rotation to the character at the beginning of the timeline. Is there any way to achieve that within the timeline editor, if not how else could I do it?
|
0 |
Can't set object's local rotation like rotating from gizmo in the scene Here, I have a plane model with some sub parts(like aileron) can rotate That red section is weight painted(rigged) vertices, and I need to control the rotation of this in Unity by script. So this is the image in Unity, rotating through green ring(along x axis) of aileron bone from gizmo works exactly I want. However as you can see in the inspector, I rotated along X axis but it doesn't changed only x axis, it also changed other axis like Y and Z. So when I just rotate X rotation of aileron from the script or inspector, it gives me total wrong rotation, and here is the solution I got How to rotate object just like in the scene? So I wrote the code leftAileron.Rotate(0, value, 0) Now it rotates desired angle but the problem is transform.Rotate method is just rotating the object, means adding the new value to current rotation. In my case, I need to "set" the rotation, not adding it, because it gives wrong rotation in this case. I made a slider for explain and demonstrate my problem here is the slide and it's range is 5 to 5 and default is 0. The code for rotating aileron is this sliderLeftAileron.onValueChanged.AddListener((value) gt leftAileron.Rotate(0, value, 0) ) When I moved slide to left, value goes negative so it rotates like this. But when I slightly moved the slide to right, it still rotate same direction because the value is still negative and just try to adding it. So I need to set the rotation of aileron, not adding it, moving slide to right should moves opposite direction and vise versa. Is there a way to set rotation just like Rotate(0, value, 0) but not adding it in this case, like this transform.rotation Quaternion.Euler(0, value, 0) I tried bunch of ways but none of them worked, how do I treat my aileron rotation just like in gizmo in the scene?
|
0 |
2d games unity vs Flash do people find unity better than flash for 2d games while unity is 3d engine , or Flash still better because it's made for 2d games and flash can get the job done faster ,and now flash is better for ios android 2d games . so what platform is the best for 2d games?
|
0 |
How can I gradually increase the speed of my game? I recently made a replica of (Dino run) game in Unity2d. But I'm stuck on how can I speed up my game gradually. Should the game speed be increased or should I increase the speed of the camera. Here is my spawn obstacles script. public class SpawnObstacles Monobehaviour public GameObject obstacles private GameObject obj private float XPos 0 private int number 0 private float randomPosition 0 Start is called before the first frame update void Start() InvokeRepeating("Spawn", 1.5f, 1.6f) private void Spawn() if (GameObject.Find ("Cube").GetComponent lt Cube gt ().isDead false) number Random.Range(0, 12) randomPosition Random.Range(19, 29) XPos transform.position.x randomPosition obj obstacles number as GameObject Instantiate(obj, new Vector2(XPos, obj.transform.position.y), Quaternion.identity)
|
0 |
Click event doesn't trigger when clicking I've made some buttons on my screen to navigate to other scenes of my Unity project but the Click(string command) method doesn't trigger. I've placed a breakpoint on the bold line in code below, but the pointer never hits that point. public class GameNavigation MonoBehaviour public void Click(string command) switch (command) case "again" Application.LoadLevel(Application.loadedLevel) break case "go to menu" Application.LoadLevel("Navigation") break default break Here are also some screenshots form my Unity project. What did I wrong? Note one I've made also this code that is called after the scene ends. the parameter command is always an empty string. public void RestartLevel(string command) switch (command) case "again" Application.LoadLevel(Application.loadedLevel) break case "go to menu" Application.LoadLevel("Navigation") break default break If I place it in a comment, I get this error 'Player' AnimationEvent 'RestartLevel' has no receiver! Are you missing a component? Note two I also use a mouse down event for when the player must shoot. Update one by a comment below I've made this code public Button btnAgain public Button btnMenu public void Start() btnAgain.onClick.AddListener(() gt Application.LoadLevel(Application.loadedLevel) ) btnMenu.onClick.AddListener(() gt Application.LoadLevel("Navigation") ) The Start() method is always called, no problems with it. But the Application.LoadLevel(...) code never executes when I click on the methods. However btnMenu and btnAgain aren't null. Update two I've upload a zip file on my SharePoint that you can access. Start a game and choose level 01. You navigating to a new scene. On that scene you have on the right below side you have two buttons, these are the buttons that doesn't work. If you can find the problem, please give me the solving of the problem. Other bug fixes are also welcome. 128521
|
0 |
How do I make an infinitely scrolling background? I am trying to make a game where a torpedos keep coming from random directions and the player has to maneuver a submarine to escape them. I am currently offsetting the background to give it an illusion that the submarine is moving i.e. if the submarine moves forward, I move the background (quad) backwards. This is primarily being done as I want it to be an infinite space. The position of the submarine does not change, the player just controls the rotation of the submarine and the background moves in the opposite direction. The background is set to repeat to give it an infinite space illusion. The torpedo gets spawned at a random distance and moves towards the submarine. Since, the position of the submarine does not change, the torpedo will always hit the submarine. How do I structure this game, specifically the background repeat so that I can actually move the submarine in absolute dimensions and still maintain the infinite space illusion?
|
0 |
How to detect if a 2D object overlaps any other 2D objects I am programmatically placing 4 large dots on my 2D scene which already has some objects on it. If the new dot overlaps an existing object I want to destroy the existing object. All the objects have 2Dcolliders and all are on the same layer ( quot Action quot ). Since I only do this once during the initial setup of the game I don't want to use collision detection events, instead it would seem that Collider2D.OverlapCollider would be the way to do this but I can't get it to work. The following code is called from Start() after all the objects have been placed, and thinking it might be something to do with the colliders not being active until the first frames, I also called it from a mouse click with the same result (no overlaps). void EraseOverlapDots() GameObject largeDots GameObject.FindGameObjectsWithTag( quot LargeDot quot ) foreach(GameObject ldot in largeDots) Debug.Log( quot Object quot ldot.tag quot ( quot ldot.transform.position quot ) quot ) Collider2D collider ldot.gameObject.GetComponent lt Collider2D gt () ContactFilter2D contactFilter2D new ContactFilter2D() contactFilter2D.SetLayerMask(ldot.layer) contactFilter2D.useLayerMask true List lt Collider2D gt collisions new List lt Collider2D gt () int colCount collider.OverlapCollider(contactFilter2D, collisions) int i 0 foreach (Collider2D col2d in collisions) i Debug.Log( quot HIT quot i quot quot col2d.tag quot ( quot col2d.transform.position quot ) quot ) In an attempt to debug this I purposely put 4 small dots in exactly the same position as the large dots to ensure they overlap. When I run the game they are visibly exactly on top of each other but the result is always zero overlaps.
|
0 |
How do I get the local player? I'm using Mirror as UNet is deprecated. How can I get the local player GameObject in my code?
|
0 |
Android split build manual obb file download necessary? I have an apk built with Unity 5.0.1 that has over 50MB. Google Play does not accept files over 50MB so I have to make a Split Build as covered in the Unity manual http docs.unity3d.com Manual android OBBsupport.html Now it says that I need to download the obb file manually. On the other hand, elsewhere I read that all apps that are downloaded from the play store are already downloaded with the obb file. So which one is it? Do I have to use the Google Play Obb Downloader or not? Where is the downloaded obb file stored in the filesystem?
|
0 |
Position of Gameobject Changes When Hit Play Button I have a 3D Humanoid model. When I press play button, suddenly position of model changes and collider doesn't match with model.
|
0 |
Can I add rigging bones to a model imported from Blender inside Unity? I created a model in Blender but recently I stumbled upon a video claiming that you can add rigging to a model in Unity. So instead of rigging in Blender, is it possible to do it in Unity?
|
0 |
Flip x when direction of the movement changed in Unity What is the easiest and the most efficient way to flip x of the SpriteRenderer when direction of the movement changed in Unity? I use Input.GetAxis() in order to get user input. When it returns 0 I would like to do nothing, when it returns positive number I would like to have x flipped in SpriteRenderer in one side and when number returned is negative another side. So far I come up with a solution of using a variable which will be keeping the info about to which side the player is turned and flip x if necessary. But I am sure that this is not an efficient way to do it and even not a convenient one since my code will tend to become a lot bigger and messier.
|
0 |
How do I make my character stop going left in Unity? I have this code and my character can go left, right and jump. I don't want the character going left, so how can I remove that. (I'm very new with coding) public class Player MonoBehaviour public float maxspeed 10f bool facingRight true Animator anim bool grounded false public Transform groundCheck float groundRadius 0.2f public LayerMask whatIsGround public float jumpFocre 500f bool doubleJump false void Start () anim GetComponent lt Animator gt () void FixedUpdate () grounded Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround) anim.SetBool ("Ground", grounded) if (grounded) doubleJump false float move Input.GetAxis ("Horizontal") anim.SetFloat ("Speed", Mathf.Abs (move)) GetComponent lt Rigidbody2D gt ().velocity new Vector2(move maxspeed, GetComponent lt Rigidbody2D gt ().velocity.y) void Update() if((grounded !doubleJump) amp amp Input.GetKeyDown ("up")) anim.SetBool("Ground", false) GetComponent lt Rigidbody2D gt ().AddForce(new Vector2(0, jumpFocre)) if(!doubleJump amp amp !grounded) doubleJump true void Flip() facingRight !facingRight Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale
|
0 |
When the motion button is pressed, the shape of the character changes and always goes to the left direction good day. When the motion button is pressed, the shape of the character changes and always goes to the left direction. Why is this happening and what is the solution? Pressing two buttons moves to the left and the shape changes. using System.Collections using System.Collections.Generic using UnityEngine public class PlayerKontrol MonoBehaviour public float karakterHizi 8f, maxSurat 4f private Rigidbody2D myRigidbody private Animator myAnimator private bool solaGit, sagaGit void Awake () myRigidbody GetComponent lt Rigidbody2D gt () myAnimator GetComponent lt Animator gt () void FixedUpdate () if (solaGit) SolaGit () if (sagaGit) SagaGit () public void AyarlaSolaGit (bool solaGit) this.solaGit solaGit this.sagaGit !solaGit public void HareketiDurdur () solaGit sagaGit false myAnimator.SetBool ("run", false) void SolaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0)) void SagaGit () float Xdurdur 0f float surat Mathf.Abs (myRigidbody.velocity.x) if (surat lt maxSurat) Xdurdur karakterHizi Vector3 yon transform.localScale yon.x 0.3f transform.localScale yon myAnimator.SetBool ("run", true) myRigidbody.AddForce (new Vector2 (Xdurdur, 0))
|
0 |
How do I move an object towards a moving object? I am trying to make an AI that tries to move towards the player but I don't know how. I tried using Vector2.MoveTowards() but it just mimics my movements instead of moving towards the player. I tried everything i could think of (which was not a lot D) but i couldn't make it move towards and touch the player! Help please D. Also my original code pragma strict var speed float 100 var targetX Transform var targetY Transform var mex Transform var meY Transdorm function Update () var targetX transform.position.x var targetY transform.position.y var meX transform.position.x var meY transform.position.y Vector2.MoveTowards(Vector2(meX, meY), Vector2(targetX, targetY), speed)
|
0 |
Problem with animations from Blender I have a model that I made in Blender and also I have a gun reloading animation, the model has a rig. So it appears that the animation of the rigged model is devided into 25 different animations but in Unity I can't play all of them at once, if I play only one animation from 25 it will only animate one object (eg. hands) not the magazine or anything else. My question is how is it usually done to play animations from Blender in Unity properly or make animation properly in Blender.
|
0 |
Pause on scrolling backgrounds I have a typical parallax backgrounds. They are scrolling by public float Speed 0f void Update () renderer.material.mainTextureOffset new Vector2 (Time.time Speed,0) I have a character. OnKeyDown he starts to move Speed of background sets to 0.4f for example. OnKeyUp a character stops by setting the speed of background 0f. The problem is when backgrounds stop to scroll, they return to its start position. They must just to pause the position. How to do?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.