_id
int64
0
49
text
stringlengths
71
4.19k
0
Why does my terrain turn white when I get close to it? When I zoom in on my terrain it goes white The further in I zoom, the greater the whiteness becomes. Is this normal? Is this to speed up rendering or something? Can I turn it off? I'm also getting these error messages in the console over and over again rc.right ! m GfxWindow GetWidth() rc.bottom ! m GfxWindow GetHeight() and GUI Window tries to begin rendering while something else has not finished rendering! Either you have a recursive OnGUI rendering, or previous OnGUI did not clean up properly. Does this bear any correlation on the issue? Update I create virtual desktops to flit between using the program Deskpot. Turning this program off and restarting has stopped the above errors appearing in the console. However, I still get white terrain when I zoom in. Not a single error message. I've restarted my computer to no avail. I have an Asus NVidia GeForce GTX 760 2GB DDR5 Direct CU II OC Edition Graphics Card. Any known issues? Update I don't think it's fog...
0
I can not proceed to my room menu using photon in unity when i use PhotonNetwork.JoinRoom() I have a TextMeshProUGUI called EnterRoomName and I am trying to enter the name of the room that I'm supposed to enter, but it's not working. This is my function public void JoinRoom() PhotonNetwork.JoinRoom(EnterRoomName .text) MenuManager.Instance.OpenMenu( quot loading quot )
0
Multiple Sprite animation layers overlayed in Unity Animator I have an animator with two layers, an axe layer and a body layer. I would like to animate the two in sync with each other. They are both 64x64 sprite animations, frame by frame bitmaps. The problem I'm having is I can't figure out how to alpha blend the layers. The axe either plays and the player body becomes invisible, or the axe isn't visible. I have a bunch of states like this which each return to an idle state. And link to an animation. I'd post a screenshot but I'm not allowed. The axe layer is set to sync so the state machine looks the same, and I set the motion to the axe animations rather than the character body animations.
0
Unity, tell matched players to go pick characters (Matchmaking) I need to tell all the players in the match to go to some method that'd take them to character pick. The thing is that the pick happens inside the menu scene after the level get's preloaded (ascyncroneously). So the players stay in the same menu scene but they have to pick characters before the time runs out and the level itself starts. Is it possible to do that in multiplayer using the matchmaker? How can it be done if so? Thanks in advance!
0
iOS build size is too large in Unity I have finally completed my game and ready to upload my game to the App store, but my build size is too large. I have checked log statement and it is roughly 13.3 mb but when i build my game and test on iOS device it is 80.0 mb. Also Scripting Backend is 'Mono2x' Stripping Level is 'use micro mscorlib' Script Call Optimisation is 'Fast but no Exception' My Game size must be around 15 to 20 mb why it is too large? What i am missing?
0
Only 1 side is rendered I'm trying to get my .blend object into Unity but for some reason I see it differently in Unity than in Blender. I was trying to solve the problem and someone said that I have to go to the edit mode, then mesh, then change the normals but that is not working for me. Here is what I mean
0
Is WaitForSecondsRealtime() dependent on machine lag? I was reading the documentation and I'm trying to get some timing down for a few animations. My question is, is the WaitForSecondsRealtime dependent on machine lag or anything? A friend of mine said that WaitForSecondsRealtime was invoked at the kernel level and thus it would be as accurate as possible. Like I said I've read the documentation, but they don't really go into the specifics about how that works. Anyone have any insight?
0
Limit position rigidbody How can I limit the position of a rigidbody, between two values if I use this code public Vector3 dir Rigidbody rb void Awake() rb GetComponent lt Rigidbody gt () void FixedUpdate() rb.velocity new Vector3(0f, 0f, 6f) rb.AddForce(dir 1f, ForceMode.VelocityChange) If I use Vector3.Clamp then the object will shake
0
Sprite disappears after adding a material to it I have background which is FirsLayer, order in layer 0 and platform over it which is FirstLayer, order in layer 1. Once I add a material to the platform, the layer doesn't seem to change but it gets rendered behind the background. The material that I add 1)Why do I get such results? 2) How can I add the material to the platform and still keep it above the background? P.S. For further clarification if somebody didn't understand, I expected the sprite to stay on its original position(i.e. not to go behind the background when a material is being added to it)
0
How to handle global Data within a state machine setup? (C ) I am currently building a turn based framework (Unity,C ) I was tired of my former tight coupled systems and opted for a state machine this time, basically all components subscribe to the state Enter and state Exit event. I am aiming for scalability and structure. But I ran into a problem. If the components cannot communicate directly, how to store and forward data in between states? Example The game starts with unit placement. The player has the option to select a unit in his pool via the ui and place it on the board. The Unit creation logic is and should(?) be handled inside the level script. How does it know where to create which unit? Ive done a workaround with a static container class, with is basically my clipboard. The player assigns a grid cell for his selected unit and the game leaves the state. While leaving the state the level scripts scans the clipboard and creates any assigned units. But I feel like a cheated my attempt to really work strictly within a firm structure this time to guide the design process. Is there a better way?
0
Instantiating Prefabs at run time I'm trying to move my project to Addressables and upload assets, prefabs and screens to an archive on the server. I'm a new in Unity and this a bit challenging for me. I've prepared all prefabs for addressable usage and now I'm trying load them. All my prefabs have loads throw GameObject.Instantiate For example public class PlatformObject LocationObject other properties and methods public PlatformObject Clone() var clone ((Runner.PlatformObject)GameObject.Instantiate(this)) clone.Id this.Id clone.NextPlatforms this.NextPlatforms clone.IsStartPlatform this.IsStartPlatform clone.Level this.Level clone.Type this.Type clone.MinimumDistance this.MinimumDistance clone.AllowDispose false clone.Size this.Size return clone I've tried change this code for usage Addressables. public async Task lt PlatformObject gt Clone() var handle Addressables.LoadAssetAsync lt GameObject gt (this.name) var clone (await handle.Task).GetComponent lt PlatformObject gt () clone.Id this.Id clone.NextPlatforms this.NextPlatforms clone.IsStartPlatform this.IsStartPlatform clone.Level this.Level clone.Type this.Type clone.MinimumDistance this.MinimumDistance clone.AllowDispose false clone.Size this.Size return clone I've got a cloned object successfully, but object doesn't appears on the scene. Looks like object not initialized properly, bcouz I've got a lot of warnings like that Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption (GameObject 'Mid Town 07'). UnityEngine.Transform set parent(Transform) I've googled and have found a few solution related with parent location. Made changed but it didn't help. I'm still getting those warnings.
0
How to Make UI Open and Close on Keypress I've been working on a 2D RPG and have been trying to make a script that will open or close the public UI element that is selected in properties. I don't receive any errors, but I do receive a warning that says Assets Scripts KeyManager.cs(7,18) warning CS0414 The field 'KeyManager.activeUI' is assigned but its value is never used Here's the script that is connected to my canvas using UnityEngine using System.Collections using System.Collections.Generic public class KeyManager MonoBehaviour private bool activeUI public GameObject UI void Start() activeUI false Update is called once per frame void Update() if (Input.GetKeyDown(KeyCode.I) amp amp (activeUI false)) activeUI true UI.SetActive(true) else if (Input.GetKeyDown(KeyCode.I) amp amp (activeUI true)) activeUI false UI.SetActive(false)
0
Increase animation speed according to the swipe speed in unity for Android I have the animation done through Maya and brought the FBX file to unity. Here is my code to calculate the speed of the swipe Vector2 speedMeasuredInScreenWidthsPerSecond (Input.touches 0 .deltaPosition Screen.width) Input.touches 0 .deltaTime Now I wanted to take speedMeasuredInScreenWidthsPerSecond and use it to increase the animation speed accordingly like this animation "gmeChaAnimMiddle" .speed Mathf.Round(speedMeasuredInScreenWidthsPerSecond) However, this results in an error that I need to convert Vector2 to float. So how do I overcome it?
0
(Unity) Spawning AI cars weighted to ahead of camera? I'm working on a little project where I drive around a small city with a top down but slightly angled camera view (like GTA Chinatown Wars). Cars are instantiated from spawners that aren't in camera view, then destroy if they drive too far from the player. To spawn a new car, I loop through all my spawner gameobjects and if they are within a certain distance to the player (and not in view of the camera), then they get added to a 'spawner' list, of which I pick a random. The loop is something like this float dist Vector3.Distance(player.transform.position, spawner.transform.position) Vector3 screenPos Camera.main.WorldToViewportPoint(spawner.transform.position) bool inView screenPos.z gt 0 amp amp screenPos.x gt 0 amp amp screenPos.x lt 1 amp amp screenPos.y gt 0 amp amp screenPos.y lt 1 if (!inView amp amp dist lt 15) list.Add(spawner) This works, but I find that when I'm driving around barely any traffic spawns on roads ahead of me, maybe because the camera angle is removing a chunk of the possibility area. Is there anyway to 'weight' it so spawners in the direction the camera (or beyond) have more chance of being picked, rather than ones behind me? In games like GTA Chinatown Wars you will be driving through rows of traffic, and I'm trying to get more density.
0
Unity Cannot access variable of C script from another object I have already found similar questions on stackexchange.com related to accessing variables from another object. But my question seems to have a slightly different context and the answers from those questions are not working. I have the following (stripped off) scene comprising the standard FPS character Scene001 FPSController FirstPersonCharacter My (stripped off) Assets hierarchy is as follows (folders are enclosed with lt brackets) lt Assets gt lt Scripts gt Actions.cs lt Standard Assets gt lt Characters gt lt FirstPersonCharacter gt lt Scripts gt FirstPersonController.cs Now FirstPersonController.cs is attached to FPSController by default and Actions.cs is attached by me to FirstPersonCharacter. Excerpt from FirstPersonController.cs is as follows ... namespace UnityStandardAssets.Characters.FirstPerson ... public class FirstPersonController MonoBehaviour ... private void GetCharacter() GameObject obj GameObject.Find("FirstPersonCharacter") ok here bool is acted obj.GetComponent lt Actions gt ().is acted error here, please see below ... Excerpt from Actions.cs is as follows public class Actions MonoBehaviour ... public static bool is acted ... All I want is to access bool is acted variable of Actions.cs from FirstPersonController.cs. Error is as follows Assets Standard Assets Characters FirstPersonCharacter Scripts FirstPersonController.cs(63,38) error CS0246 The type or namespace name Actions' could not be found. Are you missing an assembly reference? To me this seems to be a problem of namespace or folder location!!? Any help is highly appreciated. Thanks in advance. Updated above Changed Action to Actions. Corrected typo (). Sample project https ufile.io knmxj
0
3D game with Pre rendered background So a friend of mine and myself are starting to create our first game together. We descided on doing a 2.5D kind of game, so a static camera that moves with the player but cannot rotate. I got the collisions object from my friend which in unity looks like this Now I'd like to create an overlay with a JPG image which is going to cover the entire viewport and is going to "be" the map itself. I want to use this JPG as a kind of background image and then hide the collisions so the player will walk into the collisions and stop there but can't actually see them. In stead, he will see the image with buildings on it. How can I do this correctly? I've gotten as far as creating a second camera which will show me the image and then trying to create an Image (Create gameobject UI Image). But I cannot find any way to continue on this. Is this a good way to do this whole 2.5D kind of thing? We want lightweight maps in our game and thought this was a good idea to go about this. Edit My friend and me are trying to create an isometric game like this. The reason behind this is that the amount of work for the map is going to be massively reduced if we can do it like this since he can then just work in photoshop, in which he's super good. This was he does not have to bother with the 3d design in detail and can make the collision blocks much faster. So does anyone know how to get this to work? Maybe someone has a partial guide on this because I cannot seem to find anyone doing it like this but I imagine that ie Commandos is made like this. It would be much appreciated!
0
Unity2D Child class inheriting onCollisionEnter() methods I may be an idiot for asking this but I can't seem to solve it myself, I have a GenericWeapon class which has a onCollisionEnter() method which I want applying to all child classes which inherit from it, here is the code public void onCollisionEnter(Collider target) Debug.Log("Collided with player!") if(target.GetComponent lt Player gt ()) bc2d.enabled false rb2d.Sleep() equip(target.GetComponent lt Player gt ()) My child class is the following using System.Collections using System.Collections.Generic using UnityEngine public class RangedWeapon GenericWeapon Start is called before the first frame update void Start() Update is called once per frame void Update() public void attack() and my in GameObject has the RangedWeapon class as a component however the GameObject does not seem to be picking up any collisions with the player. Could someone point out where I'm going wrong with this?
0
How to load unload chunks data where view port is currently focused on? I have a 2D tile based engine with infinite procedural chunk generation. But I can't invent an algorithm, that will fill only chunk tiles on view port (and destroy old). Pls help ViewPort size can changing on the fly (2 100) I can't load all chunks completely, because I need to analyze the tiles in the visibility zone class Map public List lt Chunk gt get set public int viewPortWidth 2 ... 100 public int viewPortHeight viewPortWidth public Vector2Int playerPosition get set class Chunk Tile Tiles get set public int chunkWidth 16 public int chunkHeight chunkWidth public Chunk(int leftX, int bottomY) for (int y 0 y lt chunkHeight y ) for (int x 0 x lt chunkWidth x ) randomNumberGenerator.InitState(x leftX, y bottomY) chunk x, y randomNumberGenerator.Range(100) Tiles.Add chunk x, y
0
Quaternion.RotateTowards not working as expected when parent object moves rotates I have a Tank with a rigidbody. A Turret Base is attached to the Tank via a Hinge Joint. The below TurretController script is attached to the Turret Base in order to rotate it to point towards the direction of the mouse. The turret rotates flawlessly when the tank is stationary. But once I start moving the rotation behavior becomes very erratic https youtu.be v1VuTbMtcCM If anyone is able to help explain this behavior it would be much appreciated! lt summary gt Rotates a turret towards a point at a fixed angular velocity. lt summary gt public class TurretController MonoBehaviour public float m DegreesPerSecond 40f private Vector3 m TargetPosition Received from mouse move event public void Rotate(PointInputInfo inputInfo) m TargetPosition inputInfo.Point private void RotateTurret() Vector3 direction Vector3.Scale(m TargetPosition transform.position, new Vector3(1, 0, 1)) Quaternion targetRotation Quaternion.LookRotation(direction, Vector3.up) Debug.DrawLine(transform.position, m TargetPosition) Rotate at a fixed angular velocity. transform.rotation Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime m DegreesPerSecond) private void FixedUpdate() RotateTurret()
0
Nuget in Unity with Mac OS I have moved over to Mac for Unity development, and am aware you can still use Windows .dll files in your project. I use NuGet as a secure method of getting specific dlls, and have usually done this on Windows by manually downloading the .nukpg and extracting the .dlls using WinRAR, then putting the dlls in Unity. So far, I have thought of two ways to do this on Mac 1.) Doing the same thing, but with a WinRAR alternative that can open .nukpg 2.) Using Visual Studio for Mac that has a NuGet interface built in with Unity Has anyone done this, or found a solution for getting package from NuGet in Unity for Mac?
0
Footstepper with Vr Unity I have the Footstepper Complete Footstep Solution from the unity store, and i dont get it working with the Vr, I made the footstep material like official documentation said, Then i put the Footstepper Setup in the ovrPlayer object. The problem is that sometimes sound the default fallback, so i think that the colission is not detected as it suppose. Some idea ?
0
Can I use two Collision Boxes on the same GameObject? I have two Collision Boxes on the same GameObject. I don't want the Collision Boxes to be triggers. I want the Collision Boxes on the actual GameObject, not its children. For example, if I want to check for a headshot. My reason for not wanting triggers is that a trigger is already being used. My reason for not wanting children is for cleanliness. I understand there are work arounds. I was wondering if there was a more direct approach. When there is a collision, how can I check which Collision Box is hit?
0
Making Modular Mini's Work in TTS This is not exactly game development, and I have also posted this in Arqade but it is development of a virtual playable version of a board game so maybe it loosely fits. Im hoping someone has an idea either way, or can point me to the right place to post this to get better results. I am working to create a Tabletop Simulator mod for a newly Kickstarted game Shiver Me Timbers. https www.kickstarter.com projects shivermetimbers shiver me timbers 0 description I have gotten all of the game pieces into the mod, all of the cards, tokens, tiles, I even made 3D models of the standees. Where I am getting stuck is the pirate ship miniatures. These modular miniatures are what you use to move around the board. In the game one of the things you can do is upgrade your ship. When you upgrade the ship, or get damaged in some way, (IRL) you physically add or remove pieces from the mini (when you upgrade your hull you pull apart the front and back of the ship and add another hull section in between and put them back together, when you upgrade sails you add a different Mast to the ship, when upgrading cannons you push a new cannon into one of the holes in the side of the ship, when taking damage to any of these areas the opposite. You can see how this works in the different GIFs on the kickstarter page above). Each ship can have a maximum of up to 7 hulls, 7 sails, 7 cannons or any combination in between. Also each "hull" piece has a disk wheel in it that determines what type of cargo you are carrying. The problem I am running into is making the different components come together in a way that 1. stays together when moved, 2. is able to later be removed, and 3 allows for the disks to rotate change as needed. I originally thought about just using different states for each configuration of the mini but that would turn out to be 343 states for just the ship (not to mention the 4 positions each cargo disc can be in) and creating that many states for one mini would not only take an insane amount of time making the 3D models, but would be a HUGE number of assets for the game to load, and be extremely confusing when trying to find the correct state for the configuration you need. I did decide (potentially incorrectly) to have set it up to use states for the 7 different hull configurations, and use the fixed joint tool to attach the cargo disks and that works, as long as you have each hull state set to be attached to the disk, or if you have each disk state (4 different states for the cargo types) set to attach to the base. But if I have both items having multiple states if I change the one that the Joint is going TO then it breaks and the disks fall out. The other issue with the mini's is attaching Sail Masts and Cannons. If I bring in the basic ship base and attempt to add a piece to it (aka one of the masts) I can create a snap point that allows it to fit to the correct spot but it always immediately falls over and off of the ship. I have thought about using the attach tool, but once you place the new part onto the base of the mini, by the time you can get to the attach tool and use it the new part has fallen off or fallen over. It cant just be pre done (with a gizmo on a locked object or something) because the players have to be able to modify mid game. I have enough ability with blender to work these models some (though still a bit of a beginner) and I have been trying to learn unity so that I can use the higher poly count ship models (the texturing was done with 3D geometry not a texture png) and set them up to be asset bundles. I have done a tiny bit of work with collider geometry in blender unity. I also have a minor amount of programming ability and could muddle through learning LUA and doing some scripting to make it work if that is the solution. Does anyone have any ideas how to make these "Modular" mini's a reality in the virtual space of TTS? Any Ideas are welcome. I Really want to figure this thing out. Thanks in advance.
0
Hierarchical state machines I have a rather simple state machine to control my Unity character and as the actions the character can perform increase, so does the complexity of state management, I have been reading about hierarchical state machines, they seem like the answer to my problems but I cannot 'connect' the theory to actual implementation, take for example the below Movement State public class Player Movement BaseState public Player Movement(PlayerController playerController, EntityStateMachine Comp entityStateMachineComponent) base(playerController, entityStateMachineComponent) public override void OnEnter() playerController.GetComponent lt Animator gt ().SetBool( quot IsMoving quot , true) playerController.GetComponent lt Cast Component gt ().OnCastReady.AddListener(() gt stateMachineController.ChangeToState(new Player Movement Casting( playerController, stateMachineController)) ) public override void OnExit() playerController.GetComponent lt Animator gt ().SetBool( quot IsMoving quot , false) public override void OnFixedUpdate(StateMachineContext context) If movement input is zero if ( playerController.PlayerInput.inputData.Movement.Input Vector3.zero) stateMachineController.ChangeToState(new Player Idle State( playerController, stateMachineController)) else playerController.motor.MoveAndRotateTowards( playerController.PlayerInput.inputData.Movement.Input CameraRelative) public override void OnUpdate(StateMachineContext context) if (Input.GetKey(KeyCode.LeftShift)) playerController.motor.IsSprinting true playerController.motor.Speed playerController.motor.walkSpeed playerController.motor.sprintSpreedModifier else playerController.motor.IsSprinting false playerController.motor.Speed playerController.motor.walkSpeed if (! playerController.motor.IsGrounded amp amp playerController.Rigidbody.velocity.y lt 0) stateMachineController.ChangeToState(new Player Locomotion Falling State( playerController, stateMachineController)) if (Input.GetKeyDown(KeyCode.Space) amp amp playerController.motor.IsGrounded) stateMachineController.ChangeToState(new Player Locomotion Jump State( playerController, stateMachineController)) My current goal is to have this become my super state for my movement state machine, I would like to add a sub state to this (Cast Movement) that simply calls playerController.motor.Move instead of playerController.motor.MoveAndRotateTowards as I would like to have a different style of movement while aiming a spell, but how would I write this substate so that it only handles how the character moves and falls back on the super state for everything else? I have the feeling I have to re write how my state machine works but I have no idea where to start except I probably need to seperate transitions out of the states themselves? perhaps? haha
0
sound stops after scene reloads in unity3d I'm recently facing problem regarding the inclusion of sounds in my game. Although i have used the technique of DontDestroyOnLoad() for background sounds and that work perfectly fine. But for the casual sound, it is creating problem that it stops during scene reloads. I have my script below that contains AudioClips and AudioSources and that script is attached to an empty game object, and calling that script in different scripts for the playback of the sounds. AudioScript.cs using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI public class AudioScript MonoBehaviour public AudioClip pinshit public AudioClip rowlingball public AudioSource rowling public AudioSource hit public AudioClip cheer public AudioClip strike public Text counttext public AudioClip spare public AudioClip sorrow public AudioClip winaudio GameObject music Use this for initialization void Start () rowling GetComponent lt AudioSource gt () music GameObject.FindGameObjectsWithTag("class") if (music.Length 1) else for (int i 1 i lt music.Length i ) Destroy(music i ) Update is called once per frame void Update () private void Awake() DontDestroyOnLoad(this.gameObject) To play sound on different actions routines sorrow.clip GameObject.FindWithTag("class").GetComponent lt AudioScript gt ().sorrow sorrow.Play() sorrow.volume 1
0
How do I get an NPC to follow the player(and stop when it gets within range) I'm making a game where you have a friend follow you. I have a script that partly works, but when the friend exits the trigger, it won't follow the player. How do I get the friend to follow the player once indefinitely, or until it hits the trigger again? Here is the script public Transform friend private int movespeed public int speed public Rigidbody rb Use this for initialization void Start() speedup() Update is called once per frame void Update() transform.LookAt(freind) Vector3 eulerAngles transform.rotation.eulerAngles eulerAngles.x 0 eulerAngles.z 0 transform.rotation Quaternion.Euler(eulerAngles) rb.AddRelativeForce(0, 0, movespeed) public void OnTriggerStay(Collider other) if (other.tag "Player") movespeed 0 else speedup() public void speedup() movespeed speed
0
Upgrade items on shop menu I made a game and I made a Magnet upgrade and I have 8 game objects to set active 1 by 1 every time when I upgrade the magnet and I have (int upgrade 0 ). But when I upgrade these game objects it's set active, but if I quit the game and start again all these game objects are FALSE. How can I make e.g if I upgrade to (int upgrade 6) and to make my game objects active only from element 0 to element 6. I do upgradeMagnet() to void Update but its make active only 1 game object depends from (int upgrade) if (int upgrade) is 5 and only game object element 5 is active. public GameObject upgranded public int upgrade 0 public void upgrandeMagnetButton() upgrade 1 upgradeMagnet() void upgradeMagnet() if (upgranded upgrade ) upgranded upgrade .SetActive(true)
0
Reading a Binary File in Unity I am trying to display the first two bytes of a binary file as a test. I have the following code. void DisplayValuestext() Stream s new FileStream("Assets testbinary.bin", FileMode.Open) BinaryReader br new BinaryReader(s) int dataVal br.ReadUInt16() Debug.Log(dataVal) The first 2 bytes of the binary file are "1E44" which the function ReadUInt16() should read. However, it reads the first byte of data, "1E" rather then the first 2 bytes "1E44". I believe it is because it reads 2 characters, rather than 2 bytes. When I display the 16 bit unsigned integer "dataVal" in the console, I get 25905. The value I am trying to get is 17438 which is "1E44" little endian encoded value converted to decimal. I have also attempted to use the function "ReadUInt32". This method should read the first 4 bytes, however it instead displaces by 4 characters, which is 2 bytes "1E44". The console displays "875849009". Why do I get these strange values "25905" and "875849009" and how can I resolve this to get the desired value of 17438?
0
Dynamic Aspect Ratio in Unity (for Anti Aliasing) I am using HDRP with 1920x1080 resolution. The anti aliasing works very well if the screen resolution increases and it works really bad if the screen resolution is lower than 1920x1080. Why does this happen? Is there a way to overcome this?
0
How to associate a number to a button and get that number when the user clicks on the button? I am creating buttons for each level through script as shown below private void CreateLevelButtons() for (int i 1 i lt no of levels i ) Button button Instantiate(button prefab) button.GetComponentInChildren lt Text gt ().fontSize 12 button.GetComponentInChildren lt Text gt ().text "Level " i.ToString() button.transform.SetParent(content.transform, false) button.onClick.AddListener(() gt OnClickLevelButton()) In OnClickLevelButton() function I want to determine the level number of the button that was clicked. Is there a way to associate a number to a button so that i can access that number later when the user clicks on the button?
0
Unity sprites rendering problems on Android I'm creating a simple 2d game for android, with normal sprites and animations. The problem is that when I open the game on my smartphone (Samsung galaxy trend plus), The sprites are rendered this way Of course, this is not what should happen. Moreover, within the Unity editor everything works flawlessly. My settings for the export are Texture compressions ETC2 (GLES 3.0) Tested also with "Don't override" Player settings Default orientation landscape Use 32 bit display buffer unchecked tried also with this option checked Rendering path forward tried also with Legacy Deferred Static batching Dynamic batching both checked Camera settings Clear flags Solid color tried also skybox I don't have any other scene, and this one has only one camera (I saw some topics where people were having problems because they had two or more cameras). The sprites are all .png images with transparence, except for the background, that has no transparence, but is lagging. There are three sprites which are animated using the spritesheet, but they're terribly lagging, and almost can't be seen in this screenshot. I really can't understand why, I'll continue to try, waiting for your answers. Thank you in advance! EDIT If in the player settings the orientation is set to auto rotate and the device is in portrait, all the sprites works perfectly!!! The problem is that my game is meant for landscape...
0
Creating structure to a game (Missions, Dialogue, Triggering events upon items collected, etc) monitoring the progress of a player in our code? Hello all I have been working with Unity and other game engines libraries for many years in my spare time. It's been a long twisty road full of joy and pain D In the last few months or so I have been jumping back in and noticing I really have a good grasp of the basics for almost all aspects of game development (in other words I can happily make little characters move on input in several ways with rigidbody, without rigidbody Animations I have an ok understanding with shaders and skyboxes and post processing I kind a barebones knowledge of, etc). My main issue I always come unstuck with (and end up defeated until I start building a new project which just involves doing the above stuff I listed that I already kinda understand), is managing actual Quests or Special Events throughout the game. For example, today I'm trying to make a puzzle game (similar to Monkey Island but much much more basic puzzles for now). So you start out in the game stuck inside a room, there are many items in the room , and a door and fireplace. The door is locked. To solve the puzzle you just need to use the Jug of Water on the fire, then you will be able to click the fireplace to climb out of the room. I've actually made this exact puzzle before and it all worked (I used mainly Strings and had complicated if statements to work out if the player was holding that item). But once I applied this method across a whole game (lets say you keep the empty water jug there and need it in a puzzle way later in game along with some other items etc.) then it gets majorly complicated and seems like not a good way to do it. I've read lots about text data types. Apparently its possible to create my own custom commands in text files so that I can annotate the text and use that to trigger methods in my code , but whilst I have read a bit about this on a few forum posts I cannot find much help with coding this (on a very simple beginner level). I'm hoping I can build a text file that holds items along with dialogue and mission data Item names Item description dialogue Whether they are quest items Can they be combined (and if so with what and into what) Ideally, the same system could be used for dialogue (Initial "Hello" with NPC follow up conversations does NPC give quests? if so start one final (after all quests from this NPC complete) "See ya around!" type dialogue) The text file should be able to help me from what I've read but I dont know how?!?!? I'm fairly well versed in Polymorphism so like an Item is the parent and then child class might be Food Item Weapon Item Tool Item ,etc. and I also have parsed data from text to make simple pong breakout style levels (using Json and XML). I feel like that is the way to do it, but Im missing much about adding attributes or custom markup or something like this to my text data. I know the query here is extremely broad but any broad helpful suggestions of where I can start would be greatly appreciated. Many thanks
0
Update() method never called I have a class BlinkingBehaviour which inherits from MonoBehaviour. Game objects attached to scripts containing classes that inherit from BlinkingBehaviour should, as the name suggests, blink. BlinkingBehaviour is a small class so I will share the entirety of its code here public class BlinkingBehaviour MonoBehaviour private Renderer renderer public bool BlinkingEnabled public Color BlinkingColour new Color(1.0f, 127f 255f, 39f 255f) protected float CurrentColourScale protected float ColourScaleIncrementPerUpdate 0.005f protected const float MaxColourScale 2f protected void Start() this.renderer this.gameObject.GetComponent lt Renderer gt () protected void Update() if (this.BlinkingEnabled) SetBlinkingColour() else SetColour() protected void SetColour() if (this.CurrentColourScale lt 1f) this.renderer.material.SetColor(" EmissionColor", this.BlinkingColour this.CurrentColourScale) else this.renderer.material.SetColor(" EmissionColor", this.BlinkingColour (MaxColourScale this.CurrentColourScale)) protected virtual void SetBlinkingColour() SetColour() this.CurrentColourScale ColourScaleIncrementPerUpdate if (this.CurrentColourScale lt MaxColourScale) return ResetBlinkingColourScale() protected void ResetBlinkingColourScale() this.CurrentColourScale 0f I have a class Lamp which inherits from BlinkingBehaviour. I attached Lamp.cs to an object in my scene. In my inspector, I checked the BlinkingEnabled option, expecting to see the Lamp game object blinking after I pressed "Play". However, the object did not blink. Here is my Lamp class public class Lamp BlinkingBehaviour private void Start() base.Start() private void Update() base.Update() After setting various breakpoints, I could see that the Start() method was hit in both Lamp and BlinkingBehaviour. I could also see that this.gameObject.GetComponent lt Renderer gt () returned a valid component. On the other hand, my breakpoint in the Update method in Lamp was never hit. What can I do to fix this issue? UPDATE I deleted the Start() and Update() methods from my derived class. I discovered something new The Update() method in BlinkingBehaviour is never called, even though Start() is.
0
Can I set the unity camera to have the same position in a real world? I have a problem about setting the camera in the unity to have the same extrinsic parameters as my real world camera to the origin. So let's me describe my problem step by step. I have a camera in a real world and Its extrinsic to an aruco plane was calculated. So I use the Aruco plane(You can think as a plane reference) as an world origin(0, 0, 0). The in my unity, I want to set my camera to have the same extrinsic as my real world camera. So I take an translation to set the Position in unity transform toolbox. And set the rotation by convert my rotation matrix from extrinsic to the euler's angle and set it to x, y, z rotation. So I test this by use the unity properties named "camera.cameraToWorldMatrix". You can treat this as an extrinsic of the unity camera transform to the world coordinates(0, 0, 0). So this value should equal to my extrinsic since it's use the same rotation euler's angle. But unfortunately it's not. So how can i solve this problem or there's a simpler way to set the cameraToWorldMatrix equal to my extrinsic parameters. For more information All of my coordinates system is respect to opengl (In Opencv coordinates system are negated in y and z axis from opengl) 1.Here's my extrinsic that i got from the solvePnp() function. This is an extrinsic from camera to my aruco plane. Then I use this R T to get the euler's angle rotation and translation. And in my image also show my euler and translation. So this extinsic is also my expected extrinsic. I use these euler's angle rotation and translation to set my camera in unity. Here's my code to map from the camera coordinates to the aruco plane coordinates def mapBallToArucoPlane(camera coordinates, rvec, tvec) Mapping ball in left camera coordiantes to the camera coordinates(Aruco plane coordiantes) By using the inverse of rvec tvec Since rvec tvec is the transformation matrix from Aruco gt camera, but we need camera gt Aruco R cv2.Rodrigues(rvec) 0 print(R.shape, cv2.Rodrigues(rvec)) T np.array(tvec) print(R.shape, T.shape, np.hstack((R, T)).shape, np.linalg.pinv(np.hstack((R, T))).shape) arucoPlaneToCameraMatrix np.vstack((np.hstack((R, T)), np.array( 0, 0, 0, 1 ))) cameraToArucoPlaneMatrix np.linalg.inv(np.vstack((np.hstack((R, T)), np.array( 0, 0, 0, 1 )))) plane coordinates cameraToArucoPlaneMatrix camera coordinates plane coordinates plane coordinates plane coordinates 1 return plane coordinates, arucoPlaneToCameraMatrix My output extrinsic. (Should be the same as above) Thank you very much.
0
How can I move objects pixel by pixel in the scene editor? I'm trying to find a way to move objects pixel by pixel(on my screen at least) in the scene editor. I tried a lot of different buttons but nothing seems to work, please tell me Unity has this functionality because doing it by mouse or by altering X and Y yourself is really tedious.
0
How to align edge vertices of modular props snapped on a 2D grid? For a project I am working on I create some 3D props in Blender that can be put together in a modular way on a 2D grid in Unity. In Unity I generate the grid contents using these props. Now given these two simple shapes (imagine a pipe or railing in top view) If they are put next to eachother on the grid like so (left) I want to make a smooth transition between the two so that their edge vertices align nicely (snap together, see right image above). Note that the angle between the shapes is always the same. However there are variations like straight, left, right for each intersection and also numerous shapes. How can I achieve this? I have thought of the following possibilities Just model each possible variation in blender and use the matching prop when generating the grid (I hope I can avoid this since its a lot of effort, also it's not reusable) Rig the shapes in Blender. In Unity move the bone transforms accordingly so that they align (I like this idea, but is it practical?) (Somehow) mark the vertices on the edge of the shapes and move them to where they belong i.e. modify the mesh in Unity. Are there other better ways to achieve this? I appreciate any hints and tips. I also know I am not the first one to try this so any guidance on where to look for resources and what terms to search for is also appreciated.
0
Get a Vector2 Based on Object Rotation in Unity I feel like there is an obvious answer to this but I can't find it. Is there a function in unity that gives you a Vector2 (or 3) based on the rotation of an object. for example z rotation 0 gt (0, 1) z rotation 90 gt (1,0) z rotation 180 gt (0,1) z rotation 270 gt ( 1,0) I could just write this in my script the long way, but I feel like there might be a function for it in unity
0
How do I make Ground Check stop rotating with the character when it rotate? How do I make my character routice without Ground Check rotating with it, but still follow my character? Code using UnityEngine using System.Collections public class Player MonoBehaviour public float maxspeed 10f bool facingRight true Animator anim bool grounded false public Transform groundCheck float groundRadius 0.2f public LayerMask whatIsGround public Vector2 jumpDirection new Vector2(1f, 1f) public float jumpFocre 500f bool doubleJump false void Start () anim GetComponent lt Animator gt () void FixedUpdate () grounded Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround) anim.SetBool ("Ground", grounded) if (grounded) doubleJump false float move Input.GetAxis ("Horizontal") anim.SetFloat ("Speed", Mathf.Abs (move)) GetComponent lt Rigidbody2D gt ().velocity new Vector2(move maxspeed, GetComponent lt Rigidbody2D gt ().velocity.y) void Update() if((!doubleJump) amp amp Input.GetKeyDown ("up")) anim.SetBool("Ground", false) float move Input.GetAxis ("Horizontal") jumpDirection.x move GetComponent lt Rigidbody2D gt ().AddForce(jumpDirection.normalized jumpFocre) if(!doubleJump amp amp !grounded) doubleJump true void Flip() facingRight !facingRight Vector3 theScale transform.localScale theScale.x 1 transform.localScale theScale
0
How can I completely hide and protect strings from the player in Unity? I have been using Unity to create a 2D game which will be completely offline (which is the problem), the game play needs you to enter certain strings at certain levels and Unity compiles to DLLs, which can be easily reverse engineered, so is there a way to protect those strings (the game is offline so I can't retrieve from other source)? The game relies heavily on those strings, and yes I'm aware of Obfuscation but I want something more robust. And I know that the easy way out would be doing everything online from a data source but I was wondering if it's possible. It can be decompiled like this
0
Does "Object.ToString().GetHashCode()" return a truly unique character seed? In my game I'm generating a character seed from a bunch of traits that the player chooses. The traits are all part of a Enum. In unity I've attached a script to a bunch of toggles. When the player selects a toggle I do this charGen.testCharHash trait.ToString().GetHashCode() Does this guarantee that I will have a unique number generated based on the players choice ?
0
Consistent normals at any angle in bezier curve Could not work out or find any solution for this. I have a spline which consists of bezier curves (in 3d space) in fact, any straight line will also have such problem. I take a point on the curve and need to get a normal to this point at any given angle 0 360 (say, to build a mesh around it or to calculate an offset for the movement). I understand that in 3d space we have to define a plane to build normal, normally by using Vector3.Cross(A, B) In general, one uses curve's tangent as A and, e.x., Vector3.up or right as B. But, if curve becomes vertical (it can go in any direction, imagine any track that is ground independent, like in space), it gets aligned with Vector3.up, and the direction of normals goes crazy, swaps direction and so on, which is quite logical. More, it does so not only in straight vertical position, but start to change gradually around it. So, the question is how can I get consistent (all in equally correct direction) normals, using any given curve point position and angle for normal rotation? Update The initial approach looked like this public Vector3 GetTangent(...) Vector3 q2 CalculateTangent (...) Quaternion lookAt Quaternion.LookRotation (q2) Vector3 normal lookAt Vector3.up normal Quaternion.AngleAxis (angle, q2) normal return point normal size Which generated the following normals (blue is up) Now, if I try to use the previous normal for the direction Quaternion lookAt Quaternion.LookRotation (q2, previousNormal) first of all, I don't understand what to place here Vector3 normal lookAt ? And any combination of tangent, normal and rotation gives me something like this Where it can be clearly seen that normals on the vertical are improved (though not correct), but on the horizontal all went wrong, as if I just changed Vector.up to Vector3.right. In addition, the code for generating the tube in its main part looks like this float vStep (angleTo angleFrom) pipeSegmentCount if (b 0 amp amp tP 0f) tP 0.01f if (b 0 amp amp t 0f) t 0.01f if (b spline.Nodes.Count 2 amp amp tP 1f) tP 0.9f if (b spline.Nodes.Count 2 amp amp t 1f) t 0.9f Vector3 vertexA spline.GetTangent ( pP, tP, bP, Vector3.up, pipeAngle, pipeRadius) Vector3 vertexB spline.GetTangent ( pointsTotal b s , t, b, Vector3.up, pipeAngle, pipeRadius) for (int v 1 v lt pipeSegmentCount v , i 4) vertices i vertexA vertices i 1 vertexA spline.GetTangent ( pP, tP, bP, Vector3.up, v vStep pipeAngle, pipeRadius) vertices i 2 vertexB vertices i 3 vertexB spline.GetTangent ( pointsTotal b s , t, b, Vector3.up, v vStep pipeAngle, pipeRadius) Where 0.01f and 0.99f are because ends of spline do not have control points and LookRotation produces an error about zero rotation. b and bP are node indexes, and P suffix is for "previous". This particular code is used to generate a round rail and move an object beneath it. Thus, it is important that the bottom normal is consistent and always at the bottom (when it is vertical, this bottom is not the world bottom of course, but it protrudes at the side of the tube, object will turn itself accordingly, looking forward the curve).
0
Method subscribed to an event is called twice for every time the event is raised I am trying to make an inventory system in Unity with ScriptableObjects and a text driver that displays the contents of an inventory. So far the code looks like this An InventoryObject is defined as having a quot Container quot List of ItemObjects (simple scriptable objects, they just have a little information on the object as its sprite, its name, and whether or not it is stackable) and some methods to properly add or remove items (taking item stacking into account) from that list. https pastebin.com t4P3aGmi A PlayerInventory is a script that will be carried by the player's character. It contains a method for adding items collided with to its assigned InventoryObject instance. It also contains an OnItemPickedUp event that takes its InventoryObject instance as a parameter and passes it to listeners like UpdateDisplay. OnItemPickedUp is raised whenever a collision with a compatible item happens. https pastebin.com RsV7XYPp An UpdateDisplay script that listens to the OnItemPickedUp event and subscribes the ProcessInventoryToSingleString(InventoryObject inventory) method, that subsequently calls several methods to transform the contents of the InventoryObject's Container list into a single, formatted string. https pastebin.com N0nsvcWH The items are represented by giving a GameObject with a collider2D, aSpriteRenderer and script that contains the particular ItemObject's data and sets its SpriteRenderer's sprite to the ItemObject's. The problem I'm having is that the method subscribed to the event is being called more than once for each time the event is raised. as shown by the debug logs. Sometimes it's called twice, sometimes even four. This results in my UI display showing more items than there are. https files.catbox.moe afa467.mp4 https files.catbox.moe 6oxh9b.mp4 Here are pictures of the console debug logs I appreciate any help. EDIT These errors also appear. I'd like to believe that they're unrelated.
0
Load custom resources in Unity The situation is I work in my free time on one study project. I have resources of one game packed in it's own format. My intent was to use those with Unity without converting them into Unity's inner format. But with brief analysis of Unity Api Reference I did not find anything that would help my in my efforts. Like I have custom binary files I would need to parse with Unity and upon that data create geometry, lights and so on using Unity's classes. So I wonder if it's even possible? I would really appreciate if anyone would show make a hint on this subject
0
How can I make a shader that renders only the scene's skybox? I am trying to replicate the following image There are a few ways about doing this that involve camera stacking, layers, etc. Is it possible to create a shader that will only render the skybox?
0
If I make a 3d model in a .fbx format, do I owe any royalties fees to autodesk for using fbx files in Unity? I'm currently making a game where every format for every asset is either opensource freeformat, or requires no license fees to use. I've pretty much settled happily on .ogg for audio, vorbis webm for video, .png for pictures and openoffice for documents (or .pdf files since they were free standard since 2001?) What I'd like to know though is, if I make a 3d model in a .fbx format, do I owe any royalties fees to autodesk for using fbx files in Unity? If not, does this apply to every 3d model format, or only certain ones? Do software companies like Blender Unity pay for the privilege to import fbx files so that users like me don't have to?
0
Unity 2019 Error com.unity.xr.arsubsystems 2.2.0 preview.3 Runtime ImageTrackingSubsystem XRImageTrackingSubsystem.cs57,30) error CS0506 I am opening an old project created in 2019.3 inside my new Unity 2019.4. I got this error message in Unity Console Library PackageCache com.unity.xr.arsubsystems 2.2.0 preview.3 Runtime ImageTrackingSubsystem XRImageTrackingSubsystem.cs(57,30) error CS0506 'XRImageTrackingSubsystem.Destroy()' cannot override inherited member 'Subsystem.Destroy()' because it is not marked virtual, abstract, or override Please note that this current project does not use anything related to AR quot Augmented Reality quot or XR package. I have already Googled this error message, but have not seen a solution yet. However, I guess that this error likely comes from some conflicts in the AR or XR versions. To fix this error, should I install or update the basic Unity XR or AR package ? Thank you very much.
0
How can I create a custom List of GameObject inspector which works like the default one in Unity? I need to drag and drop GameObject to ObjectField. drag and drop a group of GameObjects to list name. The main problem is either do 1 or 2 work. I need the function same as unity List Inspector for future devolvement. Code as follow. static SerializedProperty ThisList public override void OnInspectorGUI() ThisList serializedObject.FindProperty("G") List name call G serializedObject.Update() Show(ThisList) serializedObject.ApplyModifiedProperties() public static void Show(SerializedProperty list) EditorGUILayout.PropertyField(list) EditorGUI.indentLevel 1 if (list.isExpanded) EditorGUILayout.PropertyField(list.FindPropertyRelative("Array.size")) ShowElements(list) EditorGUI.indentLevel 1 private static GameObject a new GameObject 50000 private static void ShowElements(SerializedProperty list) This code can drag and drop GameObject to ObjectField. for (int i 0 i lt list.arraySize i ) list.GetArrayElementAtIndex(i).objectReferenceValue EditorGUILayout.ObjectField("OBj", list.GetArrayElementAtIndex(i).objectReferenceValue, typeof(GameObject)) This code can drag and drop a group of GameObjects to list name. if (Event.current.type EventType.DragUpdated) DragAndDrop.visualMode DragAndDropVisualMode.Copy Event.current.Use() else if (Event.current.type EventType.DragPerform) for (int j 0 j lt DragAndDrop.objectReferences.Length j ) a j (DragAndDrop.objectReferences j as GameObject) Event.current.Use() However, it not work when both codes together. If EditorGUILayout.PropertyField(list, true) I can get the same result as the unity function. but I cant Custom the List. (such as add name, change position, add button...)
0
Unable to stop navmeshagent for rotation before moving I'm trying to get the NavMeshAgent to rotate before calculating a path and proceed walking. I stumbled upon a thread that said this can be done by manually rotating the object first. However, I am still stumped as to how to do this as my unit either a)refuses to move or b)moves, but does not stop to rotate. Below is the code I've attempted. void Update() RaycastHit hit if (Input.GetMouseButtonDown(0)) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) if (Physics.Raycast(ray, out hit) amp amp hit.collider.tag "Ground") targetPosition hit.point if (transform.rotation ! lookRotation) check if unit is in line with direction of hit.point agent.Stop() stops the navmeshagent from moving. direction (targetPosition transform.position).normalized lookRotation Quaternion.LookRotation( direction) transform.rotation Quaternion.RotateTowards(transform.rotation, lookRotation, Time.deltaTime speed) perform rotation else else, if already in line, set path and walk. agent.SetDestination(targetPosition)
0
Help with OnTriggerEntered Canvas UI This seems like it should be incredibly easy and I know there are other posts out there with a similar title, but I promise you I have looked at all of them. All I want is for my canvas that simply says "you win" to appear when I enter an invisible box collider that I have . My canvas is by default set to disabled. public class YouWin MonoBehaviour public Canvas myCanvas private void Start() myCanvas GetComponent lt Canvas gt () void OnTriggerEnter (Collision Collider) myCanvas.gameObject.SetActive(true) This script seems incredibly simple and straightforward, but for whatever reason, when I enter my box, nothing at all happens. Why might this be? What am I missing? As per an answer I also tried public class YouWin MonoBehaviour public GameObject canvas void OnTriggerEnter (Collider Collider) canvas.gameObject.SetActive(true) But had no luck with this either. I've been tinkering to no avail, can you please give me some suggestions?
0
How to implement a save load system in Unity? Many game allows the player to save progress at any time and load the save back at any time (like Minecraft and Doom 3). I would like to implement it in Unity. I think I will need to put the value of every variable in every script into a save file, but how? Or maybe not?
0
unity real time terrain editor im trying to make an editor for my game. but I want to know is it possible to edit terrain map heights or textures? if the answer is true, should i make it from scratch or can I use unity editor tools in real time? is there any asset for it? thank you for helping
0
Creating teams 2v2, 3v3, etc I'm figuring out how to create games with teams. The problem is that there will be games 1v1, 2v2, and so on as well as free for all. What would be the most efficient way to do this in Unity C ? I'm thinking of making a Dictionary with players' instances and every player has an index for a team. For example, we have 2v2 game, two players have teamIndex 1 and the other two have teamIndex 2. Is this the right way to do it, or there is a better way? Thank you!
0
load scene some time (2 seconds) after object is destroyed in Unity How do I check if an object has been destroyed. And do something like change scenes 2 seconds later. this is what I tried float delay 2 void OnDestroy() delay Time.deltaTime if(delay lt 0) Application.LoadLevel("scene2")
0
Sync Collider size with bones in model I'm setting at runtime a BoxCollider2D size by taking the difference between the Y position of two bones on the model... but the size I'm getting out of this creates a collider that is almost twice as tall as the distance between the two points... am I making a dumb mistake somewhere? If it matters, it's a 3d model in a 2d environment. BoxCollider.size new Vector2( BoxDefaultSize.x, Mathf.Abs(head.position.y Mathf.Min(leftFoot.position.y, rightFoot.position.y)) ) In the picture the blue gizmo shows the foot position, the green one the head position. The collider is almost 2x the distance between them Maybe there's a better way to sync the collider with the model animation that I don't know about? Addendum Vector3.Distance(head.position, leftFoot.position) returns pretty much the same result
0
Get intersecting point of Arc, X distance from centre (Unity) I'm no mathmetician so forgive my wording when I ask this, there is no doubt an answer somewhere but I dont even know what to search for. I want to find the intersection point (B) as a Vector2 on a perfect circle. If I know X, Y, A and C I assume I can use the radius and distance to calulate the position of B based on the distance between X and C somehow? (using C if there are any methods which will accomplish this) TIA.
0
Canvas enabling is not working I have a canvas with two buttons in it and I want to enable it on the button click, but when I try to enable it, it doesn't work. However, when I try to disable it on button click it does work. Here is my code public GameObject mycanvas public void onClick() mycanvas.SetActive(true) Can someone please tell me what I am doing wrong?
0
Moving inventory items around causes reference problems I'm in the process of implementing an inventory system in my game. The script which is most important to this question is InventorySlotManager. public class InventorySlotManager MonoBehaviour ItemData itemData const int numSlots 20 Item itemsInInventory new Item numSlots SerializeField GameObject slots new GameObject numSlots SerializeField GameObject itemImagePrefab int stackSize new int numSlots void Awake() itemData GameObject.Find("Item Manager").GetComponent lt ItemData gt () void Start() AddItem(itemData.coin) AddItem(itemData.silverRing) AddItem(itemData.coin) void Update() if (Input.GetKey(KeyCode.Alpha1)) AddItem(itemData.coin) if (Input.GetKey(KeyCode.Alpha2)) AddItem(itemData.silverRing) void AddItem(Item item) int indexOfDuplicateItem System.Array.IndexOf(itemsInInventory, item) if (indexOfDuplicateItem gt 1) Text quantityTextOfDuplicateItem slots indexOfDuplicateItem .transform.Find("Item Image(Clone)").gameObject.GetComponentInChildren lt Text gt () quantityTextOfDuplicateItem.text ( stackSize indexOfDuplicateItem ).ToString() else for (int i 0 i lt numSlots i ) if (itemsInInventory i null) itemsInInventory i item GameObject itemImage Instantiate(itemImagePrefab, slots i .transform) itemImage.GetComponent lt Image gt ().sprite item.itemSprite Text quantityTextOfNewItem slots i .GetComponentInChildren lt Text gt () stackSize i item.itemQuantity quantityTextOfNewItem.text stackSize i .ToString() return This does what you'd expect. (The bit in Update is just there temporarily for testing.) When an item gets added, the function checks to see if one already exists in the items array. If not, then the for loop is executed and the item is added to the items array, an item image game object is instantiated in the corresponding index of the slots array, etc. So far so good, everything behaves properly until I start dragging items around in my DragHandler script. So I press play, my inventory has two kinds of objects in it (coin, and silver ring). They each display their correct quantities (stack sizes) as I keep adding items. Then, I move the coin from slot 0 to slot 5 and attempt to add more coins to the inventory. It stops working because the line Text quantityTextOfDuplicateItem slots indexOfDuplicateItem .transform.Find("Item Image(Clone)").gameObject.GetComponentInChildren lt Text gt () returns null at that point. What is the best way to fix this such that this reference won't become null if I move the item to a different slot after it gets added to my inventory? I think I either have to map the items array to the slots array or store all of these values, e.g., items, slots, quantitytext, in one array. Is this correct?
0
How to handle enemies outside camera view in 2d platform i am making a 2d platformer in unity like mario or adventure island, and i am placing enemies manually(not doing any spawning) in the world, and those enemies have animations and movement scripts with update function. And now my question is, how can i handle the enemies outside camera view. I just want that the enemies should update animate move only when they come inside the camera view, otherwise they should be fixed where they were manually placed in the world. Maybe not only enemies but other things like coins, stars, etc(having different animations and scripts) Should i need to use some collision trigger, like attaching trigger to camera and detecting each enemies entered inside it and enabling animations and scripts on them. Please tell me if that is an efficient way or if not please tell me if there is any simple and efficient way to do this. Please correct me if there's anything wrong. Thank you.
0
Updated Unity project from 2020.2.1f to 2021.1.7 lighting is messed up, scenes are brighter I've updated my project from 2020.2.1f to 2021.1.7 (also tried 2020.3.8), and now my scenes are much brighter for some reason Any tips? Current I use the standard pipeline I think, because the Render Pipeline Asset is set as None. I have only one realtime directional light in the scene, and no Lighting Settings set in the Lighting window. The environment is the Default Skybox.
0
Setting object position in screen space camera I'm trying to set an Image gameobject's transform.position. My canvas is "screen space camera" because I needed to use a line renderer. However, when I set the position, say to new Vector3( 320, 240) the object (in play mode) gets positioned at 16266.44, y 15360, way off screen. I've tried to reset the localPosition and such based on some other answers but it doesn't help. What else could be translating my pixel coords? var go Instantiate(HexTilePrefab, this.transform) go.transform.localPosition Vector3.zero go.transform.localRotation Quaternion.identity go.transform.localScale Vector3.one go.transform.position new Vector3(screenX, screenY)
0
Can Unity support use textures that are not square? I have been told by another highly skilled Unity artist that Unity cannot efficiently handle non square images. Since that doesn't sound right to me, I wanted to get a second or third confirmation to that claim. Having worked in the game development industry for almost 15 years, I have always understood that best practice was keeping in powers of two, but that if the UV map called for it, a 1024x512 map was acceptable, rather than using a 1024x1024 map with 1024x512 pixels of wasted UV space. Granted, that was best practice on game engines other than Unity. Can anyone confirm that in Unity's case, it is better (best practice) to have a 1024x1024 image containing UV islands occupying 1024x512 pixels, rather than using a 1024x512 image map to exactly accommodate the UVs? Which platforms can use non square images and which ones cannot with the Unity engine? I am particularly interested in whether or not this limitation affects PC builds.
0
Unity Canvas hover image does not trigger event So i have the following setup This produces the following UI Now on each of the "HudCircle"(Bottom Right Left Top), I have the following components As you can see I have a script that has the following code public class HUDAction MonoBehaviour, IPointerEnterHandler, IPointerExitHandler public Color StartColor public Color SelectedColor public Image Image private void Awake() Image GetComponent lt Image gt () StartColor Image.color public void OnPointerEnter(PointerEventData eventData) Image.color SelectedColor Debug.Log("Over") public void OnPointerExit(PointerEventData eventData) Image.color StartColor Debug.Log("Not over") Sadly when playing this scene nothing happens when I hover either of the circles. Can anyone tell me what I've done wrong?
0
Getting any type in Unity Inspector I am developing a SaveManager system for my games. Basicly what it should do is 1) Gets the "ANY" user created Serializable class by Drag amp Drop to inspector. (save data). 2) Writes that class to a file using either BinaryFormatter or XMLSerializer. I want to be able to use it in my future games. So it should be save data class(type) independant (like serializers). I will use it like an asset, import the SaveManager, give serialized class as parameter, and let it do the rest. But as i said, it should be able to use any user created serialized class. So the problem is, since that "serialized class" will be written by the user in the "game project" (not in the SaveManager project), and i don't have that "serialized" class type in my SaveManager project, i don't know how to make the SaveManager, reference the class from inspector. So lets say i create this class in the game project (not in the SaveManager project) System.Serializable public class SaveData public string Name "Name" public int Number 5 Now when i import the SaveManager project (asset) into my "game" project, i should be able to drag and drop the script to the SaveManager inspector and let it do the rest. Since BinaryFormatter works for every Serializable type, the name of the type is actually doesn't matter. I mean BinaryFormatter is type free as long as the type is serializable. I want to use that feature, and make the SaveManager type free too. So in future if i want to use, say "MyNewSaveData" serialized class, "in an another game", i want to be able to drag and drop this to SaveManager inspector and let it do the rest. Now the thing is, if i use public object SaveData in SaveManager script, unity inspector doesn't show it. if i use public Object SaveData it casts the user created type to an Object, and i lose the type i need. I tried to use System.Type, but unity doesn't show it too. Basicly what i want to do is, get "any" serialized class as reference. Like public SerializedClass SaveData or something like public Script SaveData That reference should accept "any" serialized class. Gets it's type, then casts it to that type. When i use public Object SaveData if i use SaveData.GetType(), i get the type the "user created". I have the type, in my hands, but i can't cast Object to that type. I don't know how to use that type for casting. What ever i do, it either doesn't show up in inspector, or it casted to another type and i lose the data. What should i do?
0
Set up Blob shadow projector My game completely uses baked lighting in URP and because of URP's forward renderer, point and spot lights can't cast realtime shadows on moving characters if I set their types to mixed lighting, and my game mostly takes place indoors, so directional lights wouldn't make sense. So now, I thought I'd use the blob shadow projector from the standard assets pack and it didn't work then I found out that it does not support URP. Does anyone know how I can recreate the blob shadow projector for URP? Or is there another way to create fake shadows for non static characters?
0
How do I detect whether mouse (or touch) is being pressed over thecurrent gameObject in Unity 5? I have a Canvas set as Screen Overlay, and an Image there. I want my image become an 8 direction custom pad, so I wanted to make a component script for the image. In such behavior I would like to detect, on each frame (Update()) whether the mouse (or touch 0) is being pressed over the current object, say public class MyBehavior MonoBehavior void Update() if (Application.isPlaying amp amp Input.GetMouseButton(0)) TODO Verify the mouse is pressing over this.gameObject else if (Application.isMobilePlatform amp amp Input.touchCount gt 0) Touch touch Input.GetTouch(0) if (touch.phase ! TouchPhase.Canceled amp amp touch.phase ! TouchPhase.Ended) TODO Verify the touch is pressing over this.gameObject What I need is Determine the pressed over UI object is actually this.gameObject and not one which is overlapping in front. Determine the position of the click, in the same coordinate space as the image being clicked. My goal is to calculate the appropriate direction of the click (angle) wrt the pivot of the image. I will process that direction value. I will also calculate the appropriate distance to the pivot, and process it. How can I achieve that goal? (Notes The test I want to do for standalones and mouse are actually for debug purposes)
0
SerializeField UntiyEvent not properly saving modifications in EditorWindow I'm making a node editor in Unity using an EditorWindow, I'm currently trying to make it so designers can add their own methods to a node using serialized UnityEvents but I haven't been able to get it to function properly. SerializedObject serializedObject new SerializedObject(selectedNode.NodeState) SerializedProperty property serializedObject.GetIterator() property.Next(true) while (property.NextVisible(false)) EditorGUILayout.PropertyField(property) serializedObject.ApplyModifiedProperties() serializedObject.Update() The above code runs through all necessary fields of the class so the user can modify them. Everything functions perfectly with the exception of UnityEvents. They almost do as I intend them to do, except they don't preserve the variable inputs of inserted object's method. If I keep working within the editor window they stay, but if I close the window and re open the inputted variable resets. I thought this may be caused by an issue somewhere else in my code, but all other fields work fine.
0
Multiple SpriteSheets break batching The problem I can't fit all my 2d animation sprites for all units and environment in 1 spritesheet. Everything batches fine until I use two spritesheets... I noticed the following all units from spritesheet A batch fine until something needs to be rendered fom spritesheet B. so lets say from back to camera 50units tree 50 units camera will result in 3 drawcalls... Not that bad but if you have unit tree unit tree unit tree ... like it's probably most of the time... this wil result in 100 drawcalls even though you have only two spritesheets... How can you solve this? Or better, how can i use two spritesheets and have only two drawcalls even though the sprites are at different distances to the camera Hope this image helps to understand the problem 1 the trees are on spritesheet B and batch fine 2 the batching is broken as the unitsprite sits on spritesheet A and is put in between the trees...
0
Inserting into the first available inventory slot Hello my inventory system picks up one item but does not pickup any more to fill the other two slots. It is saying the whole inventory is full when it should be one slot is full. Here is my code for the inventory and this is attached to the player. public class MedInventory MonoBehaviour public bool isFull public GameObject MedkitSlot public GameObject BandageSlot public GameObject CoffeeSlot This next script is attached to the items you pickup. public class MedPickup MonoBehaviour private MedInventory medInv public GameObject itemButton private void Start() medInv GameObject.FindGameObjectWithTag( quot Player quot ).GetComponent lt MedInventory gt () itemButton.SetActive(false) void OnTriggerStay2D(Collider2D other) if (other.CompareTag( quot Player quot )) GameObject targetSlot new GameObject 0 bool validItem true switch (gameObject.tag) case quot medkit quot targetSlot medInv.MedkitSlot break case quot bandage quot targetSlot medInv.BandageSlot break case quot coffee quot targetSlot medInv.CoffeeSlot break default validItem false break if (validItem) for (int i 0 i lt targetSlot.Length i) if (!medInv.isFull i ) medInv.isFull i true itemButton.SetActive(true) Instantiate(itemButton, targetSlot i .transform, false) Destroy(gameObject) break
0
Generate plane with script missing triangles I am trying to do a simple script to generate a plane from a script by creating a new mesh. After trying it, it seems like some of the triangles aren't showing up. I checked if they were in the list by making it publci and they are in it, so I dont understand why the last triangles aren't showing while the others are. int size 4 Mesh meshy public List lt Vector3 gt vert new List lt Vector3 gt () public List lt Vector2 gt uv new List lt Vector2 gt () public List lt int gt tri new List lt int gt () void Start() vert new List lt Vector3 gt () tri new List lt int gt () meshy new Mesh() for (int x 0 x lt size x ) for(int z 0 z lt size z ) vert.Add(new Vector3(x, 0, z)) meshy.vertices vert.ToArray() for (int i 0 i lt ((size 1) (size 1)) i ) tri.Add(i) tri.Add(i 1) tri.Add(i size) tri.Add(i size 1) tri.Add(i 1 (size 1)) tri.Add(i 1) meshy.triangles tri.ToArray() for(int i 0 i lt ((size 1) (size 1)) i ) uv.Add(new Vector2(0, 0)) uv.Add(new Vector2(1, 0)) uv.Add(new Vector2(0, 1)) uv.Add(new Vector2(1, 1)) meshy.uv uv.ToArray() GetComponent lt MeshFilter gt ().mesh meshy
0
Why doesn't my material show up on my imported model (Unity Blender) UPDATE The material does work on smaller objects like a simple sphere, but not on my big arena model, which is actually imported from blender, any suggestions? UPDATE Tried to export as .fbx, but doesn't change anything. I've imported this material pack https www.assetstore.unity3d.com en ! content 13004 I tried to apply it to my mesh, but only weird things happen, I can't see the texture at all. So I tried to apply this material in the "shader calibration scene" and that worked without any problem, even updating to the standard shader worked fine. So I tried to fix it with the following things Rebaking lighting Restarting Unity Tweaking the material settings Tweaking quality settings in Unity Building the project All these things couldn't fix it, but it should most likely be related to my project settings, since this material is working in another project (shader calibration) Here are my quality settings I'm not sure, which information is needed to answer the question, but I can provide it if you ask for it. Update with Object properties
0
Main camera transform.forward becomes up and down when looking from above The camera script is a 3rd person orbit camera, when I look straight it does what it supposed to do which is walk in the direction the camera is pointing, but when the camera is looking down from above the player, the camera's forward is now up. This means when I press W to go forwards I go into the ground and when I press S it goes upwards. Here is my movement script private void FixedUpdate() float x Input.GetAxisRaw("Horizontal") float z Input.GetAxisRaw("Vertical") Vector3 moveDirection Vector3.zero moveDirection Camera.main.transform.right moveDirection Camera.main.transform.forward moveDirection.y 0 Rotation if (x ! 0 z ! 0) anim.SetBool("Walking", true) if (x ! 0) transform.rotation Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), 0.4f) else transform.localEulerAngles new Vector3(transform.localEulerAngles.x, Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z) else anim.SetBool("Walking", false) Moving if (Input.GetKey(KeyCode.LeftShift) amp amp !idle) anim.SetBool("Running", true) rb.position z Camera.main.transform.forward Time.deltaTime runSpeed rb.position x Camera.main.transform.right Time.deltaTime runSpeed else anim.SetBool("Running", false) rb.position z Camera.main.transform.forward Time.deltaTime moveSpeed rb.position x Camera.main.transform.right Time.deltaTime moveSpeed while I'm asking, the movement script gets doubled when two keys are pressed, how do I fix it while keeping the same functionality of my current movement script?
0
Best approach for destructible car in Unity I'm developing a simple racing car game. I'm wondering what is the best approach to manage visually car destruction. For instance i think one option (expensive) is to build car 3d model with 'separate' mesh, each for any component (bump, door, glass) and relative cooliders.. Other options ? Thanks
0
Unity Bullet spawns in wrong position in client I am making a multiplayer game with prefab shooting, but unfortunately the prefab sometimes spawns in the wrong position when I shoot from a client. The bullet tends to spawn in a location where the player was a few miliseconds ago, making that the bullet sometimes spawns inside of the player which killing the player in the process. For shooting, I currently have this code setup to instantiate the bullet void Update() if (Input.GetMouseButtonDown(0)) float angle GetComponentInChildren lt Weapon gt ().angle CmdShootBullet(angle) rigidbody.AddForce(Quaternion.AngleAxis(angle 180, Vector3.forward) Vector3.right (bulletPrefab.GetComponent lt Bullet gt ().force 7.5f)) Command void CmdShootBullet (float angle) GameObject bullet Instantiate(bulletPrefab, firePoint.position, Quaternion.identity) Bullet bulletScript bullet.GetComponent lt Bullet gt () bulletScript.shotBy gameObject bullet.GetComponent lt Rigidbody gt ().AddForce(Quaternion.AngleAxis(angle, Vector3.forward) Vector3.right bulletScript.force) NetworkServer.Spawn(bullet) And this is the setup for the location of the player and the gun. The top one is the player, the bottom is the gun. My guess is that it has to do with lag, that the player position does not update soon enough, so how would I make it that the bullet spawns in the position of the player in the client rather than the position of the player in the host?
0
Target Lower API Level than Package or Plug In Requirements I am working on a project that I want to use local mobile notifications for Android using Unity as game engine. I want to reach as much as users I can, so I want to target API level 16 for the lowest Android API level. As expected, when targeting Android API level 16 for a build, build fails with that error Execution failed for task ' processReleaseManifest'. Manifest merger failed uses sdk minSdkVersion 16 cannot be smaller than version 19 declared in library androidnotifications release C Users Tumay Varel.gradle caches transforms 2 files 2.1 71d39d4badfde5815e850866bcf079c9 AndroidManifest.xml as the library might be using APIs not available in 16 Suggestion use a compatible library with a minSdk of at most 16, or increase this project's minSdk version to at least 19, or use tools overrideLibrary "com.unity.androidnotifications" to force usage (may lead to runtime failures) In documentation , it is explicitly saying that the package supports Android 4.4 (API 19) and higher API levels. I can handle this problem by targeting lowest API level 19, however I want to ask Is there a way to use this package or any other package or any plug in for required and higher API levels while not using for lower API levels than requirement at the same project?
0
Why is Vector3.MoveTowards only working on a single frame? I have three laptops in my scene and I am trying to bring them to front when I click on them. I am able to recognize which laptop is clicked by using the code below, but it doesn't move to the focus position in a single click it moves only one frame so I have to keep clicking it. void Update () if (Input.GetMouseButtonDown (0)) RaycastHit hit Ray ray Camera.main.ScreenPointToRay (Input.mousePosition) if (Physics.Raycast (ray, out hit)) if (hit.transform.name "Laptop 1") Debug.Log("Laptop 1 is clicked") Laptop1Trans.position Vector3.MoveTowards (Laptop1Trans.position, FocusPointTrans.position, moveSpeed) else if (hit.transform.name "Laptop 2") Debug.Log("Laptop 2 is clicked") else if (hit.transform.name "Laptop 3") Debug.Log("Laptop 3 is clicked") else I tried moving the move part to a method but still same behaviour. Are there any workaround?
0
Dissolve object starting from the bottom I'm currently getting into using the new "Unity Shader Graph"s and have made an OK dissolve shader that looks like this My next goal is to move this effect so the object dissolves bottom up. This is where I'm stuck. I tried blending this effect with another effect that just fades the object from the bottom up but this does not create the effect I am looking for ( 1 is the fade effect, 2 is the two shaders blended together) The end effect should look something like this How can I achieve this effect? Answers do not have to be specific to Unity and a good answer should include the thought process to creating this effect, not just code or pictures of a shader graph.
0
Unity3D Disable player input but not character movement? I'm trying to code a dash air dash for a 2D platformer. In my character controller's FixedUpdate(), I have various if statements that cause certain actions when a button is pressed. To disable player input while the dash was happening, I tried putting Dash() in an IEnumerator with a simple test code like this IEnumerator Dash() if (player.GetAxis("Horizontal") lt 0) thePlayer.GetComponent lt HeroController gt ().enabled false yield return new WaitForSeconds(0.5f) move move 2 thePlayer.GetComponent lt HeroController gt ().enabled true But since the character's physics are inside the character controller, both the player's input and the character's movements are stopped when the controller is disabled. How can I disable inputs while still allowing the character to dash?
0
Box2D Soft Body Wheel in Unity3D I was watching this video made with IForce2D, its about creating soft bodied wheels in box2D. http www.youtube.com watch?v F aDMZUVw0c I wanted help in being able to increase the Radius of the Wheel gradually. I tried increasing the natural distance of spring joint (Distance Joint) between central body and outer body. But since outer bodies are connected by revolute joint, which force the outer bodies to not change their positions. I then changed the Anchor Points of Revolute Joint to match the increase in Radius of Wheel. Now, the outer bodies start moving away from center body towards their natural Distance. But gradually some outer bodies rotate and move away from each other. Check out this video i made showing what i have done https drive.google.com file d 0B CQHvLBg5TQNlBEZXpRaVc5MDQ edit?usp sharing Note I am using Unity3D 4.3.4 with 2D Physics, Gravity is Off. Any ideas?
0
How does Unity pick which sprite atlas to load? I plan to use sprite atlases for my 2D game. All my animation is sprite animation so I'm going to use sprite atlases for my characters' sprites. My question is, if I put the same sprite in two different atlases, how does Unity decide which atlas to load? EX I have a sprite atlas per level that contains the background for that level. Sometimes, there's space left over in the atlas. So, if I want to put a sprite, which already exists in another atlas, in the empty space for that level's atlas, how does Unity know not to load both atlases?
0
How can I use a coroutine and GetAxis to rotate a game object? For the sake of learning about coroutine, I want to convert the following to a cleaner Update that just calls a coroutine. How would I do that? using UnityEngine public class Controller MonoBehaviour public float speed 5f private float deltaX void Start() deltaX transform.localEulerAngles.x void Update() deltaX Input.GetAxis("Vertical") speed deltaX Mathf.Clamp(deltaX, 90f, 90f) transform.localEulerAngles new Vector3(deltaX, transform.localEulerAngles.y, transform.localEulerAngles.z)
0
Why can't we put GameObject's into a NativeArray and pass them to a Job? I just started using the Unity Job System. It has a lot of limitations. You have to use NativeArray with it and NativeArray doesn't allow many types, notably GameObject's. It says there is a bug that you have to use non nullable types. Why can't the job system operate directly on game objects?
0
Unity and the problem with calling functions from other scripts I'm not sure how everyone handles this, but I'm running into lots of instances where I want to call a nonstatic script from another script which forces me to add the nonstatic script to the gameobject that also handles the other script. Such as, I would have two classes in different scripts public class Example1 MonoBehaviour public void someMethod() public class Example2 MonoBehaviour public void anotherMethod() if I wanted to call anotherMethod from someMethod, I would need to do this public class Example1 MonoBehaviour private Example2 exampleTwo void Awake() exampleTwo gameObject.AddComponent lt Example2 gt () public void someMethod() exampleTwo.anotherMethod() Is this really how everyone is working? It just seems extremely long and complicated, making me attach a whole bunch of scripts to one gameobject at runtime, and then I run into a whole bunch of issues with multiple copies of each script (such as with mousedown functions or input functions).
0
How to save variables into a file unity I've wanted to save progress of my game (i don't have the code , sorry) without using PlayerPrefs. If it's possible with UnityEngine.
0
Writing a glow shader I'm trying to learn writing shaders. And I've pieced together something that is kinda working. I want to create a transparent glow around a sphere. The problem I have is that I can't seem to alter the transparency of the glow. I tried experimenting with ZWrite off but that doesn't give me the desired results. The red part around the sphere is the glow. But I'm unable to change its alpha. I'd would also like to change the "blurriness" of the glow. How would I do that? EDIT so I did some more tinkering. I've changed the blending to Blend SrcAlpha OneMinusSrcAlpha and enabled ZWrite off. This allows me to change the alpha. The problem with this is that the inside of the object is also colored by the glow. I just want the glow around the circle. not inside. Shader "Custom HoleShader" Properties holeColor ("Color", Color) (1,1,1,1) glowColor ("Glow Color", Color) (1,1,1,1) glowSize ("Glow Size", Range (0.0,5)) 1.0 glowOpacity ("Glow Opacity", Range(0,1)) 1 SubShader Tags "LightMode" "ForwardBase" Pass CGPROGRAM pragma vertex vert pragma fragment frag uniform float4 holeColor uniform float4 glowColor struct appData float4 normal NORMAL float4 vertex POSITION struct v2f float4 pos SV POSITION float4 col COLOR v2f vert (appData v) v2f o o.pos mul(UNITY MATRIX MVP,v.vertex) return o float4 frag(v2f i) COLOR return holeColor ENDCG Tags "LightMode" "ForwardBase" "Queue" "Transparent" "RenderType" "Transparent" Pass ZWrite Off Blend One OneMinusSrcColor Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM pragma vertex vert pragma fragment frag uniform float4 holeColor uniform float4 glowColor uniform float strength uniform float glowSize uniform float glowOpacity struct appData float4 normal NORMAL float4 vertex POSITION struct v2f float4 pos SV POSITION float4 col COLOR float3 viewDirection float3 normalDirection v2f vert (appData v) v2f o float4 pos v.vertex (v.normal glowSize) o.pos mul(UNITY MATRIX MVP,pos) return o float4 frag(v2f i) COLOR return float4( glowColor.rgb, glowOpacity) ENDCG
0
How to write a PBR Unlit Shader in Unity? I have a REALLY specific case here I have an Texture (a webcam), that is used by a shader to pickup a few x,y colors at the cordinates, and renders to a Custom Render Texture, that is later fetched (download pixel color information from GPU to CPU), and I can handle the algorithm from there. The thing is, once I upgraded the project to PBR (Physically Based Rendering), all my Unlit scripts become PINK, and they stopped working. This is a special case because It doesn't need to appear on the screen It acts as a "Compute Shader", but with backward compatibility to old phones It works well without PBR, but once PBR is enabled it becomes pink and stops working It doesn't need to reflect, refract, output pixels or anything to the "Screen", only to my Custom Render Texture so that I can fetch it later. The algorithm doesn't fits on a Graph based programming (it has iterations and etc) Well, I didn't find documentation on how to write custom PBR shaders and here I am.
0
How to make a car follow a path? I have a 2D game and my goal is to make a car follow a path (the road in the picture) and rotate in the same time. I tried a plugin in the assets store but it didn't work well for me and i had difficulties making work as intended. If you have any suggestions, i ready to listen. Thanks for help in advance.
0
What is the right approach for using foot ik for characters in slopes(Specially when in walk or run)? i use unity but this question applies for any third person controller or enemy controller. i need to use foot ik on slopes(any condition and any kind of slope) to place foot on right places. as i considered some important third person games, it seems they only use ik when character is idle and not moving otherwise no ik is applying and leg animations run purely. i use the same approach and result looks good enough but im looking for applying when character is walking or running. as i looked, some people disable ik when leg is going up and enable it when its coming down. some other do a raycast from foot bone to the ground to check foot need ik on little distance to ground. but all of these are prototypes and has flaws. can you give me a good approach that works best in all conditions?
0
How can I reuse objects without depending on prefabs? I have several "frames" in a scene, each frame holds a different image. These frames all hold the same scripts and are in a way instances of the same concept, but the image is different in each frame. I want to find a solution for reusability. If I make a change in the hierarchy or add a script to the frame, I don't want to have to go through all the frames and make the same change. The prefab system works for this case in all ways but one There are desirable differences between the frames that I want to keep (the image for instance). But if I make a change to one frame, and click the "Apply" button, all the settings of the current frame will apply to all other frames, including the ones that are desirable. Is there a solution for this other than "Be careful not to click the Apply button" ?
0
Character Movement and Collision with Ragdoll Rigidbodies Colliders? I have a player character that I'm moving with a character controller script and it is moved by applying velocity to a Ridigbody. This works when I have a rigidbody component on the player but my character also has ragdoll colliders and rigidbodies on each body parts (set up with Untiy's ragdoll wizard). What I'd like to do is remove the ridigbody and collider that are on the player and use the ragdoll colliders and rigidbodies instead for physics movement and collision. But it's not working! When I use the rigidbody from the skeleton Root and try to apply velocity the character won't move (animation plays but she keeps running on the same spot). What do I need to do to get this working? Another issue is that if I leave the player rigidbody on but remove the large capsule collider I can move the character but collision doesn't work and she runs through static objects. I already tried with convex set to true on static meshes but it doesn't make a difference. Does somebody know what causes movement and collision not to work with the ragdoll rigidbodies and colliders?
0
How do I fix missing anti aliasing in the Unity scene view and game? Both the editor and the game seem to lack anti aliasing even though quality is set to Ultra. I chose the quot 3D quot project template when I created the project, so I am using the build in render pipeline.
0
Does Google Play allow an account to log in to the same game on 2 devices? I'm developing an online Android game with Unity. I want all Google Play accounts to have only one session logged in at a time. Do I need to write my own code to disconnect an existing session on new login attempts, or does Google Play already handle this? Edit An idea popped to my mind. I can save the logged in device's state to a a file on Google's Saved Games cloud, and write an instance specific identifier to that file that indicates who has logged on last. And checking file constantly on all instances will allow me to disconnect instances whose identifier doesn't match the one on the file on the cloud. Do you think this is a good idea? I mean, fetching file from cloud every second or so?
0
Attaching objects on collision in Unity? I'm trying to make a game where the player can connect objects Lego style with objects becoming children of any object they come into contact with, so if the parent object is moved the child is moved too, but the child object can be dragged away to disconnect it. What is the best way to go about doing this?
0
Do empty Update() methods get executed and slow down the game while playing? From an optimization point of view, is it best practice to delete the predefined update() methods in all my C scripts if there is no code inside them ? On hundreds thousands of GameObject(s) with Update() empty, does the game slow down ? Can they be left empty or is it better to delete them ?
0
Finding the closest point on a concave mesh (Unity C ) One of my game systems requires that I find the closest point on a generalized mesh, which more often than not will be concave. This prevents me from just using Unity's built in ClosestPoint function, and all other alternatives have some other caveat which prevents me from using them so far. The meshes are dynamically generated, pretty complex, and altered often, so it would be computationally unreasonable to split it into multiple convex meshes, unless there's some way I don't know about which allows fast splitting reattachment of said meshes. I considered checking a sphere around the point, and increasing the size of that sphere until I get a collision, but OverlapSphere and CheckSphere don't give any means to check the point of collision, only to check whether there was a collision at all. Continuing with that train of thought, I tried a Spherecast with the same method and the maximum distance set to zero, but that didn't work either. Spherecasts don't detect any objects which are inside of the starting sphere location, so setting the distance to zero will result in no collision every time. As a workaround to that, I tried setting the distance to a small positive number, equal to the step size which the Spherecast increases by each pass (in my case, 0.2). This almost works, but causes the cast to only detect collision points if I have a general direction to give it. There are two ways I tried to resolve this The first is by just passing in the direction from the point towards the center of the mesh I am trying to find collisions with, and although this works for a sphere, it breaks down for most of my other test cases, and just in a lot of different scenarios (Very concave polyhedra and shapes such as torii being two examples of situations where this method does not work.) The second method I tried was to just take the direction to the closest point on the last frame, and pass that into the Spherecast. Again, works in some situations, but breaks down on large dihedral angles. Neither of these are really sufficient for what I need them for. In terms of the constraints which I have to work under, the point should always be on the outside of the mesh, and the point should never be too far away from the mesh, but other than that there isn't really much else I can guarantee. Both the shape and the topology of the mesh are subject to change over time. Any help would be greatly appreciated, thanks in advance!
0
In Unity unable to find second github branch I'm using github for unity asset and for some reason I can't find new branch that was created on a different PC. I tried refreshing, fetching, reinstalling asset, reinstalling asset and recloning repository. Strangely, my laptop shows the branch, but not my personal home computer. Any ideas why is this happening?
0
Using points to unlock next scene in Unity Below is my code and I'm a beginning game designer trying to make my first game for art school teehee! ) I'm not sure how to unlock the next level with a scene I've already made called Rust Room Any ideas? o I also attached the error codes I'm getting! using System.Collections using System.Collections.Generic using UnityEngine.SceneManagement public class Example HUD hud int points const int ScorePrefix "Score " int score public void LoadLevel() if ("Score 45") load the nextlevel SceneManager.LoadScene(SceneManager.GetSceneByName(Rust Room)().buildIndex 1)
0
Determine which button is at specific coordinates I am implementing a weapon wheel in Unity and I have most of it all worked out, but am struggling with one issue My weapon wheel looks a bit like this one (example only) And mine is for something else, not weapons.. but that doesn't matter. There is no mouse involved.. the idea is to spin the wheel left and right until you've selected the item you want.. the selected one would be the one in the top most position (the example above is the bottom most position, it seems).. Anyway, I have it moving left and right just fine.. the problem now is trying to figure out which button (yes, they are implemented as UI buttons) is currently in the selected position. My initial thoughts are To calculate the center X, Y pair of the quot selected quot location and store those.. When user hits action button to select, then iterate through the 8 buttons I have in that weapon wheel and.. Calculate the current X and Y of each button in the loop If the button overlaps the quot selected quot location, then invoke that button's click() This is proving to be a real pain in the neck though.. for example, I have found that the button transform's positon is always 0,0 until you show the UI at least once.. so I have to use Update() instead of Start().. In addition, trying to calculate the overlap means needing to add width of button to current X and height to current Y and getting pixel width does not seem to be an easy task. Is there some simpler way to do this? How can I have a quot selected quot button on my weapon wheel without too much fuss like this? And if this really is the only way, then please let me know how I can get the pixel width and height of buttons.
0
Access Single Pass RenderTexture I'm trying to achieve a mirror effect where a second camera renders to a render texture, which is then passed into a shader using SetGlobalTexture. Everything works fine outside of VR, but in Steam VR it seems like the render texture only stores the texture for one eye (left), even with single pass stereo enabled in player settings. How can I access the texture for the second eye? Or rather, how can I access the texture where both eyes have been drawn, one on each half of the screen? What I'm doing at the moment void Awake() mirrorCameraRenderTexture new RenderTexture(vrCam.pixelWidth, vrCam.pixelHeight, 24) mirrorCamera.targetTexture mirrorCameraRenderTexture Shader.SetGlobalTexture(" MirrorCameraRenderTexture", mirrorCameraRenderTexture)
0
Check which object was activated first How do I check which object was activated before the other? Let's say that there's door to open. To open the door you need to press firstly the second button and then the first button...but not the other way around. I have these scripts for now Switch script (it's on 2 objects that are switches and both objects have colliders with IsTrigger checked) public var IsPressed boolean false public var triggered boolean false function OnTriggerEnter() triggered true function OnTriggerExit() triggered false function Update() if (triggered amp amp Input.GetKeyDown(KeyCode.JoystickButton1)) IsPressed true SwitchCheck script (it's on door that should be opened) public var Switch1 Switch public var Switch2 Switch function Update() if (Switch1.IsPressed amp amp Switch2.IsPressed) Destroy (gameObject) EDIT Let me explain this in detail. If Button1 Switch1 is pressed, door opens to World1.(no Button2 needs to be pressed.) If Button2 and then Button1 is pressed, door opens to the World2.
0
How is the value of transform.position updated and accessed between different private methods? I followed this YouTube video but I'm still confused about how the code actually retrieves the value of transform.position. I can understand the Camera.main.ScreenToWorldPoint code is to transform the screen position to a position in the world based on the camera's view, and it then uses this to update the transform.position as in the private void OnMouseDrag method. However, I also learnt that since the method is declared as private, the quot transform.position quot cannot retrieve the value of quot transform.position quot in each bracket. So how does the value of quot transform.position quot in private void OnMouseUp, private void Awake get updated, unless I misunderstood the concept? using UnityEngine using UnityEngine.Assertions.Must using UnityEngine.SceneManagement public class GreenBird MonoBehaviour Vector3 initialPosition private bool birdWasLaunched SerializeField private float launchPower 500 private void Awake() initialPosition transform.position void Update() if ( birdWasLaunched amp amp GetComponent lt Rigidbody2D gt ().velocity.magnitude lt 0.1) timeSittingAround Time.deltaTime if (transform.position.y gt 10.00 transform.position.y lt 10.00 transform.position.x gt 10 transform.position.x lt 10) string currentSceneName SceneManager.GetActiveScene().name SceneManager.LoadScene(currentSceneName) void OnMouseDown() GetComponent lt SpriteRenderer gt ().color Color.red private void OnMouseUp() GetComponent lt SpriteRenderer gt ().color Color.white Vector2 directionToInitialPosition initialPosition transform.position GetComponent lt Rigidbody2D gt ().AddForce(directionToInitialPosition launchPower) GetComponent lt Rigidbody2D gt ().gravityScale 1 birdWasLaunched true private void OnMouseDrag() Vector3 newPosition Camera.main.ScreenToWorldPoint(Input.mousePosition) transform.position new Vector3(newPosition.x, newPosition.y)