_id
int64
0
49
text
stringlengths
71
4.19k
0
Unity3D Multiple OnTriggerEnters are called before the first one could finish and destroy the object I'm working on a projectile which explodes when it reaches a destructible object and damages its voxels. (The projectile is a trigger) But the problem is that I use raycasting in OnTriggerEnter which makes it slow to finish. Which lets multiple OnTriggerEnter to be called before it could be finally destroyed. I fixed it by having a flag which lets only one call to be executed. But it feels a bit hacky, so I decided to ask you, maybe you have some better solutions. void OnTriggerEnter(Collider collider) if (!hit amp amp LayerMask.LayerToName(collider.gameObject.layer) "Destructible") hit true DoImpact() Destroy(gameObject) void DoImpact() Do 1 SphereCast RaycastHit hits Physics.SphereCastAll(transform.position, ExplosionRange, transform.forward, 0.0001f, 1 lt lt LayerMask.NameToLayer("Destructible")) Iterate through voxels foreach(var hit in hits) the parent object which manages its voxels var destructible FindDestructibleParent(hit.transform) Make some damage to that voxel based on the projectile, the voxel, and some "whole container parent object properties" destructible.TakeDamage(this, hit.transform.gameObject)
0
How do I override a SteamVR Controller's transforms in Unity? I'm trying to provide an illusion to the user by rotating the controller about an arbitrary axis in the LateUpdate() method. But this doesn't seem to be having any effect as the controller probably is constantly getting updated by its real world location. Is there any way to override its real world position and orientation with a transformation in script?
0
How to dynamically create an UI text Object in Unity 5? I have been searching for something that should be simple, but Unity 5's documentation on that is fairly outdated. What I want to achieve is to be able to create UI Text totally from script, i.e. fully dynamically in my real case application, I will do that in a loop of not pre defined number of iterations. A search using Google will find quite many examples on how to do that, but all I saw either use methods that are already deprecated (are from before Unity version 5) or are simply wrong (no surprise here...). I already know that I should first add a Canvas to my project, then I should include using UnityEngine.UI in my C code, and also that I could declare a UI Text like Text guitext. However, the code below does not work. I mean, it's not that it crashes, but rather that nothing is shown using UnityEngine using System.Collections using UnityEngine.UI public class MyClass MonoBehaviour Text guitext Use this for initialization void Start () guitext.text "testing" Update is called once per frame void Update () Worse than that, it seems that while game is played, no new object appears in the object hierarchy list. Could you please point me out in the right direction here? Thanks.
0
Spriterenderer on top of canvases I have two canvases. One with a background image and one with all overlaying elements like texts and such. The background canvas has an order of 0, the overlay canvas of 1. Now, I'd like to create an animating sprite on top of those canvases but I can't for the life of me get the sprite on top of the other images. I can see the sprite being on top on the stage, but when I switch to gameview, it's gone! There are no scripts attached to the sprite. Only an animator(Which works fine when I play it). Note My canvases have a render mode of Screen space Overlay. I've set the spriterenderer on Sorting Layer 9, order 300. Although it's the only sprite out there. layer 1 or order 1 didn't do anything different, though. The other elements in the canvases are either UI texts or Images All the elements in the canvases are on either BackgroundLayer or OverlayLayer The canvases themselves are on the UI layer
0
How to decompose a 4x4 TRS transformation matrix with negative scale? As the title says I need to decompose 4x4 TRS transformation matrices and extract the proper scale vectors and the proper rotation vectors (or rotation quaternions). I know how to extract those information when the upper 3x3 matrix determinant is not negative. The problem is that those matrices can have that negative determinant and as far as I could understand, this negative determinant indicates a flip or mirrored transformation. What do I have to do to extract the proper values for scale and rotation in those cases?
0
How can I obtain the file size of a Unity build at runtime? I'm wondering if it is possible to obtain the filesize of a game's build at runtime. Searching this topic only yields results for reducing the build size, which is not at all what I'm looking for.
0
Best practice for toggling between ragdoll and CharacterController One feature of the game I'm working on is that if a character is hit with a certain amount of force, it will temporarily ragdoll, then get up off the ground after a small period of time. This character is moved by a CharacterController (CC) component. At the moment, I have the model as a child of an object with a CC component and movement script. My issue is that when the ragdoll is activated animator is disabled, the model moves independently of the CC if it ragdolls with some arbitrary force in any direction, the CC does not move with it (as you'd expect). This would be fine if the ragdoll wasn't meant to be re enabled, but it is. At this stage, the model teleports moves to where the CC is, and it looks very weird. I have tried a few different methods to synchronize the two Decoupling the CC and model. Both objects are children of a shared parent, and I added them both to an PhysicsIgnoreLayer (for now eventually if I go with this I'll probably add all the ragdoll colliders to an array and ignore them individually). When the ragdoll state is enabled in the parent, the CC is disabled and the object is teleported to the root bone every frame. When the CC is enabled, the model is teleported to the CC object every frame. See here. The issue here is that setting the position means extra Update() calls and it lags behind the controller a little. Also, because the model isn't a child of the controller, it doesn't inherit the velocity of the controller, so it needs to be manually applied. Changing the parented GameObject at runtime. Depending on the state of the character, the CC model will be parented to each other if the CC is active, the model is set as its child and vice versa using SetParent. I couldn't get this one working (the local position variable was a little confusing to me, but no configuration I tried worked for me). Conjoined CC and model. I placed the CC on the same object as the model. This isn't really ideal for me because I want greater control over the rotation and presentation of the model. I couldn't get this one working either I don't know how I could set the position of the CC without moving the whole thing. Is there a more effective way of doing this? If so, what? I feel like I am greatly overcomplicating this. Any help would be great. In an ideal situation, I could have the model as a child of the controller (or behave that way) and move the CC when it is inactive without affecting the model position.
0
Problem with Factory Method Pattern when I try to create a Weapon MonoBehaviour I'm learning about Design Patterns using Unity and I'm not sure about how to solve the following problem with the Factory Method Pattern I want to read a XML file and using the Factory Method Pattern to create a Component (a Weapon) to add it to a GameObject which will be cointained on a Pool Manager, but Weapon "Is A" MonoBehaviour and for that reason It can't be instantiated using a "machineGun new MachineGun() " public abstract class WeaponFactoryMethod protected string fileName "weapons.xml" public abstract Weapon CreateWeapon() public class MachineGunFactoryMethod WeaponFactoryMethod public override Weapon CreateWeapon() string filePath Path.Combine(Application.streamingAssetsPath, fileName) Weapon machineGun null XmlReader xmlReader new XmlTextReader(filePath) if (xmlReader.ReadToDescendant("Weapons")) if (xmlReader.ReadToDescendant("Weapon")) do I CAN'T DO THIS machineGun new MachineGun() machineGun.ReadXml(xmlReader) while (xmlReader.ReadToNextSibling("Weapon")) else Debug.LogError("There aren't definition for Weapon") else Debug.LogError("There aren't definition for any Weapon") return machineGun public abstract class Weapon MonoBehaviour, IXmlSerializable public float AttackRange get set Every weapons Shoots in a different way public abstract void Shoot() Serialization public XmlSchema GetSchema() return null public void ReadXml(XmlReader reader) XmlReader childReader reader.ReadSubtree() while (childReader.Read()) switch (childReader.Name) case "AttackRange" childReader.Read() AttackRange childReader.ReadContentAsInt() break public void WriteXml(XmlWriter writer) public class MachineGun Weapon public override void Shot() Raycasting.. At the end I want something like GameObject (player) Component (A Weapon script with the data from the xml) Should I just create a GameObject (player) and do an "AddComponent lt MachineGun " and later copy the info from the xml file instead using the Factory Method Pattern?? Is there a better way?? Any suggestions, corrections or advice will be very grateful. I'm sorry by my English.
0
Unity DirectoryInfo not working in OSX standalone build So I'm building an application in unity which I hope to use at a market day coming up soon at my school (it's not a game, it's basically like a checkout app, kind of...) Anyway, I'd like to be able to import images from the app and to have the option to change them while the app is running. Currently I have the images in a folder and I'm using DirectoryInfo to get the contents of that folder and load the images. Works like a dream inside the editor but as soon as I build the app (on OSX), everything is blank. Other people seem to have similar issues but I'm a little unsure as to how they fixed it. Could someone please help me, this is kind of urgent!
0
Using Unity's transform.translate() to translate relative to an object but only using two axis I'm using transform.translate() to move an object around the world space, relative to the camera that is following it. The camera has an angle of 23 degrees on the X axis. The problem is that when I move forward the object tries to go into the ground and when going backward the object starts jumping because of the angle of the camera. What I want to do is freeze the Y axis of the object However if I did this the object would no longer be able to jump. The other solution to this would be to write a method which rests the object to the ground when not jumping but them if the object was jumping and going backwards it would go flying backwards again. How do I solve this issue?
0
Advantage of Using Addressable Over Asset Bundles in Unity I have a project that already uses asset bundles. I download assets when the game starts and show them to the user when needed. I see that Unity provides addressables as new solution for asset management. As its new (not very new as its accessible from 2018.2, but official docs dont say a lot) there is not so much about it on the web. From what it seems, in addressables you dont need to care about the bundle version, or which asset is in which bundle. In addresables, Unity automatically uploads assets to your host, and Unity automatically correctly manages local caching or downloads from a server, so objects behave like they are in the main game package but you have to check if they are loaded or downloaded. Am I right? Are there any other features that addressables offer?
0
How can I get Unity to tell me the battery status of my OS X laptop? How do I get battery status on an OS X laptop in Unity? This is un Googlable I keep finding either mobile stuff (iOS or Android) or people complaining about laptop battery life.
0
How do I create this windblown snow effect? How do I create this snowy wind kind of effect, where wisps of snow appear to blow through the air close to the ground? I have seen this in several games like Skyrim, the new God of War, but I don't know what name to call it by. I found this God of war gameplay https youtu.be b7u59Iutb0c
0
How to modify the Unity sprite renderer (or create a custom one) that can display the sprites on the X Z plane? Prefix I am NOT trying to rotate a sprite 90 degrees by it's transform, this changes what is up down and forward backwards for the object. I need the sprite displayed on the X Z plane in comparison to the default X Y plane in it's natural state in the game world with rotation transforms of 0. I'm trying to use 2D sprites on the X Z plane, how do I go about either modifying the built in sprite renderer to do this, or creating my own custom sprite renderer component?
0
Unity animator controller animations don't work I'm having problems animating a character pack I purchased from unity asset store. I've placed the character in an environment and created an animator controller. After I drag the animation that to the animator tab, there aren't any motions. Even if I place triggers or booleans in my script as parameters in the animator it doesn't work. It worked with other characters but the animations were somehow embedded in the 3d models. How is this supposed to work?
0
Run a Script at Game Startup in Unity I have a script that is made to run when the game is loading. That script set the resolutions, fullscreen, and loads other screen and important settings and it applies them. I have the script attached to a gameObject in the main screen that have some game and scene scripts. The problem is that everytime that you return to the main scene, that script runs again and cause several bugs. So, there is a way to run a script only at game startup?
0
Microphone channel not detected in Unity This is very specific to Unity. A few testers are reporting that their microphone output isn't being detected. The code below works for the vast majority of users, but certain microphones seem to be outputting on the wrong channel (R maybe)? AudioClip current microphone recording clip Microphone.Start(microphone name, true, 30, 16000) How can I capture and analyze output from several channels? I don't see any channels parameter for Microphone.Start
0
Color bands over tile when scaling texture in shader I want to have tiles with different sprites on the back. Initally I thought I will mix two textures together and then apply mixed texture to game object. I thought that should be easy, but google returned discussion about shaders and their superiority. After reading about shaders I decided to use shaders instead. Also I am using rather big sprites and I am scaling them down in shader. Kind of want to be sure that tiles look good on big screens also. Also to be sure that game works on smaller screens I change camera distance when game does not fit in the screen. Everything is working nice when tile is "near". But when tile is far away it starts to show artifacts over all surface of tile. It appears that scaling is done not pixel by pixel but in some chunks. Modified shader code (I commented out mainTex because it does not change anything from "bug" perspective) Shader "Custom TwoTextureShader3" Properties Color("Color", Color) (1,1,1,1) MainTex("Main Texture Color (RGB)", 2D) "white" MainTex2("Overlay Texture Color (RGB) Alpha (A)", 2D) "white" Glossiness("Smoothness", Range(0,1)) 1 Metallic("Metallic", Range(0,1)) 0.2 OffsX("Offset X", Range( 2, 2)) 0 OffsY("Offset Y", Range( 2, 2)) 0 Scale("Scale", Range(0, 10)) 1 SubShader Tags "RenderType" "Transparent" LOD 200 CGPROGRAM Physically based Standard lighting model, and enable shadows on all light types pragma surface surf Standard alpha fullforwardshadows Use shader model 3.0 target, to get nicer looking lighting pragma target 3.0 sampler2D MainTex sampler2D MainTex2 fixed OffsX fixed OffsY fixed Scale struct Input float2 uv MainTex float2 MainTex2 half Glossiness half Metallic fixed4 Color void surf(Input IN, inout SurfaceOutputStandard o) float4 mainTex tex2D( MainTex, IN.uv MainTex) fixed2 offsetUV fixed2( OffsX, OffsY) float4 overlayTex tex2D( MainTex2, IN.uv MainTex Scale offsetUV) half3 mainTexVisible mainTex.rgb (1 overlayTex.a) half3 overlayTexVisible overlayTex.rgb (overlayTex.a) float3 finalColor (mainTexVisible overlayTexVisible) Color o.Albedo finalColor.rgb o.Albedo overlayTex.rgb o.Metallic Metallic o.Smoothness Glossiness o.Alpha max(mainTex.a,overlayTex.a) o.Alpha 1 ENDCG FallBack "Diffuse" Tiles looks good when they are near Tiles looks awfull when they are far away Currently I am thinking about using two Meshes for single tile, so that game never hints about what is on the back of the tile even when graphics hardware really want to.
0
Does 2D Platformer games still have popularity among gamers? I'm currently working on a 2D platformer game that i wanted to put out as my first game but seeing the popularity of other games made by Voodoo and others are quite distressing and made me ask myself this question and now you guys. will the 2D Platformer games that had the popularity will have any popularity for developers to take interest and make some living out of it in the for future projects or can they work on the more popular games like color bump 3d.
0
Saving a high score and updating it as score increases I'm following Brackeys "Dodge the Blocks" tutorial. In the video, he covered everything accept the score high score system. I have a working score system, which gives you 1 point every time you collect a coin. In the scene where you play the game, I have a text UI that says "Score ", and another one for the score number, another that says "Best ", and one more for the best number. I want to make it so that your high score gets saved, and updates in real time with your score every time you pass the score. Here are some of the scripts UI Manager (Where I want to put the high score code) using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class UIManager MonoBehaviour public Text scoreText int score public static int coinAmount void OnTriggerEnter2D(Collider2D col) CoinTextScript.coinAmount 1 Destroy (gameObject) public void scoreUpdate() score Coin Text Script using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class CoinTextScript MonoBehaviour Text text Text bestScoreText public static int coinAmount public int score void Start() text GetComponent lt Text gt () void Update() text.text coinAmount.ToString()
0
Unity facebook sdk 'Didn't find class "com.facebook.FacebookContentProvider"' any more fixes workarounds for this? How to replicate this error... Create a new Unity project. Import the facebook sdk unitypackage Set your App Id for facebook via Facebook Edit Settings Using Assets External dependency manager Android, press 'Resolve dependencies', then press 'delete resolved libraries' (otherwise the build will fail at the gradle stage) Build and run. When the app tries to run I immediately get the error message on my phone 'app has stopped working' and see this error in the logs ... Caused by java.lang.ClassNotFoundException Didn't find class quot com.facebook.FacebookContentProvider quot on path DexPathList zip file quot data app com.SandwichGeneration.MakeASquare nLEHpzOYlwW6XKmGzPfIw base.apk quot ,nativeLibraryDirectories data app com.SandwichGeneration.MakeASquare nLEHpzOYlwW6XKmGzPfIw lib arm64, data app com.SandwichGeneration.MakeASquare nLEHpzOYlwW6XKmGzPfIw base.apk! lib arm64 v8a, system lib64, system vendor lib64 Suggested fixes I've tried from here I've tried different combinations of old or new facebook sdks and old or new versions of Unity. I've tried building from a few different machines to different Android devices. I've deleted the external dependency manager included with the facebook sdk and used this one instead. In order to get this one to resolve I had to set a 'Custom Gradle Properties Template'in the player setting under publishing settings. I've set a Custom Proguard file'in the player setting under publishing settings, and I added the following two lines to the file.. keep class com.facebook.internal. keep class com.facebook. So I've tried all the suggested fixes and various combinations thereof. I dont know what more I can do. Can anyone suggest anything else to try?
0
Collision Detection Response Issues in Unity Sprite A Box Collider 2D and Rigidbody 2D. Sprite B Box Collider 2D. Both sprites have a Sprites Default material with Pixel Snap enabled. The textures being used are set to Truecolor Format and Point Filter Mode. No Mip Maps and 1 Pixels Per Unit (higher PPU seems to make the issue more obvious, but lower value does nothing but scale the problem down). I put Sprite A above Sprite B, hit play. I see Sprite A fall into Sprite B and hover slightly above it. I think this is horrible, so I look it up. I find I can lower Min Penetration For Penalty to help.. but not fix.. this issue. It's barely noticeable now. After a while, I noticed Sprite A sometimes overlaps Sprite B briefly during collisions. I can't seem to find a clean fix to either of these issues. Is Unity's physics engine just not designed for the level of accuracy I'm wanting? It seems the whole way the physics engine works is by allowing overlap (minPenetrationForPenalty) before pushing objects out of each other. I've been coding for many years as a hobbyist, so no professional experience, but this seems.. wrong. Are there options that don't involve overlapping of objects? Thanks for any and all help.
0
Realistic angular velocity for rolling sphere in Unity 5.1 I'm trying to make a small 2D game with a rolling ball sphere using Unity 5.1, but if find the angular velocity of the ball weird. On this first image (http imgur.com 8wBoGms), you can see the sphere in 2D and in its initial position. On this second image (http imgur.com ArCRSZn), the sphere was moved by rolling until it made a 90 turn. But the distance traveled by the sphere is greater than it should, if you wanted to be to be realistic you can see that the radius of the circle is equal to the size of the squares' sides, so the circle circumference should be equal to 6.28 (in square side size). If the sphere was traveling realistically, it should travel 1.57 (in square side size) to turn 90 . But in the second image, we can see that it take 3 and not 1.57 . The controller of the sphere is simply adding a force when a left or right button is pressed public class PlayerController MonoBehaviour public float speed private Rigidbody2D rg2d void Start() rg2d GetComponent lt Rigidbody2D gt () void FixedUpdate() float moveHorizontal Input.GetAxisRaw("Horizontal") Vector2 movement new Vector2(moveHorizontal, 0.0f) rg2d.AddForce(movement speed Time.deltaTime) So my question is how can I make the angular velocity realistic in this situation? Or am I doing something wrong? Thanks for taking the time, I really appreciate !
0
How do I bring a child object in its original position after it is translated and rotated? This is the original position of the cube and its child object cone. Over here, I have translated the cone for 2 units Now I have rotated the parent cube around 25 degrees wrt to the Y axis If we translate the cone 2 units back again, it's not in the original position What formula do I need to apply to the cone while translating it back to bring it back to it's original position? Code The below code is a coroutine for translating the child object IEnumerator MoveToNewPos() Vector3 newPos Quaternion.Euler(0, 0, 135) Vector3.left distance float t 0 float animTime 30 isMoving true for ( Vector3.Distance(transform.position, newPos) gt 0.001f t Time.deltaTime) float p t animTime transform.position Vector3.Lerp(transform.position, newPos, p) yield return null isMoving false
0
Lightmapping custom model manifold What are the things one should consider before doing light maps? We have custom models in Unity Scene,while doing light mapping it stuck at "Clustering job 5 11". After researching I come to know models should be "Manifold" to be light mapped so we did manifold our custom models and now light maps are occurring properly though at the cost of lot of polys which is causing performance hit on Android device. So my question is has anyone faced similar issue or workaround for same?
0
Get Closest point between a Box 3D and a Point I have a point A (x, y, z), and a Box Center (x, y, z), Size (Width, Height) How to get the closest point in the box from the point A ? In Unity I can create a bound, and I can find the non rotated position like that Bounds bounds mesh.bounds Vector3 closestPoint bounds.ClosestPoint(pointA) But then If the bound is rotated, the result is not correct. So I have 2 options Find the way to rotate my closestPoint from the pivot. Find the math formula myleft. If someone can help ! thanks. EDIT here a video the red point is the one find with bound.ClosestPoint the yellow point is the one find with Vector3 closestPointInverse currentTarget.InverseTransformPoint(closestPoint) https youtu.be RMRRtSaJv8w I have also tryed to do my own rotateFromPivot function public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) return Quaternion.Euler(angles) (point pivot) pivot When I use it, I get the same result with the InverseTransformPoint method.
0
Unity Handling external data files I'm moving from an old game dev tool to Unity, and wondering how to go about handling external data files. In my previous program I'd set up external (txt ini) files like this Group1 Count 1 1 Hello Group2 Count 2 1 lol 2 end Then I would simply reference which group name and line I wanted to pull. What's the equivalent to this in unity? I see I can import TextAssets but I can't find functions to pull select data from it. Do these exist? Do I have to split by lines, loop through them all and convert it into groups (lists) manually? What is the standard method for doing this? Is it moving to xml files?
0
How can I make 2D fog like in Graveyard Keeper? I really like Graveyard Keeper's fog effect but I can't work out how to make it. It's 2D, and made in Unity. The characters all seem to be 'under' the fog, but the tops of tall trees and buildings poke out. It looks like this The developer has given a bit of information about how it's made on Gamasutra http www.gamasutra.com blogs SvyatoslavCherkasov 20181023 329151 Graveyard Keeper How the graphics effects are made.php "As you see, the tops of houses and trees are seen from the fog. In fact, this effect is really easy to make. The fog consists of a great deal of horizontal clouds spread across all the picture. As a result the upper part of all the sprites is covered with a fewer amount of fog sprites " I used the information from this article, and one of the developer's tweets that included this picture I attempted to recreate it this fog effect. When the character moves up or down the screen, it flickers as it crosses each fog sprite What have I missed? All of the sprites are on the default sorting layer and have sorting order 0. The project, in Graphics Settings Camera Settings has the custom axis and sort axis (0,1,0). The tree and character are on the same z position, and the fog is spread out over several z positions
0
How to prevent OnCollisionEnter2D calling a function again and again? My current code makes a ball keep jumping whenever it hits the ground. But when it hits a vertical ground it keeps calling the jump function again and again. That is because OnCollisionEnter2D makes the isGrounded bool true as long as it is in touch with a vertical collider. I tried several ways for example this didn't work for me void FixedUpdate() if(isGrounded true) Verticaljump() isGrounded false void OnCollisionEnter2D(Collision2D collision) if(collision.gameObject.CompareTag("H Ground")) isGrounded true As shown in the picture the OncollisionEnter2D starts and keep adding force on y axis.Is there any way I can call a function only once even if the gameObject keeps colliding with a surface. OnCollisionExit2D also does not work. So how can I call a function only once as it collides with ground and even if it keeps colliding with the ground?
0
How to prevent collisions between instantiated prefabs I'm creating a virtual creature evolution system like here. This type of project requires to define creatures, which are made of some 3d boxes and simulate them over and over again, making little changes along the way, until the point where they are good enough at a certain task. Basically, I'm using Genetic algorithms. I'm going to be doing a lot of simulation (a few hundred creatures each generation, times X generations, where X could be in the thousands). In order to save time, I want to simulate multiple creatures at once, so I must run collision checks efficiently. Each creature exists on its own and therefore should not be bothered by other colliders except himself and the ground. I have a prefab of a creature. Each creature is made of multiple 3d boxes with colliders. The nodes in the same creature should collide with themselves but should not collide with nodes that are in other creatures (because it should learn to perform based on the environment as it is). What is the most efficient way I could do this? I thought about checking the root of the collision object but that just prevents the collision and doesn't eliminate the useless checks that are being made. I've also looked at solutions involving the "Layer Collision Matrix" but still could not find a way to make it work. Thanks in advance.
0
How do I use Unity's OnPlayerConnected method? https docs.unity3d.com ScriptReference MonoBehaviour.OnPlayerConnected.html using System.Collections using System.Collections.Generic using UnityEngine.Networking using UnityEngine public class SendData MonoBehaviour void OnPlayerConnected (NetworkPlayer player) Debug.Log ("A player connected!") This code, surprisingly, doesn't work! Expected The server prints "A player connected!" in the Unity editor debug console. What happens Nothing is printed. It doesn't matter if I use print() or Debug.Log(). This script is applied to a standard object in the scene. It has a NetworkIdentity. I really don't know what else to try. The Unity documentation is very short and gives an example very similar to this. My code should be even simpler than Unity's example but it doesn't work.
0
How do I implement corner correction in a platformer? I'm writing a platformer in Unity and I'm trying to make it so that when the player jumps up to a ledge but barely misses (imagine they hit their toe on the ledge, or maybe even their foot, I'll play with the values) they are nudged up onto the ledge instead of not making the jump (as it is now in my game). There's a thread showing that Celeste does this in a few ways here. My player character uses a dynamic Rigidbody2D and I move the character by setting the velocity directly.
0
Replicating Flight Mechanics of Star Wars Battlefront (2015) I'm trying to replicate the flight mechanics from Star Wars Battlefront (2015) in Unity and I can't get my head around what exactly is going on. Specifically, how do I get the camera to behave like this using Unity and C https youtu.be gxZdOUiEiyY?t 1m1s I don't mind if you don't give code, I'm just struggling to understand what happens and when in terms of camera movements and rotation.
0
Using shared memory instead of marshalling for C native plugins in Unity? So I'm a C developer who has been playing with C for a week or two in order to get acquainted with Unity, and I'm curious about the marshalling process used to transfer data for use in C native plugins. From what I can tell, the general consensus is that while using effective C plugins can be a performance increase for computation heavy tasks, the marshalling process of transferring data can be significantly slower than the potential gains provided by the C flexibility. I'm familiar with how shared memory works in C and it appears C has the functionality required to use the buffers as well. From what I understand, the process of marshalling is slow due to copying, creating buffers and transferring chunks from one memory segment into another. Even though there's the problem of cache coherency when operating in shared memory, it may be less than the cost incurred by marshalling. I'm sure I'll have to do some experimenting. Does anyone have thoughts or experience with using shared memory or marshalling in Unity who could weigh in on the question?
0
How can I rearrange layers in Unity 2D? I'm new to using Unity (2019.30a2) and am currently learning by watching Brackey's (youtube) "How to make a 2D Game in Unity" At 6 58 he is able to rearrange his layers easily. On my hand, I can create but am unable to change the order of the layers. Looking at other questions on similar subjects hasn't provided me with a solution yet. I'm currently working around it but feel this will hinder me in the future. The screenshot of the unmovable layers is included below
0
Unity Material Override Video is too dark I have made a TV in Blender, UV Wrapped a material and applied a video on it in Unity. But the picture is too dark, and I would like to make it brighter. How could I solve this problem? The left one
0
Where and how should I check for collision in multiplayer game? I'm making a multiplayer game. For now, I added a script to towers and I have booleans to change using OnTriggerEnter. When triggered, client sends a message to server and towers health starts to get lower. So it works. But I don't know if it's safe to use OnTriggerEnter because it calculates on the client side. Should I calculate on the server side ? And how I do it ? (Using Physics.ComputePenetration is a little bit slow.)
0
Room generation with external walls and doors I am looking to implement a means to generate rooms with outer walls with windows and doors from prefab game objects in Unity. The idea is that a group of tiles is defined as a room which I then iterate through to find the outer tiles and then use their external edges to generate the walls of the entire room. Gathering the outer tiles is easy enough and working out the external edges is already implemented. What I need to understand is the best approach for using prefab game objects as the set pieces for walls and floors. Currently for a single wall piece, I have created a quad and made that into a prefab which I then clone, position and rotate into place along the outer edges. The below screenshot shows a room with walls made using the prefab wall GameObject. In this screenshot, the room consists of 12 wall GameObjects. I want to avoid having lots of GameObjects for single wall segments and instead perhaps merge them all into a single mesh on a single GameObject. What I would like to achieve is to be able to create a consistent set of pieces for each outer wall, with windows and doors (most likely cloned from other prefabs) to build a realistic looking room. For example, any single length of a wall would be made up from Wall gt Wall gt Window gt Wall gt Wall Perhaps there is a much easier way to achieve this that I have overlooked but searching for room generation always leads back to examples for dungeon crawlers and roguelikes. I am not creating a dungeon crawler, nor am I generating the environment proceedurally, instead the player will be able to create rooms in a similar fashion to Evil Genius and The Sims. In the current approach, creating a room which is 5x5 would mean that there are a total of 20 wall GameObjects and 25 floor GameObjects. I am not keen on having this many objects in the scene for a single room. I would prefer to be able to create a mesh for the entire room, adding in the vertices and triangles from the prefab mesh to cut down on the number of GameObjects in the scene. Does anyone have any experience with building rooms in this fashion, or are there any clear examples of how to achieve this? I am not sure how to translate and rotate a prefab and then merge the translated meshes into a single mesh. Perhaps I am barking up the wrong tree and there is a better approach but for now, this is the only way I can see which is possible to achieve what I want.
0
Inaccurate UI button unity As you see in this screenshot I must hover the mouse on that that spot to click on button in overall you must hover the mouse upper than button to click on it, tried to change the Sprite but even with default Sprite I have this problem so I don't think there is problem with Sprites. Let me explain more about this panel In this scene I have two canvas's one for Pause button only and another one for this panel that is disabled. When you click on Pause this panel will appear ( second canvas will be activated. Why is that? I tried to change some things in the canvas like change UI scale mode to scale with screen size but no luck. I will be grateful for help I don't really know where problem is. Update I just now found very odd behavior when hit play if mouse be in game view that problem wont occur, after mouse leave the button issue will appear again.
0
How to blur entire scene but a specific spot in Unity? What I want is basically A way to blur every object sprite on the scene, but have a "blur free" circular zone, that can move. And everything that's behind that circular zone won't have the blur effect applied to it. In a 2D mobile game, how would I do that, especially in a way that's not too heavy, performance wise(if possible). And if it's not possible to do that in a way that won't completely destroy my performance, I also have those sprites already "pre blurred" so maybe there's a way to have both blurred and "unblurred" objects at the same position, and only draw the right parts of them as they go through the scene and reach the blur free zone. If there's a way to do that, that'd also help immensely. Thanks for your time.
0
Problems with Unity3D Animator controller states I have an object (a simple card) equipped with the Rigidbody, Collider and Animator components. In particular, Animator performs two simple clips Cover and Uncover that rotates the card 180 degrees. The first starting from 0 degrees to 180, the second from 180 to 0. So the clips should cover or uncover the card. The problem is that the card returns to its original state. For example, the original state of the card is the "uncovered state" so when I click on it to cover it covers as expected. The I register the state "covered" programmatically. However, immediately after the animation ends, it returns to its original state (uncovered). The card now has an internal (C variable) state as "covered", but I see it to still be uncovered. When I click it again, will be fired the correct animation clip "uncover". What should I do to leave it covered at the first click? I have uploaded here a short clip that shows the behavior of the card, also below find some screenshots that refer to the various views of the IDE that may have useful information. The video clip is uploaded to Dropbox for the while. The video of the behavior Dropbox link The code of the Flip script using System.Collections using System.Collections.Generic using UnityEngine public class Flip MonoBehaviour private Animator anim private enum cs e covered, uncovered private cs e coveringState Use this for initialization void Start () anim this.GetComponent lt Animator gt () coveringState cs e.uncovered Update is called once per frame void Update () private void OnMouseUp() Debug.Log("Mouse up") if (coveringState cs e.uncovered) anim.Play("Cover") coveringState cs e.covered else anim.Play("Uncover") coveringState cs e.uncovered private void OnMouseDown() Debug.Log("Mouse down") private void MouseDrag() Debug.Log("Mouse drag") Some screenshots
0
Unity 5.x Network Synchronization Concepts Bear with me, It will be long read I am working on the new Unity Networking system. I was using Photon and old (legacy) unity network API's before. But as it seems there are some good benefits of the new system than the previous ones, so I want to stick with it. (Despite of it being uncompleted) But there are some points that doesn't make sense to me with the API. Data Sync for example. So, in the old systems (both in Photon and legacy unet) we had functions called OnPhotonSerializeView or OnSerializeNetworkView depending on which API we use. Both API's are very similar as you may know. So in these functions we could send and recieve data between clients and server. Which makes sense, and was really usefull. But aperantly they changed this concept, (or it still exists, and i couldn't find it) There is a new thing called SyncVar , which syncs the data "ONLY" from server to client automatically. (Which really, literally doesn't make sense, I mean why not sync both server to client AND client to server? That would make everything much easier) According to the documents, you can ONLY send data from client to server by using Command 's. Which is basically (as far as I understand), "one way" version of old good RPC calls. Instead of calling function in all other clients, it calls it in the server. So, you can send data to server with function parameters like the way we did it with the old RPC 's before. Which is usefull on point but If this is the only way to send data to server, then it doesn't make any sense to me.. I mean there are variables that needs to be kept synced all the time, back and forth, like position or rotation vectors. And sending them with Command calls, contradicts with the concept of network framework in my mind. We used to avoid this kind of situation before, right? Why make it the obligation now? Or are there simply any other ways to send data from client to server that I couldn't find yet? There is a custom serialization with the SyncVar , with OnSerialization and OnDeserializaton functions. Which really looks like the good old OnSerialize functions but apperantly it's diffrent as it does what the SyncVar does. OnSerialization is only called on server, and Deserialization is only called on client. So we can only send from server to client even with it. If Command is the only way to send data to server, please say so. And clarification about why this concept is reasonable would be really nice. Please enlighten me more with the new concepts of the new UNET framework. Thanks in advance for any help.
0
How does Vector3.MoveTowards work in Unity? What I mean is that I don't understand what each part does, like in the example in the API, it didn't give much on what did what! I kinda need this for an aim script in a shooter game I'm working on. Any help will be good, but a direct answer would be great!
0
Why is this MeshRenderer null? The following line fails in my class MeshRenderer nRenderer Sphere.AddComponent lt MeshRenderer gt () This is the entire class. All works except the mentioned line. using System.Collections using System.Collections.Generic using UnityEngine public class SphereMaker MonoBehaviour private GameObject Sphere void Start() Sphere GameObject.CreatePrimitive(PrimitiveType.Sphere) Sphere.AddComponent lt MeshFilter gt () MeshRenderer nRenderer Sphere.AddComponent lt MeshRenderer gt () Material nMat new Material(Shader.Find("Universal Render Pipeline Lit")) I'm using the URP if (nMat null) Debug.LogError("no mat!! n") nMat.color Color.red nRenderer.material nMat float fSize 0.4f Sphere.transform.localScale new Vector3(fSize, fSize, fSize) Sphere.transform.position new Vector3(0, 0, 0) Does anybody see what I'm doing wrong? Thank you!
0
Sprite changing position on its own? I have a simple 2d scene, where I'm trying to have a sprite at x 8 which I can move up and down. The problem is, when playing the scene, the sprite "jumps" by itself to the middle, x 0, for no apparent reason. It then only goes back to x 8 when there is input to move it. How do I get it to stop "jumping" to the middle at the start of every play? using UnityEngine public class player1 MonoBehaviour Vector2 targetPos public float speed public float step void Start() transform.position new Vector2( 8,0) void Update() if (Input.GetKey("w") amp amp transform.position.y lt 3.8) targetPos new Vector2( 8, transform.position.y step) if (Input.GetKey("s") amp amp transform.position.y gt 3.8) targetPos new Vector2( 8, transform.position.y step) transform.position Vector2.MoveTowards(transform.position, targetPos, speed)
0
Game not accepted in Google Play even though it's built in 64 bit (Unity) I tried building my game according to the google play rules, but I get the following error message "This release is not compliant with the Google Play 64 bit requirement The following APKs or App Bundles are available to 64 bit devices, but they only have 32 bit native code 1. Include 64 bit and 32 bit native code in your app. Use the Android App Bundle publishing format to automatically ensure that each device architecture receives only the native code that it needs. This avoids increasing the overall size of your app." According to the documentation (https developer.android.com distribute best practices develop 64 bit) for Unity I should get a working version when I do Set Scripting Backend to IL2CPP Select the Target Architecture ARM64 checkbox Build as normal I've built the game both as APK and as AAB, but neither are accepted. I am using Unity 2018.3.14f1. I have downloaded this NDK https dl.google.com android repository android ndk r16b windows x86 64.zip and put the content to C Users MyName AppData Local Android
0
Why the state of the duration is all the time 7 even if updating the state inside the while in the ienumerator? I want to get the current coroutine state. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.PostProcessing public class DepthOfField MonoBehaviour public UnityEngine.GameObject player public PostProcessingProfile postProcessingProfile public bool dephOfFieldFinished false public LockSystem playerLockMode private Animator playerAnimator private float clipLength private Coroutine depthOfFieldRoutineRef private DepthOfFieldModel.Settings depthOfField private DepthField state void Start() if (depthOfFieldRoutineRef ! null) StopCoroutine(depthOfFieldRoutineRef) playerAnimator player.GetComponent lt Animator gt () AnimationClip clips playerAnimator.runtimeAnimatorController.animationClips foreach (AnimationClip clip in clips) clipLength clip.length DepthOfFieldInit(clipLength) state new DepthField() public void DepthOfFieldInit(float duration) depthOfField postProcessingProfile.depthOfField.settings depthOfField.focalLength 300 StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, duration)) postProcessingProfile.depthOfField.settings depthOfField public IEnumerator changeValueOverTime(float fromVal, float toVal, float duration) playerLockMode.PlayerLockState(true, true) float counter 0f while (counter lt duration) var dof postProcessingProfile.depthOfField.settings counter Time.deltaTime float val Mathf.Lerp(fromVal, toVal, counter duration) dof.focalLength val postProcessingProfile.depthOfField.settings dof state.duration duration state.focalLength val yield return null playerAnimator.enabled false dephOfFieldFinished true depthOfFieldRoutineRef null public struct DepthField public float focalLength public float duration public void Save() SaveGame.Save("depthoffieldstate", state) public void Load() Time.timeScale 1f depthOfField postProcessingProfile.depthOfField.settings DepthField state SaveGame.Load lt DepthField gt ("depthoffieldstate") depthOfField.focalLength state.focalLength StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, state.duration)) postProcessingProfile.depthOfField.settings depthOfField Inside the while loop I'm doing state.duration duration state.focalLength val The focalLength value does change if for example I save onethe game start the focalLength value will be 299 and if I will save after the coroutine has finished the focalLength value is 1. But the coroutine duration value is not changing it keep staying on 7 when saving even if the coroutine has finished and should be 0 it still 7. The value 7 of the duration is coming from the clipLength. I can't get the current duration time of the coroutine. In the Load function I'm starting the coroutine over again but since I'm using the loaded focalLength value and duration value it should look like the coroutine is continue from the last saved point. But I can't get the correct duration value when saving.
0
What's the best way to index my object? Obviously, lists automatically create their own index. So basically I wouldn't need this function at all. But I figured it was safer in case my list index ever changed (e.g. adding a new item at the beginning of the list, would shift the index numbers for all the other list items). public EmpireAgentView ShowEmpireView(int eIndex) foreach (EmpireAgentView e in EmpireViews) if (e.EmpireIndex eIndex) Debug.Log("Showing Empire for Agent " e.AgentName) return e Debug.LogError("No EmpireAgentView Found for that empire " eIndex) return new EmpireAgentView(9999) So in this case, I added the property "EmpireIndex" to the EmpireAgentView object. So now, whenever I need to access a specific EmpireAgentView from the EmpireViews list, I would use ShowEmpireView(1) instead of EmpireViews 1 . Each EmpireAgentView object has unique information about the same Agent object. For example, where the Agent is currently located. If we have 4 empires, than there will be 4 EmpireAgentView objects in the Agent class. Each empire has their own idea of where the Agent is currently located, so I need to be able to access the specific empires data on this agent. Right now, I assign a simple int called EmpireIndex to each EmpireAgentView, so that I can make sure I got the right view for the right empire. If i simply used EmpireViews 3 , and that list rearranged itself somehow, (like adding an EmpireAgentView object to the beginning of the list, presumably) than all that information would be mixed up for the empires. Is that the best way of doing that? is there a better way of finding it? Or am I being TOO careful, and just need to not add new EmpireView's to the beginning of the list? (I'm new to C , is there anything else that would change the index of a list item?)
0
How to blur entire scene but a specific spot in Unity? What I want is basically A way to blur every object sprite on the scene, but have a "blur free" circular zone, that can move. And everything that's behind that circular zone won't have the blur effect applied to it. In a 2D mobile game, how would I do that, especially in a way that's not too heavy, performance wise(if possible). And if it's not possible to do that in a way that won't completely destroy my performance, I also have those sprites already "pre blurred" so maybe there's a way to have both blurred and "unblurred" objects at the same position, and only draw the right parts of them as they go through the scene and reach the blur free zone. If there's a way to do that, that'd also help immensely. Thanks for your time.
0
Can I test collision inside an edge collider area in Unity? I have a triangle with its perimeter represented by an EdgeCollider2D, and I want to trigger an event when the player reaches this area. So I set the collider as a trigger and, I used the OnTriggerStay2D function in my code. But the event works only when the player is intersecting the line of the collider, not when the player is inside the triangle but not touching the edge. How can I continue to get OnTriggerStay messages when I'm inside the triangle, not touching the edges?
0
Why won't Unity drop objects to the origin position? It seems that my objects drop to the middle of the scene, not a global position of (0, 0, 0). Why is Unity behaving like this?
0
How to stretch screen image to fit higher res monitors set to lower resolutions with Unity? Using Screen.SetResolution(width, height, windowMode) , how might I stretch the image to match the monitor size? I've noticed this problem occurs both with this line of code and also the default unity configuration launcher. No body seems to discuss this issue which is odd to me.
0
Generating objects in Open Worlds using Unity I have an open world (infinite) which is proceduraly generated in chunks. In this world I want to proceduraly load objects trees grass by raycasting them around the player position and unload them when the player is far. My questions are What is the most optimized way of loading unloading large quantities of objects around a player ? Since I'd like players to be able to interact come back to objects, I'm thinking of using a blue noise seed to load objects, and unloading them by replacing them with an empty. Is that common practice ? I've looked in a lot of places for ressources but couldn't find much, I'd really appreciate any kind of link to tutorials, videos, pseudo code ideas and common practices for open worlds as I am not very experienced in video game design, but mildly familiar with code. Thanks !
0
How to get multiple string values from override ToString()? I want to get multiple string values(selectedNameand selectedCurrency) individually from public override string ToString()below. How do I go on about it? using System.Collections using System.Collections.Generic using UnityEngine CreateAssetMenu(fileName "Country", menuName "Country Country", order 0) public class country ScriptableObject System.Serializable public class Item public string Name public string Currency public string Capital public string City public override string ToString() string selectedName this.name string selectedCurrency this.currency return selectedName selectedCurrency public Item m Items public Item PickRandomly() int index Random.Range(0, m Items.Length) return m Items index I need to use the selected string values in the script below. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class GameController MonoBehaviour public country country This is the scriptable object country public Text countryText public Text currencyText void Start() countryText.text country.PickRandomly().ToString() This is where I need the country name string to show up. currencyText.text country.PickRandomly().ToString() This is where I need the currency string to show up. Right now it just displays a random country name and currency for example USA USD in both the fields.
0
Why do I get a jitter stutter when moving and following a target? I am using the script below to move a transform to quickly follow a target (the player), and come to a stop close to the player. When I move the player around, the transform is following the player, keeping the 1.5 distance. To ensure the transform can keep up with the player, I set the moveSpeed to 5, But when I do that, the transform jitters stutters when moving. If I set the moveSpeed to 1 for example, the transform will move smoothly but will not keep up with the player the player has to stop moving and wait for it to catch up. But increasing the speed makes the stutter return. Why is this stutter happening, and how can I make the movement smooth? using System using System.Collections using System.Collections.Generic using System.Linq using UnityEngine using UnityEngine.UI public class Follow MonoBehaviour public Transform targetToFollow public Text text public Text text1 public float lookAtRotationSpeed public float moveSpeed private float minMoveSpeed 0f private Vector3 originPos Start is called before the first frame update void Start() originPos targetToFollow.position Update is called once per frame void Update() Vector3 lTargetDir targetToFollow.position transform.position lTargetDir.y 0.0f transform.rotation Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(lTargetDir), Time.time lookAtRotationSpeed) var distance Vector3.Distance(transform.position, targetToFollow.position) text.text quot Transform Distance From Target quot distance.ToString() float ms moveSpeed if (distance gt 5f) ms moveSpeed 0.5f else if (distance lt 1.5f) ms Mathf.Max(minMoveSpeed, ms 0.3f) else transform.position Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime ms) if (distance lt 0.5f amp amp originPos targetToFollow.position) ms 0f if (distance gt 1.5f) transform.position Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime ms) originPos targetToFollow.position
0
How to render text on an 3d Object? I want to render text on an 3d object. I'm trying to simulate a digital signage LED panel. My lcd Panel has a material and a texture. How can I do ? Using 3d Text ? Thanks
0
Unity I can't change the "colorOverLifetime" property of the "Particle System" via script The goal is to remove the particles via script with fade effect. But I'm not just interested in an alternative, I want to understand why my code doesn't work. The code below is modified to show only the important parts. I can't know before what time the particles will be dissolved, so I can't set the parameter from the editor. StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys This is the important point (see the log image). The gradient does not take my new values but alphaKey is correct. Why ? Thanks private bool FadeStarts false void Update() if (FadeStarts) return StartCoroutine(fadeStars(false)) private IEnumerator fadeStars(bool show) FadeStarts true ParticleSystem.ColorOverLifetimeModule c new ParticleSystem.ColorOverLifetimeModule() c StarsConfig.Stars.colorOverLifetime Gradient g c.color.gradient Debug.Log("OFF " c.color.gradient.alphaKeys 0 .alpha " gt " g.alphaKeys 0 .alpha) GradientAlphaKey alphaKey new GradientAlphaKey 2 alphaKey 0 c.color.gradient.alphaKeys 0 alphaKey 1 c.color.gradient.alphaKeys 1 while (c.color.gradient.alphaKeys 0 .alpha gt 0f) alphaKey 0 .alpha StarsConfig.VelocityAlpha Time.deltaTime alphaKey 1 .alpha StarsConfig.VelocityAlpha Time.deltaTime StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys(c.color.gradient.colorKeys, alphaKey) Debug.Log("g " alphaKey 0 .alpha " gt " StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 0 .alpha) StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys( new GradientColorKey new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1.0f) , new GradientAlphaKey new GradientAlphaKey(StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 0 .alpha (StarsConfig.VelocityAlpha Time.deltaTime), 0f), new GradientAlphaKey(StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 1 .alpha (StarsConfig.VelocityAlpha Time.deltaTime), 1f) ) yield return 0 StarsConfig.Stars.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear) FadeStarts false UPDATE Ed Marty's suggestion is correct, and the solution is there (thanks!). But I would like to understand what is the difference between these two codes. This code works var col StarsConfig.Stars.colorOverLifetime while (col.color.gradient.alphaKeys 0 .alpha gt 0f) float alpha StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 0 .alpha (StarsConfig.VelocityAlpha Time.deltaTime) Gradient grad new Gradient() grad.SetKeys( new GradientColorKey new GradientColorKey(Color.white, 0.0f), new GradientColorKey(Color.white, 1.0f) , new GradientAlphaKey new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) ) col.color grad yield return 0 And this doesn't work while (StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 0 .alpha gt 0f) float alpha StarsConfig.Stars.colorOverLifetime.color.gradient.alphaKeys 0 .alpha (StarsConfig.VelocityAlpha Time.deltaTime) StarsConfig.Stars.colorOverLifetime.color.gradient.SetKeys( new GradientColorKey new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1.0f) , new GradientAlphaKey new GradientAlphaKey(alpha, 0f), new GradientAlphaKey(alpha, 1f) ) yield return 0
0
How to Trigger OnSelect on a Button? I'm new to Unity and C and have been struggling to figure out how to solve this. What I'm looking for is a way to make text display whenever a button is selected. (ex. Player selects a difficulty option, and text pops up describing what mechanics the difficulty will affect) I can get this to work with mouse input with no issue, with the following code attached to the button. void Update() if (this.IsHighlighted() true) gameObject.transform.GetChild(1).gameObject.SetActive(true) else gameObject.transform.GetChild(1).gameObject.SetActive(false) The aforementioned description text is set up as a child to the button, and will appear disappear depending on whether it's highlighted or not. The problem is that isHighlighted only occurs when the mouse is hovered over the button, and does not take effect when selected via directional inputs from a keyboard controller, which is what I'm looking for. I've done some research and noticed there is an OnSelect method, but I can't figure out how to implement it. Any advice would be greatly appreciated.
0
UV mapping. Texture blurry and overlapping. Unity3d In my voxel game, this is how I'm calculating UV coordinates for my cubes' faces public static Vector2 faceUVs(Direction dir) Vector2 sideUV new Vector2 4 new Vector2(0, 1), new Vector2(1f 3, 1), new Vector2(1f 3, 0), new Vector2(0, 0) Vector2 topUV new Vector2 4 new Vector2(1f 3, 0), new Vector2(1f 3, 1), new Vector2(2f 3, 1), new Vector2(2f 3, 0) Vector2 bottomUV new Vector2 4 new Vector2(2f 3, 0), new Vector2(2f 3, 1), new Vector2(1, 1), new Vector2(1, 0) if ((int)dir 4) return topUV if ((int)dir 5) return bottomUV return sideUV Then depending on which face is being generated, I return appropriate UV coordinates for it. This is the texture itself(pretty clean, each block is exactly 16 pixels wide and 16 pixels tall. Total length of picture is 48 pixels) But the result is terrible(Faces are almost correctly aligned with appropriate texture part, but the annoying keyword here is "almost") As you can see, edges of side faces contain few pixels of what should have been the texture of top face. I've set filter mode to point too. If I instead use 16x16 pixel texture, for example only side, then I get good result I suspect the problem here could be floating point precision. In that case, how do i resolve this error?
0
Lightmapper artifacts I really don't understand why this is creating these kinds of artifacts. I'm starting to think something is wrong with Unity. There are clearly no overlapping faces on the Model. There is enough of a margin to remove all chances of bleed. Yes the lid is a seperate object but any UV's of the lid and it's box are not overlapping. Thix odd pixelation occurs no matter the quality. It happened all the time sofar here and there and it forced me to replace a few objects in older projects. No idea what causes it. Really sick and tired of this. Edit when I rotate the crate by 90 degrees the artifacts appear on the adjacent side of the cube. From the perspective of the camera it would be the same side. So clearly it's not the UV's or anything. Lightmap settings Object Import settings
0
How to align a hint arrow to point along a path? I am using CalculatePath and trying to use path.corners in order to give user a hint for path, that where should he lead next. I am using first two instances of Vector3 of path.corners. Lets call those vectors A and B. Let me illustrate this using figure. Now I want to position my arrow above the midpoint of the line from B to A, and orient it so it's pointing along the direction from B to A. When I orient the arrow with LookAt(), it doesn't point in the same direction as the path. Here is an image of my arrow prefab, showing how it's oriented
0
How can I reduce the draw calls in a split screen game? I am working on a split screen game with one camera per player. It appears that the number of draw calls is multiplied by the number of cameras I have, which makes perfect sense. More cameras means more drawing means more draw calls. So for every player, there is effectively a new instance of the game that must be rendered. What do developers do when presented this problem? Do they scale down their game? Or are there practices I am unaware of to where this should not be an issue? (I am using Unity, if it is relevant.) How can I improve rendering performance in a split screen game? Example
0
Unity3d iOS build where are the textures? First time building and running my Unity3D app on my iPhone and it appears that all the textures are missing. Everything is just a solid block of whatever color I made it. When running in Unity I see everything correctly. See images below. To complicate things I'm using custom shaders, and all the objects are custom procedural meshes. Quads that I build in script. If I switch the paper backplate shader to a built in shader I still only see white on the iPhone. So I suspect that somehow the textures just aren't making it to the iOS project. When I look in the iOS project I can't find any textures. Where would they be in the iOS project? For example in Xcode under Build Phases Copy Bundle Resources the only thing there is the Images.xcassets, which only contains the splash screens and icons. Surely I'm missing something simple. I tried renaming the folder where I keep my textures to "Textures". Also my textures are not built in to the shader but added programmatically like this void Awake () meshFilterComponent GetComponent lt MeshFilter gt () Material material GetComponent lt MeshRenderer gt ().material material.SetTexture(0, paperTexture) material.color new Vector4(1f, 1f, 1f, 1f) Where paperTexture is set up in the GameObject to point to the correct texture. Is there any way to force a texture to be part of a build? Let's say that you swap out textures in code, like swapping themes, how would you make sure they're all there to be loaded as needed? Running On iPhone Running In Unity3D
0
unity3d Object keeps falling down I have an object that moves towards another object using this line transform.position Vector3.MoveTowards(transform.position, target.transform.position, speed Time.deltaTime) this is it's attributes It doesn't use gravity, kinematic and it's Y position is frozen, but it keeps falling to the floor and colliding with it. How do prevent that and keep it floating ?
0
How to use Input.GetAxis("Mouse X Y") to rotate the camera? I want to make a first person camera that rotates with the mouse. I looked at the Input.GetAxis Scripting API page and found a sample code, which I have included at the bottom of my post. Upon trying it out, I realized that although it has the same basic functionality I hoped it would have, it does not keep the camera parallel to the xz plane, particularly when moving the mouse in circles. After a while the camera would be at an odd angle, and the player would be completely discombobulated! Is there a quick fix to this code that would restrict the camera movement somehow, or is there a better way to rotate the camera? using UnityEngine using System.Collections public class ExampleClass MonoBehaviour public float horizontalSpeed 2.0F public float verticalSpeed 2.0F void Update() float h horizontalSpeed Input.GetAxis("Mouse X") float v verticalSpeed Input.GetAxis("Mouse Y") transform.Rotate(v, h, 0)
0
Client side prediction buffer size considerations for jitter I am currently having a FPS game with client side prediction. Every 20ms, the client sends it's input to the server. The server buffers 5 ticks worth of input (100ms) and starts consuming the inputs each tick and sends a world snapshot to the client. The client then validates the predictions and corrects the simulations if there is a misprediction. The setup works fine under ideal network conditions. However when the latency suddenly spikes from say 50ms to 400ms, the client's tick packet is delayed which causes the server to eat through all of the available inputs in the buffer and resort to using the previous tick values to perform server simulation. When the client input finally arrives at the server late, the server discards the input because it has already processed the input for that particular tick (using old input values). How do I handle this edge case of latency increasing and decreasing? Sure I could use a larger buffer size for the inputs, but that will cause delays between client state and server state. Using a smaller buffer will cause the server to stall from inputs if there is a jitter that is more than the duration required by the server to process the inputs. I was under an impression that I would need some kind of dynamic buffer size that expands and contracts. However, I am out of ideas to implement something like this. Does anyone have a solution?
0
Unity 2d overlapCircle melee combat issue I have an issue with my overlapCircle melee combat in the game. I'm not good at such things, so I just copied that code from some YouTube tutorial. But the thing is that if the enemy is behind the collider, I can still damage and kill him. And I don't want this. Is there a solution to this problem except recreating the melee combat system from the ground up? Maybe changing circle radius when close to collider?... Here's a video clip that may help show the situation. void Attack() Collider2D hitEnemies Physics2D.OverlapCircleAll(attackPoint.position, attackRange, whatIsEnemy) foreach (Collider2D enemy in hitEnemies) Debug.Log( quot Melee hit quot enemy.name) if (enemy is BoxCollider2D) CinemachineShake.Instance.ShakeCamera(3f, 0.2f) SoundManager.PlaySound( quot Knife kill quot ) if (enemy.tag quot Melee enemy quot ) enemy.GetComponent lt enemy melee gt ().TakeDamage(attackDamage) else if (enemy.tag quot Gun enemy quot ) enemy.GetComponent lt enemy gun gt ().TakeDamage(attackDamage) animator.SetTrigger( quot Melee attack quot ) animator.SetBool( quot IsCrouching quot , false) animator.SetBool( quot IsJumping quot , false)
0
How do I get the Oculus Rift's position and rotation? I'm looking for the functions to get the position and rotation data of the rift headset itself in Unity. I have the Oculus integration SDK installed and want to avoid using any pre fabs.
0
How do C and UnityScript differ in Unity development? Other than the obvious language differences, how do UnityScript and C differ when developing games in Unity3D? Is there a noticable performance difference? Is the UnityScript code packaged as is? If yes, does this help the game's moddability? Is it possible to use libraries developed for one language while developing in the other one? Can the two languages be mixed in the same Unity project coding some parts in C and others in UnityScript?
0
Will I lose the mesh if I delete the original prefab? I'm working in Unity 5, and I currently have the following setup My project contains two prefabs which we'll call "Cube" and "CubeT". Cube was imported from an FBX file generated by Autodesk 3DS Max, and CubeT was created within Unity. I want to be able to modify Cube's mesh collider, but Unity will not allow me to do so. Therefore, I've thought about adding the mesh within Cube to CubeT and removing Cube. The thing is, I'm worried that I'll lose the mesh when I delete Cube, and subsequently lose the reference to it in CubeT. If I reference Cube's mesh in CubeT and then remove Cube from the project by deleting the asset within Unity, what will happen? Will the needed mesh remain in the project or am I going to have to find another way?
0
How to playlay multiple Particle Systems when colliding with multiple obstacles using object pooling? I have two types of particle, one for each player Player 1 (Red Particle) Player 2 (Blue Particle) When player 1 collides with an obstacle then I want to play the red particle system, and when player 2 collides with an obstacle then I want to play the blue particle system. Code TouchControll.cs public GameObject PlayersPartical void OnTriggerEnter2D(Collider2D other) here my player collided with obstacle foreach (Transform child in transform) if (child.tag "point") GameObject partical Instantiate(twopartical Random.Range(0,1) , transform.position, transform.rotation) ParticleSystem heal partical.GetComponent lt ParticleSystem gt () heal.Play() GameObject partical Instantiate(PlayersPartical, transform.position, transform.rotation) ParticleSystem heal partical.GetComponent lt ParticleSystem gt () heal.Play() ObjectPooler.Instance.SpawnFromPool("redandbluepartical", transform.position, Quaternion.identity) ObjectPooler.cs public static ObjectPooler Instance public void Awake() Instance this System.Serializable public class Pool public string tag public GameObject prefab1 public GameObject prefab2 public int size public List lt Pool gt pools public Dictionary lt string, Queue lt GameObject gt gt pooldictionary which gameobject you should be pool void Start () pooldictionary new Dictionary lt string, Queue lt GameObject gt gt () foreach(Pool pool in pools) add a pool in list Queue lt GameObject gt objectpool new Queue lt GameObject gt () for(int i 0 i lt pool.size i ) GameObject obj Instantiate(pool.prefab1) GameObject obj1 Instantiate(pool.prefab2) obj.SetActive(false) obj1.SetActive(false) objectpool.Enqueue(obj) pooldictionary.Add(pool.tag, objectpool) public GameObject SpawnFromPool(string tag,Vector3 position,Quaternion rotation) two tag red and blue partical if(!pooldictionary.ContainsKey(tag)) Debug.Log("doesnot exist" tag) return null GameObject objecttospawn pooldictionary tag .Dequeue() here how to call my trigger objecttospawn.SetActive(true) objecttospawn.transform.position position pos objecttospawn.transform.rotation rotation rotation pooldictionary tag .Enqueue(objecttospawn) return objecttospawn Image1 Image2 How do I call these particles?
0
How to rotate a whole Bezier Curve around a given point I am using the code from the question Adding functionality to make individual anchor points of bezier continuous or non continuous to create bezier curves (I added a line renderer). How can I rotate the whole bezier curve (which may contain multiple cubic B zier segments) around a point? Please note that the rotation point could be any point including the one of the curves anchor points or control points.
0
Get MonoBehaviour components from Prefab I need to assign the script values for the following Prefab in Unity 3.5 The structure is the following Kinect Prefab MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script MonoBehaviour Script Missing Mono Script All the components have the same name. I have tried to obtain all of them in an array, but the GetComponents method does not seem to work properly. var mono MonoBehaviour mono Kinect Prefab.GetComponents(MonoBehaviour) The thing is the resulting array is empty. Any idea what might be wrong? EDIT When I do GetComponents(MonoBehaviour) I get the following error InvalidCastException Cannot cast from source type to destination type. I have tried receiving the components in var mono Component but I still don't receive anything
0
Algorithmically fracture a mesh in Unity3D? I want to create a plugin which shatters fractures meshes, so I can make every object destructible if I want to. Like in Unreal's built in feature. My quick approach to this problem is randomly generating cuts (planes) every cut divides the mesh into 2 groups left side of the cut and right side of the cut, at the points where it intersects the mesh, I add vertices to both groups. and add 1 1 face to each group with these new vertices. create the new mesh. Is there a better way? What do you recommend? Is my way even possible? If yes, what API methods should I use?
0
Need help to make and optimize a dense forest in Unity with bird view camera I'm currently developing a RTS game that has a bird view camera operating while playing the game. One of the core aspects of my game are trees. So in the previous days i was playing with trees in Unity. First i played with Unity Tree Creator however later i realized it is broken since 2018.3, and devs said it wont be fixed because it will be a community developed package in the future Then i downloaded assets from the store that are said to be highly optimized trees, however they are mostly for "3rd person camera projects" thus having around 7 14k triangles. After these experiences, i decided to export a tree prefab to fbx, then manually decrease the triangle count to around 2.5k in 3ds max, then reimport it to Unity. With this technique i was able to produce quite good results, but still not very satisfied with it. My camera view, and my "dense forest" 180 300fps... and only like 3 4 shadows For the above picture i used a Tree with 2 LOD and one billboard(BB). After playing with this i realized i can sure do better especially with playing LOD numbers, material optimization, and with the default tree trinagle optimization. However the problem is i can't model pine trees that satisfy my needs in 3ds max. So i started looking into SpeedTree documentation, however it seems a bit too professional for my needs(All the tutorials also make trees with like 20k poly tri). So regarding this story. I would like to ask the following question a bonus one about LOD Can you model quality trees with SpeedTree for Unity that have like around 1k 2k triangles, or SpeedTree is for high quality high poly trees, they algorythms won't work with lower polygon count etc? (I heared they have a simplify modifier is it good? like make a 7k triangle tree then cut it to 1k 2k) I'm thinking about using 4 5 LOD and a BB for smooth transition. In my picture i use 2 LOD and a BB and sometimes when moving the camera fast, transitions are not as smooth as i want it to be. So i would like to rather have more lower detailed meshes before trasitioning to BB. So does having a 4 5 LOD s a common practice or any better ides for this?
0
Every X months Visual Studio Code says 'UI' does not exist in the namespace 'UnityEngine' I've tried countless fixes in the last 1,5 year, and I still don't know what is the absolute fix for this. Or after fixing it, why it got fixed. Usually this happens after a Unity update, or after updating the IDE packages. I tried lots of fixes, and it seems like that it's always changing what fixes it Sometimes it's fixed by regenerating all projects files, also sometimes manually deleting them. Sometimes it's fixed by reinstalling Visual Studio. Sometimes it's fixed by downgrading the IDE packages (until now not for me, but based on some browsing, it works for some people) Switching to Visual Studio in the preferences, opening it, then switching back to Code. (At first I thought that this is just regenerates the projects files, but who knows, maybe it does something else in the background.) This time it got fixed after I switched to Visual Studio, opened Visual Studio, and it showed missing references. So I closed it, regenerated all project files, and then reopened it. Now Visual Studio works. And after this, I switched back to Visual Studio Code, and now it works there as well. (I always restart Unity and Code after these) Sometimes it isn't fixed by just going through this list one by one. Sometimes none of them fix it, so I try them all again, in different order, etc, and then it's fixed after some random combination. Most of the times only Visual Studio Code is broken, but sometimes Visual Studio is missing the references as well. Could someone tell me why this keeps occurring for a lot of people, and what is the absolute fix and why? In the log, it says that UnityEngine.UI got successfully loaded and added OmniSharp.MSBuild.ProjectManager Successfully loaded project file 'c Projects RPG UnityEditor.UI.csproj'. OmniSharp.MSBuild.ProjectManager Adding project 'c Projects RPG UnityEditor.UI.csproj'
0
How to get the physical camera sensor size on iOS Android in Unity I'm trying to get the physical camera sensor size on iOS and Android mobile devices for intrinsics calculations. On Android the sensor size should be found in the SENSOR INFO PIXEL ARRAY SIZE (Android CameraCharacteristics API). However I don't find a way to access that array via ArFoundation. I can imagine to write a plug in for that, but I would also require a plug in for iOS so I don't know if that's the right way to go. Is there maybe another (easier) way to get the physical sensor size?
0
Unity 2018.3.0f2 Blank Errors I am getting these blank errors in unity for quite a while now, as soon as I create a new Project 2D or 3D I am presented with the following and can't enter in play mode. And as a workaround I have to change the Scripting Runtime Version to 3.5 in the project settings to make it work. I cannot able to work with version 4.x I have the Window 7, .NET Framework 4.7.2 Installed, any help or advice is much appreciated. Thank you.
0
Unity3D position of 2D objects with size of Object I'm making a 2D project in Unity3D. I want to place an image in the right upper corner. I've got this working, but ofcourse the image is falling of the screen for a part (and completely when I change the screenrotation). This is the code I've got for it posImage new Vector2(Screen.width imgGear.transform.localScale.x, Screen.height imgGear.transform.lossyScale.y ) As you can see in the code I've tried to adapt the position with the size of the object, using localScale 1.0f and lossyscale 0.9...f doesn't really do much as it will be changed with 1 unit. Is their a way to get the real width and height of the objects?
0
How do I find the name of the current audio clip being played? I have a title scene and a credits scene that use the same music. When I start my game the title scene music plays, and I have my game set up so the audio manager is not destroyed on load. When I enter my credits scene I do not instruct any new music to play, but each time I reload my title scene the title music restarts because a script in the scene tells it do so. How can I get the name of the current audio track so that I will only play audio if it differs from what's currently being played? This is my "LevelMaster" script which is responsible for handling the audio in each scene. public class LevelMaster MonoBehaviour private AudioManager AudioManager SerializeField private string trackName private void Start() AudioManager GameObject.Find("AudioManager").GetComponent lt AudioManager gt () AudioManager.Play(trackName) public void PlaySound(string soundName) AudioManager.Play(soundName) public void StopSound(string soundName) AudioManager.Stop(soundName)
0
Instantiate prefab randomly but not in already occupied position I want to generate bubbles randomly on screen. When a bubble is generated in one place then other bubbles should not be generated near its radius 1 area, so they can not collide or trigger with any other bubbles. How can I do it ? public void GenerateBubble () newBubbleXPos Random.Range ( 7, 7) newBubbleYPos Random.Range ( 3, 3) bubbleClone (GameObject)Instantiate (bubblePrefab, new Vector3 (newBubbleXPos, newBubbleYPos, 0), Quaternion.identity) UIManager.instance.ChangeBubbleSprite (bubbleClone) bubbleList.Add (bubbleClone) if (bubblePosList.Contains (bubbleClone.transform.position)) bubbleClone.transform.position new Vector3(Random.Range ( 7,7),Random.Range ( 3,3),0) bubblePosList.Add (bubbleClone.transform.position) bubbleClone.transform.parent UIManager.instance.CurrentLevel.transform GLOBALS.bubbleCounter In this code every bubble is generated in a different position, but they can collide with other bubbles. I want to generate new bubbles not at the same position. My bubble colliders's radius is 1.
0
How can I ensure a radius variable doesn't get reduced below 0? For some reason when I'm using the mouse to change the radius in the Update, the minimum radius is 1 even if I set the range in the top of the script to be 0,50 and even if I check that the xradius is be 0 or higher it's still getting to 1. using UnityEngine using System.Collections using System.Collections.Generic using System.Linq using System RequireComponent(typeof(LineRenderer)) public class DrawCircle MonoBehaviour Range(0, 50) public int segments 50 public bool circle true Range(0, 50) public float xradius 15 Range(0, 50) public float yradius 15 LineRenderer line public float drawSpeed 0.3f void Start() line gameObject.GetComponent lt LineRenderer gt () line.positionCount (segments 1) line.useWorldSpace false private void Update() if (xradius gt 0) if (Input.GetAxis("Mouse X") lt 0) xradius xradius 1 CreatePoints() if (Input.GetAxis("Mouse X") gt 0) xradius xradius 1 CreatePoints() private void CreatePoints() if (circle true) yradius xradius float x float z float change 2 (float)Math.PI segments float angle change for (int i 0 i lt (segments 1) i ) x Mathf.Sin(angle) xradius z Mathf.Cos(angle) yradius line.SetPosition((int)i, new Vector3(x, 0.5f, z)) angle change In the Update I did if (xradius gt 0) But yet when using the mouse for the minimum radius it set both xradius and yradius in the sliders to 1 not sure how can it be 1 if I set the range in both xradius and yradius to be 0,50 You can see in the screenshot in the Inspector in the right both Xradius and Yradius are 1
0
Unity DontDestroyOnLoad FindObjectsOfType(GetType()).Length is always returning 1 I'm trying to have an object with the DontDestroyOnLoad property. I want an object with NetworkIdentity to persist across scenes, so I can have a holder script for RPCs. This answer suggests the following code public void Awake() DontDestroyOnLoad(this) if (FindObjectsOfType(GetType()).Length gt 1) Destroy(gameObject) Despite this, I still end up with duplicate objects. FindObjectsOfType(GetType()).Length is always returning 1, and I don't know why, or how to fix it. It makes no difference whether this object is a prefab instance or a simple object in the hierarchy. I have also tried to clone this object in my NetworkManager script, which is automatically persistent, but GameObject.Find("ObjectNameHere(Clone)") is always returning false. However, the above solution seems simpler so I'd prefer to figure out FindObjectsOfType(GetType()).Length.
0
NullReferenceException Object Reference Not Set to an Instance of an Object (How is that so and I should I solve it?) I am stuck several days because of this problem, which I am almost on the verge of giving up. (Using Unity Engine 2019.3a by the way). The TextButtonName.text can't read what TextButton is throwing to it. Meanwhile, when I did a Debug.Log test, the console shows what is the text in the TextButton. What the console showed about Debug.Log() thing should be the value of a variable assigned (hence, the Is there any way that whatever is the text at the button, will be the value that can be used for Switch Statements? If there is a way (I am sure there is), how? Thanks. When pressed, ButtonPress() will be triggered and will go to Experiment Information Scene public void ButtonPressTutorial() TextButton gameObject.GetComponentInChildren lt Text gt ().text TextButton EventSystem.current.currentSelectedGameObject.GetComponentInChildren lt Text gt ().text TextButtonName.text TextButton TextButton, although has value shown in Debug.Log, the problem is that it throws a NULL value when being thrown to TextButtonName.text Why is that? Is there that I need to do? Debug.Log(TextButton) SceneManager.LoadScene(5) Switch statements switch (TextButtonName.text) case " Tutorial" ExpNum.text "Tutorial" ExpTitle.text "Coke With Mentos Experiment" ExpDetails.text " Details will be shown here" break case "Experiment 1 Button" ExpNum.text "Experiment 1" ExpTitle.text "Lemon Volcano Experiment" ExpDetails.text " Details will be shown here" break default ExpNum.text "No Experiments" break
0
How can I make a chest that can be opened and shut in SteamVR? I'm working in Unity with SteamVR for a school project. I'm trying to have a chest that can be opened and shut. I tried using a hinge joint but it would break if the attached body was static which is what I want. I'm now trying to use a circular drive which works better but the lid to the box will move away from the intended position when colliding with the body of the box which is set to static and kinematic. I can fix this by setting the lid to kinematic but it won't collide with the body anymore. Both the lid and body are properly colliding with the hand and with a sphere I added to help test collisions. I'm assuming the issue is that two kinematic objects can't collide with each other but I don't know how else to approach this.
0
Why do asymmetric specular highlights appear in a scene with only ambient lighting in Unity? I have a scene in Unity (2019.3.0f3 Personal) using the High Definition Render Pipeline. There are no lights in the scene, and Baked Global Illumination is disabled. The skybox is a GradientSky. By all means, the lighting in the scene should be absolutely uniform, but instead there is a gradient from one side to the other. This is what the scene looks like Though the effect is faint, you can see that the right side of the plane is slightly lighter than the left. The ground shader is HDRP TesselationLit, and by bringing the Smoothness Remapping to max I can exaggerate this effect, as shown below. This is why I am under the impression the effect is specular in nature. Interestingly, if I switch the camera to the Isometric mode, the effect disappears Finally, the effect appears to occur in world rather than camera space, as shown by the changes in lighting when I rotate my camera in increments of 90 degrees What is causing this effect, and how can I disable it?
0
How do you pass arguments with UnityEvents? I was inspired by a great talk at Unite by Ryan Hipple. https youtu.be raQ3iHhE Kk?t 28m His examples didn t cover passing arguments with UnityEvents Do I need to extend UnityEvent, GameEvent and GameEventListener from a generic base class for this to work properly? If so do I need to make a new set of classes for each Type and combination of Types that I want to pass? Game Event Scriptable Object CreateAssetMenu public class GameEvent ScriptableObject lt summary gt The list of listeners that this event will notify if it is raised. lt summary gt private readonly List lt GameEventListener gt eventListeners new List lt GameEventListener gt () public void Raise() for(int i eventListeners.Count 1 i gt 0 i ) eventListeners i .OnEventRaised() public void RegisterListener(GameEventListener listener) if (!eventListeners.Contains(listener)) eventListeners.Add(listener) public void UnregisterListener(GameEventListener listener) if (eventListeners.Contains(listener)) eventListeners.Remove(listener) Listener Class public class GameEventListener MonoBehaviour Tooltip("Event to register with.") public GameEvent Event Tooltip("Response to invoke when Event is raised.") public UnityEvent Response private void OnEnable() Event.RegisterListener(this) private void OnDisable() Event.UnregisterListener(this) public void OnEventRaised() Response.Invoke()
0
Unity calculate the size of a text box before text gets drawn so it can lerp to the next size Im trying to make a dialog box image that lerps to the next size. In order to do that I need to calculate the size of the image before the text gets drawn. My idea is to use the legacy GUI stuff like guiStyle.CalcSize to get the width and guiStyle.CalcHeight to get the height. then im setting the image's layout elements min values to the GUI sizes. the width is set to the longest string in the array of "lines" the problem is that while the image does scale it doesn't do so correctly. perhaps my approach is wrong and there's an easier way? private void Update() lineText dialogueRunner.dialogText drawnText dialogueUI.lineText.text Debug.Log(prefferedValues) numberOfCharactersInLine dialogueRunner.dialogText.Length lineTextWithNewLine NewLineAfterNChar(lineText, 18) string lines lineTextWithNewLine.Split(new " n" , StringSplitOptions.None) for (int i 0 i lt lines.Length i ) longest lines.OrderByDescending(s gt s.Length).First() prefferedValues textMesh.GetPreferredValues(longest) Debug.Log(longest.Length) scale isnt correct layoutElement.minWidth size.x layoutElement.minHeight size.y void OnGUI() guiContent new GUIContent(longest) guiStyle GUI.skin.box guiStyle.alignment TextAnchor.UpperLeft guiStyle.wordWrap true boxSize new Rect(Screen.width 2, Screen.height 1, txtBGRect.sizeDelta.x, txtBGRect.sizeDelta.y) boxSize.center new Vector2(Screen.width 2, Screen.height 2) Compute how large the button needs to be. size.x guiStyle.CalcSize(guiContent).x width size.x 1 size.y guiStyle.CalcHeight(guiContent, width) height size.y GUI.Box(boxSize, longest) this draws the box Pass it a string and it will insert a line break after every n characters at end of words. public static string NewLineAfterNChar(string inputText, int lineLength) string stringSplit inputText.Split(' ') Split string into array seperatly "word1" "word2" "word3" etc... int charCounter 0 string finalString "" for (int i 0 i lt stringSplit.Length i ) iterates per word count finalString stringSplit i " " "word1 " "word2 " "word3 " charCounter stringSplit i .Length if (charCounter gt lineLength) after n characters finalString " n" charCounter 0 return finalString
0
Movement in grid in Unity I am a beginner at Unity. I want to make a game like Lightbot, but in 2d (without the z axis movement) with some obstacles. Before making the function system of the Lightbot, I want to make the in game character move on a grid by the set of key inputs (e.g. WASD) by the player. But I'm stuck here. I searched on Tilemap which makes a grid, but I have no idea how to save the set of input keydowns and move my character on this grid at once. Suppose my character is on the (0, 0) square for example. After the player taps WWDD, then my character should move to the following squares, in the following order (0, 1) (0, 2) (1, 2) (2, 2) How can I achieve my goal?
0
Unity 5 Input Field How to confirm password entry with ENTER only and not a click loss of focus I have an input field password box, currently the password is 'submitted' either by clicking Enter or by clicking elsewhere on the screen. This seems to be the designed way, as it states this in the documentation (https docs.unity3d.com Manual script InputField.html) "A UnityEvent that is invoked when the user finishes editing the text content either by submitting or by clicking somewhere that removes the focus from the Input Field." As I have other buttons on the same screen that users can click on, I would like it so mouse clicks are not counted as an invoke. Is this possible? Many thanks in advance
0
Prefabs moved to before position when zooming scene I have build some pipes for waterline drawing, like following screencast https youtu.be WnJb1JwOW78 As you can see, when I zoom in the scene, Pipes moved to lower position. When i zoom out, Pipes moved to higher position. Actually I have changed the position and moved down the pipe position before, the unexpected higher position was the pipe before position. So i guessing this problem might about cache clean. So I I try to clear the GI cache, but the problem still exist. And then I try to build a windows executable file and run game again, problem still. How to fix it? I am using Unity 2018.4
0
How can I make a gameobject snap to something when it gets close to it? Any idea if there is a way I can make a gameobject snap to something when it gets close to it? Like drag a cube around and when it gets close to something then snap to it.
0
Where does Unity save Inspector properties for objects in a scene? If I add a collection of objects to my scene and configure Inspector properties on those objects (like name, layer, tag, transform parameters, attached Components and their parameters), where does the information about those Inspector properties get saved within my project? Is it all saved within the scene's .unity file or are there other files I should look at?
0
Unity raycasting not always detecting component I am trying to determine what object I am clicking with the help of a raycast, however it doesn't always work In update I call if (Input.GetMouseButtonDown(0)) selectedObject null selectedUnits new List lt Unit gt () Select(Input.mousePosition) startPos Input.mousePosition which calls void Select(Vector2 screenPos) Ray ray cam.ScreenPointToRay(screenPos) RaycastHit hit Debug.Log( quot 1 quot ) if (Physics.Raycast(ray, out hit, 100)) OnClicked(hit.transform.tag) Debug.Log( quot 2 quot ) if (hit.transform.GetComponent lt Unit gt ()) Debug.Log( quot 3 quot ) if (!selectedUnits.Contains(hit.transform.GetComponent lt Unit gt ())) Debug.Log( quot 4 quot ) selectedUnits.Add(hit.transform.GetComponent lt Unit gt ()) if (hit.transform.GetComponent lt Building gt ()) if (hit.transform.GetComponent lt Building gt () ! selectedObject) selectedObject hit.transform.gameObject Detecting a quot building quot always works and is fine, but clicking on a quot unit quot works anywhere between 0 and 5 times per play session before it returns nothing anymore like the object doesn't exist. I have tried to find where it gets stuck and it gets stuck after the 2nd debug (debug 1 and 2 print but 3 and 4 do not). This is the Unit in the inspector and this is it in the hierarchy When drawing the ray here you can see it hits the cube 3 times before it just passes right through the 4th time. it seems like after each hit the ray penetrates the collider more and more But how and why can it only hit it a couple of times before it passes through. After a certain amount of clicks with or without moving my mouse it just doesn't hit it anymore even though in the inspector nothing changes and there are no scripts that alter the box collider. I hope someone knows what's going wrong, thanks!
0
Transform manipulator for Unity Oculus Touch game like in Quill, Medium etc I'm trying to create a script to manipulate the transform of a gameobject using the Oculus Touch just as in for instance Quill or Medium, with rotation, translation and scaling. Can somebody help me with this? My initial attempt was to focus on rotation and I got it almost working I think. Here's the code void Update() On button down if (OVRInput.GetDown(OVRInput.Button.SecondaryIndexTrigger)) originalRotation transform.localRotation originalControllerRotation OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch) While button is down if (OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger)) var controllerRotation OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch) var rotation originalRotation rotation Quaternion.Inverse(originalControllerRotation) rotation controllerRotation transform.localRotation rotation This kind of works but the rotation center doesn't look right. I want it to rotate around the center of the right touch controller and it looks to be rotating around the local origo of the gameobject. How do I modify the code so it rotates around the controller instead?
0
How can I play a particle system only when it's visible? I am making a game and it has a lot of particle systems in it as special effects, and all of them are supposed to be playing at the same time, but doing that will be heavy on the game's performance, then I thought Is it possible to play a particle system only when it is visible to the camera and stop playing it when it is out of range or hidden from the camera, maybe with physics raycasting? If it is, can someone help me to write codes that will do so.
0
When scene loaded up, Position player at a start point. (Unity2D) If pointName and player.startPoint are true, shown by the inspector, why doesn't the player's position go to the start point with a pointName of "ToNeighborhood". Note The code runs if pointName player.startPoint. It isn't running even when they both contain the same string shown by the inspector using System.Collections using System.Collections.Generic using UnityEngine public class PlayerStartPoint MonoBehaviour private PlayerController player private CameraController theCamera public string pointName Use this for initialization void Start () player FindObjectOfType lt PlayerController gt () theCamera FindObjectOfType lt CameraController gt () if (pointName player.startPoint) Debug.Log("Changing") player.transform.position gameObject.transform.position theCamera.transform.position new Vector3(transform.position.x, transform.position.y, theCamera.transform.position.z) Update is called once per frame void Update ()
0
What the difference between public int and int? I was trying to understand the difference of int and public int by checking how unity respond to it using UnityEngine using UnityEngine.Assertions.Must using UnityEngine.SceneManagement public class Bird MonoBehaviour int CurrentState 1 int PreviousState 1 Void Update() (if CurrentState ! PreviousState) transform.localScale new Vector3(transform.localScale.x 1,transform.localScale.y 1,transform.localScale.z 1) Since the equality is false, the scale of object remail unchange and in my next step, I changed quot int CurrentState 1 quot to quot public int CurrentState 0 quot and quot int PreviousState 1 quot to quot Public int PreviousState 1 quot . Isn't that this time, the equality is true as 1 ! 0 but the scale of object remained the same. Once I deleted the word quot public quot on both currentstate and previousstate, the scale increase indefinitely. I thought the word quot public quot basically meant there no access restriction but why it looks like the quot if quot statement couldn't retrieve the info correctly?
0
Create Bezier curves with random heights that connect In unity, I am trying to create several curved platforms that connect using bezier curves, however I am having issues. I understand the basics of genertating a bezier curve and I have something working well My goal is to generate a series of forward moving Bezier curves, that are all connected to each other, while also having varying lengths and points. I have something working, however I am having issues connecting the curves, while retaining random Y values for different heights in the 4 points. Below is my attempt Below is a Sketch I did in MS Paint to help explain goal From the sketch you can see that there is a diffrence in height between gameobject 0 and 1 but they are still connected. How can I generate the next points with random Y values, while still accounting for the previous curve? Any help would be greatly appreciated, Thank you for your time.
0
Unable to edit tile sizes in unity I'm trying to change the size of sprites in unity to fit the palette. Except there are no options to change multiple sprite sizes at once. But when I watched a youtube video on tilemaps and palettes, there were options to change the size of the entire palette! v2019.2.11f1 (Personal)