_id
int64
0
49
text
stringlengths
71
4.19k
0
Is It Possible To Reset UI To Initial State At Runtime Without Any Direct Assignments? Is it possible to reset UI to it's initial state (the state when game started) without directly reseting elements one by one? Thanks in advance. Edit I'm asking for runtime. (ResetToPrefabState doesn't work at runtime.)
0
How do I make my rigid body rotate a fixed angle value each time I click the movement keys Ive tried some experiments with the character rotation, but I dont want it to rotate when he touches something, but I also need to unfreeze the Z axis rotation or else the character doesnt rotate when I press a key. My code is this right now, each time I press play (with the Z axis unfreeze) the character just turns like 10 degrees each time I press a key and he is still interacting with objetcs, I dunno what I can do and I might need some help public float speed 2f private Rigidbody rb private float midJump 1 private Rigidbody rB Character Movement void Start() rb GetComponent lt Rigidbody gt () void Update() rb GetComponent lt Rigidbody gt () float moveHorizontal Input.GetAxis("Horizontal") float moveVertical Input.GetAxis("Vertical") Vector3 movement new Vector3(moveHorizontal, 0f, moveVertical) rb.AddForce(movement speed) Character Jump if (midJump 1 amp amp Input.GetKeyDown(KeyCode.Space)) rb.velocity new Vector3(0, 45, 0) midJump 2 Character Rotation else if (rb.velocity.y 0.0) midJump 1 if (Input.GetKeyDown(KeyCode.D)) rb.AddRelativeTorque(new Vector3(0, 0, 90)) rb.angularVelocity Vector3.zero if (Input.GetKeyDown(KeyCode.A)) rb.AddRelativeTorque(new Vector3(0, 0, 90)) rb.angularVelocity Vector3.zero if (Input.GetKeyDown(KeyCode.S)) rb.AddRelativeTorque(new Vector3(0, 0, 180)) rb.angularVelocity Vector3.zero if (Input.GetKeyDown(KeyCode.W)) rb.AddRelativeTorque(new Vector3(0, 0, 0)) rb.angularVelocity Vector3.zero
0
Unity Animator animations fail to play only when triggered by user input I have a unity animator setup like so. When the game runs, I can trigger each state in the state machine with user input. I can use HasExitTime flag to trigger the animation, and it will play through and loop infinitely as expected. However, when I try to use the GearChange trigger, the state machine progress bar plays, the correct box is triggered, but the animation itself doesn't play! I'm at a total loss as to what the problem is here, as everything else is exactly the same, minus the user input. The console isn't showing any errors, the animation simply doesn't respond to the state machine. What am I missing here? Unity version 2020.1.0f1 So I deleted the animator, and setup everything again the exact same way. Now the animation won't play, period. The state machine progress bars are still triggered as expected, but the animation won't play. In the transition preview, the animation won't play there either.
0
Unity UNet without a lobby How do you get an ordered list of participants (network players)? Please imagine a turn based multiplayer game. Right now there's no lobby in place and connections are established using Unity's Network Manager HUD. Now on the server, how can you get a list of all the match participants? Preferably ordered something like the player on the host should be player 1, the first player who joined the match should be player two, the second player who joined should be player three.... Any advise is welcome, thank you.
0
Changing text occurs error move initialization code to the Awake or Start function I have GameManager class that has Log method using UnityEngine using UnityEngine.UI public class GameManager MonoBehaviour public static GameManager Instance SerializeField private ScrollRect m GUIConsoleContainer SerializeField private UnityEngine.UI.Text m GUIConsole ... void Awake() Instance this ... public void Log(string message) m GUIConsole.text m GUIConsole.text message " n" GameManager class has static instance, so I can invoke Log method in anywhere like this GameManager.Instance.Log("Helloworld") However it works only first time. After invoke Log again, Unity gives me this error message get isActiveAndEnabled can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function. UnityEngine.UI.Text set text(String) I assigned reference of m GUIConsoleContainer and m GUIConsole in inspector, but I don't get it what this means and why it happens. Just using Debug.Log() or print() works without any error. How should I avoid this error message? Using Unity 2018.2.1f1. p.s. Error coming from here, another class called NetworkManager void OnReceivedBytes(IAsyncResult result) try if(m Socket null) return int resultLength m Socket.EndReceive(result) if(resultLength 0) Shutdown() return Log("Received " m RecvBuffer 0 ) lt lt Error coming from here ... ... And this is where it call OnReceivedBytes using UnityEngine using UnityEngine.UI using System using System.Collections using System.Net using System.Net.Sockets public class NetworkManager MonoBehaviour private Socket m Socket void Start() m Socket new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) m Socket.Connect("localhost", 1337) if(m Socket.Connected) Log("Connected.") m Socket.BeginReceive( m RecvBuffer, 0, m RecvBuffer.Length, SocketFlags.None, new System.AsyncCallback(OnReceivedBytes), null ) else Log("Failed to Connect.") ...
0
Is there a way to customize the Game view Editor GUI? I need to add a simple slider like scale slider in Game view to change the timescale because I usually test my games by changing timescale.
0
Tell Unity to use a certain LayerMask to raise or not OnDrop (for a class that implements IDropHandler) I am trying to make a draggable GameObject that can be dropped within a container but when i'm releasing the mouse button even though the mouse is over the container (and the dragged object too) OnDrop isn't raised on my container. To make it work i must pick the dragged GameObject right at its edge so that the mouse is over the container but not the draggable when i release the mouse button According to what I've seen drag and drop handled by unity is based on Raycasts and Raycasts could be configured to ignore objects that are in certain Layers thanks to a LayerMask the problem is that i wasn't able to find anything to apply a LayerMask Is there a way to do this or any workaround that could let the drop target know that a dragged was dropped on him?
0
How to deal with cheat avoidance and trusted client issue I hope not to be off topic here. At the moment I'm dealing with networking programming for the game I'm working on and I found different possible scenarios. I started to build code using a Platform as a Service such as Photon Unity Network which offers a quite simple system to sync players through its cloud. The problem is that by using the cloud you must have at least a trusted client in order to prevent cheating from players. I wish I could learn what is best to deal with this problem considering that opting for a client server structure would be the best but I'm a bit worried about rental purchase pricing. Is there a cheap way to have a working game server?
0
In GameCenter realtime multiplayer how to identify who is host? In GameCenter real time multiplayer how to identify who is a host?
0
Unity How to serialize show private fields and custom types in Inspector? By default, Unity only serializes public fields. How can I serialize private fields and custom types to show them in inspector?
0
How to create in game menu attached to unit I'm creating a game similar to Banner Saga, except my game will be in 3D, with a camera that can move around and zoom in and out. What I want is for a menu to appear after the user clicks on a unit. This menu must always be visible and facing the camera. The menu that has the foot and sword symbols is what I want. How can I get a similar result in 3D? The new Unity UI canvas isn't really suitable, since the camera will move around, and the menu must stay next to the unit. The menu elements can't be covered up by things in front of it, like other units. Thanks
0
Downloading 10 images and storing their data with WWW I would like to download 10 images, and store their texture data into my list. I don't really know how to do that I heard that for this you use the WWW class, so I went List lt byte gt StartDownload() List lt byte gt result new List lt byte gt () for (int i 0 i lt 10 i) WWW request new WWW("http www.example.com " i ".png") result.Add(request.texture) return result Which of course doesn't work, but I'm not sure why.
0
How can I change some tree's radius and length in C script in Unity3D? So, I have this little tree stem. It only has its initial node. All I would like to do is make it grow in length and radius in Update(). How can I do that?
0
Input.GetAxisRaw not returning zero after releasing the key In my WebGL Project here is the way for camera navigation (Movement Rotation) on Update event void UpdateMovement() bool accelerate Input.GetKey(KeyCode.LeftShift) Input.GetKey(KeyCode.RightShift) moveDirection new Vector3( Input.GetAxisRaw("Horizontal") moveSpeed, 0, Input.GetAxisRaw("Vertical") moveSpeed) moveDirection new Vector3(Input.GetAxis("Horizontal") moveSpeed, 0, Input.GetAxis("Vertical") moveSpeed) moveDirection transform.TransformDirection(moveDirection) if (Input.GetButton("Up")) moveDirection.y moveSpeed else if (Input.GetButton("Down")) moveDirection.y moveSpeed if (Input.GetAxisRaw("Mouse ScrollWheel") gt 0) moveDirection.y moveDirection.y scrollSpeed else if (Input.GetAxisRaw("Mouse ScrollWheel") lt 0) moveDirection.y moveDirection.y scrollSpeed moveDirection (accelerate ? speed moveSpeed) controller.Move(moveDirection Time.deltaTime) void UpdateRotation() if (!Input.GetMouseButton(1)) return rotationX Input.GetAxis("Mouse X") lookSpeed rotationY Input.GetAxis("Mouse Y") lookSpeed rotationY Mathf.Clamp(rotationY, 90, 90) rotationZ Input.GetAxis("Mouse ScrollWheel") transform.localRotation Quaternion.AngleAxis(rotationZ, Vector3.forward) transform.localRotation Quaternion.AngleAxis(rotationX, Vector3.up) transform.localRotation Quaternion.AngleAxis(rotationY, Vector3.left) All working fine but the problem on WebGL canvas when I rotate the camera using mouse and comes out of the bound of WebGl canvas meanwhile, I also continuously press horizontal or vertical key, then release input key doesn't work. Remember I logged the key Input.GetAxisRaw("Horizontal"),Input.GetAxisRaw("Vertical") input and found that it is not reset to zero on release. Debug.Log("Hr GetAxisRaw " Input.GetAxisRaw("Horizontal")) Debug.Log("Vertical " Input.GetAxisRaw("Vertical")) Normally when I don't use camera rotation using mouse and during this time, when i release the horizontal vertical key, it works fine.
0
Why is the Position Handle placed at certain distance away from vector3 unit in Unity? I have a vector3 value that I am setting in inspector and I am drawing a ray using OnDrawGizoms to draw that vector line. However, the position handle I made using Handles API to set the vector3 value is placed certain distance away from the vector unit. It's not placed exactly at the end point of the vector line that is drawn and I am not sure why. My goal is to just make a handle to position a vector3 value. EDIT For some reason, the handle is positioned correctly for y position alone but not for x and z positions. Here is my code In this script, it is the localTargetPosition vector3 value that I want to make my handle for. public class MovePlatform MonoBehaviour public Vector3 localTargetPosition new Vector3(5, 0, 0) public Vector3 m initialPosition get return initialPosition set initialPosition value private Vector3 initialPosition, targetPosition, targetPosDebug public float speed 3 public bool loop void Start() initialPosition transform.position SetTargetPosition(localTargetPosition) void Update() transform.position Vector3.MoveTowards(transform.position, targetPosition, speed Time.deltaTime) if (transform.position targetPosition) if (loop) SwitchDirection() public void SwitchDirection() if (transform.position initialPosition) SetTargetPosition(localTargetPosition) else targetPosition initialPosition private void SetTargetPosition(Vector3 localPosition) targetPosition initialPosition transform.TransformDirection(localPosition) targetPosDebug targetPosition void OnDrawGizmos() if (Application.isPlaying) Debug.DrawLine(initialPosition, targetPosDebug, Color.red) else Debug.DrawRay(transform.position, transform.TransformDirection(localTargetPosition), Color.red) This is the script used for making handle CustomEditor(typeof(MovePlatform)), CanEditMultipleObjects public class MovePlatformEditor Editor protected virtual void OnSceneGUI() MovePlatform movePlatform (MovePlatform)target Vector3 initialPosition movePlatform.transform.TransformPoint(movePlatform.m initialPosition) Vector3 targetPosition movePlatform.transform.TransformPoint(movePlatform.localTargetPosition) EditorGUI.BeginChangeCheck() Handles.Label(targetPosition, "Target", "button") targetPosition Handles.PositionHandle(targetPosition, movePlatform.transform.rotation) if (EditorGUI.EndChangeCheck()) Undo.RecordObject(movePlatform, "Move Handles") movePlatform.localTargetPosition movePlatform.transform.InverseTransformPoint(targetPosition) Handles.color Color.yellow Handles.DrawLine(initialPosition, targetPosition)
0
Texture not working on object I have a project that I'm having a bit of trouble with. Let me try and explain. In short, I'm trying to apply a texture to an object, but instead it is a solid color. I built a building in "Autodesk 123d design", and exported it as stl. Then I used an online converter to convert it to obj, then added that to the unity scene. I created a material with a texture and tried to apply it to the object, but it was a solid color. I think the UVs on the object might be messed up. I tried some things in blender, but had no luck. Any ideas on how I can fix this? Edit Here is the 3D model I'm working with http www.123dapp.com 123D Design Conisbrough Castle Keep 4578568
0
How to determine the amount of idel time left in main thread for Unity before next frame? Hi I'm trying to improve a thread tool and would like to make a function which use the idle time before the next frame. So how can I determine the time left?
0
Adding 90 degree Y rotation into script I'm using the following script to move a spray bottle around a head. It should looke like in a barber shop. The code works fine I have assigned the script to the spray bottle, and I have set the head as the target. One thing that is wrong is that the spray bottle needs to have a 90 yaw rotation in order to face the head. I have tried the wildest things to include these 90 degrees, all produced weird results. Could anybody state how to include this 90 Y rotation into the script? Thank you very much! using UnityEngine using System.Collections AddComponentMenu("Camera Control Mouse Orbit with zoom") public class MouseOrbitImproved MonoBehaviour public Transform target public float distance 5.0f public float xSpeed 120.0f public float ySpeed 120.0f public float yMinLimit 20f public float yMaxLimit 80f public float distanceMin .5f public float distanceMax 15f private Rigidbody rigidbody float x 0.0f float y 0.0f Use this for initialization void Start () Vector3 angles transform.eulerAngles x angles.y y angles.x rigidbody GetComponent lt Rigidbody gt () Make the rigid body not change rotation if (rigidbody ! null) rigidbody.freezeRotation true void LateUpdate () if (target) x Input.GetAxis("Mouse X") xSpeed distance 0.02f y Input.GetAxis("Mouse Y") ySpeed 0.02f y ClampAngle(y, yMinLimit, yMaxLimit) Quaternion rotation Quaternion.Euler(y, x, 0) distance Mathf.Clamp(distance Input.GetAxis("Mouse ScrollWheel") 5, distanceMin, distanceMax) RaycastHit hit if (Physics.Linecast (target.position, transform.position, out hit)) distance hit.distance Vector3 negDistance new Vector3(0.0f, 0.0f, distance) Vector3 position rotation negDistance target.position transform.rotation rotation transform.position position public static float ClampAngle(float angle, float min, float max) if (angle lt 360F) angle 360F if (angle gt 360F) angle 360F return Mathf.Clamp(angle, min, max)
0
Unity Animator bool transitions keep re entering state while true My StateMachine is triggered in a loop as long as transition boolean is true. I have made sure my code only runs once, where I set the animation bool animator.SetBool("talk", true) This does trigger the transition but the problem is that it re triggers every frame as long as the bool is true. I had the same issue with a normal state earlier, but there I could turn off "Can transition to self" which solved it. However a StateMachine does not have that option. I want the animation to play until the bool is set back to false, so using a trigger would not be good here. EDIT For some reason it seems the "Transition duration" is the one resetting my animation. So if I change that to 3, it re enters every 3 seconds, and so on. This seems really weird? How do I just make sure that the animation plays until its done, then it re enters (to choose another random talking animation from my StateMachine), as long as talk true?
0
Shader which supports vertex colors and pixel lights? From my question at Unity Answers Hello everyone, I'm facing a bit of a problem here I need a shader which has the ability to colour individual vertices and be lit pixel by pixel. Until recently, I was planning to use just vertex shading, since I couldn't find any info about this. The thing, it looks like this Bad shading 1 and Bad shading 2. As you can see, it is horrendously bizarre and even glitchy. Here is the shader I'm using right now (ShaderLab syntax) Shader "Alpha VertexLit Colored" Properties Color ("Main Color", Color) (1,1,1,1) SpecColor ("Spec Color", Color) (1,1,1,0) Emission ("Emmisive Color", Color) (0,0,0,0) Shininess ("Shininess", Range (0.01, 1)) 0.7 MainTex ("Base (RGB) Trans (A)", 2D) "white" SubShader ZWrite Off Alphatest Greater 0 Tags Queue Transparent Blend SrcAlpha OneMinusSrcAlpha ColorMask RGB Pass Material Shininess Shininess Specular SpecColor Emission Emission ColorMaterial AmbientAndDiffuse Lighting On SeparateSpecular On SetTexture MainTex Combine texture primary, texture primary SetTexture MainTex constantColor Color Combine previous constant DOUBLE, previous constant Fallback "Alpha VertexLit", 1 I searched around on the Unity forums, wiki and also on Google, but I found no resources for this. I really need the vertex colours here, it's a crucial element of the graphic style of my game, and is the simplest way to do what I want. Any help is immensely appreciated. Does anyone know if such kind of shader exists?
0
Unity2D Best way to determine degrees between two colliding entities? I'm trying to determine the collision direction between two objects. I'll be using this for various things such as creating blood entities in a specific direction proportional to where the other entity is hitting an entity. What's the best most efficient way to do this? I've been doing this but it seems unstable not to be working. Assuming both entities are center pivoted, I use trigonometry to find the angle like atan(b a). For some reason the output angle seems to be pretty random. Here's the method I made protected void checkCollisionDirection(Collision2D target) Vector3 positionDifference target.gameObject.transform.position gameObject.transform.position int quadrant 0 float x positionDifference.x float y positionDifference.y float degrees Mathf.Atan (y x) Mathf.Rad2Deg if (positionDifference.x gt 0 amp amp positionDifference.y gt 0) quadrant 1 else if (positionDifference.x lt 0 amp amp positionDifference.y gt 0) quadrant 2 degrees 180 else if (positionDifference.x lt 0 amp amp positionDifference.y lt 0) quadrant 3 degrees 180 else if (positionDifference.x gt 0 amp amp positionDifference.y lt 0) quadrant 4 degrees 360 hitDirectionDegrees degrees I'm open to any suggestions that can find an angle between two entities.
0
Adding a function call to a prefabbed button in Unity For each of my scenes, I have an empty GameObject Manager that stores my scripts for setting up the level, keeping track of variables, etc. On my main screen, I have a play button that isn't instantiated I simply dragged it into the editor. In my script Main.cs I have a function Play() which calls LoadLevel("Game"). To get my play button to call the Play function, I dragged Manager into the onClick slot and selected the function. This worked fine and I have a functional play button. Unfortunately, this is not working for the prefabbed buttons I need to instantaite in my Game scene. In Game.cs I have a function LayoutButtons() which is both public and returns void, yet I am unable to drag Manager into the slot on my prefabbed button. Even if I do it before converting the button to a prefab, it simply disappears once it becomes a prefab. I've managed to work around this by putting my LayoutButtons() function in a new script which I attached directly to the prefab, but I'd like to keep the function within Game.cs and attached to my manager object if that's possible.
0
Help creating combat for collection type game sorry for my odd terminology, I am rather new to all this I'm creating a collection pokemon type game. as of right now I have created a separate GameObject prefab for every monster character in the game. Each gameobject contains a script with enumerated values for it's stats. When combat begins It calls a random monster from a pool of gameobjets. The problem is at this point I'm not sure how to have it create a new instance of the enemy in a way where it retains the values in it's public floats from the prefab or have it's level be adjusted as it enters. And I don't know how I can derive it's stats and properties for scripts outside the function that spawned it. as the function that creates the new duplicate won't remember the new creature after the function resolves. so In short, How can I reference the enumerated integers of a newly duplicated gameobject I was asked to include some more information on what I've coded public List lt baseMonsters gt allMonsters new List lt baseMonsters gt () public void EnterBattle(Rarity rarity) this code swaps camera view to the battlefield from the overworld map playerCamera.SetActive(false) battleCamera.SetActive(true) call function to determine which monster appears baseMonsters battleMonster GetRandomMonsterFromList(GetMonsterRarity(rarity)) returns which monster was chosen Debug.Log (battleMonster.name) prevents the player from moving after combat begins player.GetComponent lt PLayermove gt ().isAllowedtoMove false Creates the defending monster GameObject dMon Instantiate (emptyMon, defencePodium.transform.position, Quaternion.identity) Ensures scale from original is preserved dMon.transform.localScale battleMonster.transform.localScale Vector3 MonLocalPos new Vector3 (0, 1, 0) dMon.transform.parent defencePodium dMon.transform.localPosition MonLocalPos Adds the stat components of the original prefab baseMonsters tempMon dMon.AddComponent lt baseMonsters gt () as baseMonsters tempMon battleMonster dMon.GetComponent lt SpriteRenderer gt ().sprite battleMonster.image bm.ChangeMenu (BattleMenu.Selection) the issue that I see with the code is that it's transforming an already existing object into what the prefab monster is, not copying it. what method can I use to copy the prefab in a way I can easily reference in the same function to change it's level? Update ok so changing everything over to instantiating a GameObject is what I want. now there is the other part from the code before public List lt baseMonsters gt GetMonsterRarity(Rarity rarity) List lt baseMonsters gt returnMonster new List lt baseMonsters gt () foreach (baseMonsters Monster in allMonsters) if (Monster.rarity rarity) returnMonster.Add (Monster) return returnMonster public baseMonsters GetRandomMonsterFromList(List lt baseMonsters gt monList) baseMonsters mon new baseMonsters () int monIndex Random.Range (0, monList.Count 1) mon monList monIndex return mon I was following a tutorial when I created this code, I am starting to understand more and more how spaghetti it is. sorry for all the Alike Terms, baseMonsters is a class that houses things like the rarity and stats of the monster. These functions are searching by and for that script. How can I convert these codes over to searching the class from a list, to a Gameobject from a list, and still be able to read baseMonsters of each respective GameObject and it's rarity int? as of right now, one workaround I can think of is to create a seperate list for each rarity. that way I can skip needing to read the rarities in the baseMonsters script entirely. But I will still need to know how I can call that class script for other things like determining level of the monster and what it's attacks will be?
0
Why does the object rotate to a random direction when I start dragging? I'm trying to do drag to rotate sort of thing, so far the code is fine. However when starting to drag (left clicking first), the object rotate to a random direction first which looks odd. here is my code public Camera cam public float smoothAngle, dragPower .3f public bool isRadial true float angle, angleOld, angleDelta, angleRef Vector2 mousePosOld, mousePosDelta Vector2.zero void Update() Vector2 mousePos cam.ScreenToWorldPoint(Input.mousePosition) if (Input.GetMouseButton(0)) mousePosDelta mousePos mousePosOld float rotX (mousePosDelta.magnitude Time.deltaTime) dragPower Mathf.Sign(mousePos.y) Mathf.Sign(Vector2.Dot(Vector2.right, mousePosDelta)) transform.Rotate(Vector3.forward, rotX) mousePosOld mousePos angleDelta Mathf.DeltaAngle(angleOld, transform.localEulerAngles.z) angleOld transform.localEulerAngles.z else transform.RotateAround(transform.position, transform.forward, angleDelta) angleDelta Mathf.SmoothDampAngle(angleDelta, 0, ref angleRef, smoothAngle) this is the effect
0
Unity raycasting not always detecting component I am trying to determine what object I am clicking with the help of a raycast, however it doesn't always work In update I call if (Input.GetMouseButtonDown(0)) selectedObject null selectedUnits new List lt Unit gt () Select(Input.mousePosition) startPos Input.mousePosition which calls void Select(Vector2 screenPos) Ray ray cam.ScreenPointToRay(screenPos) RaycastHit hit Debug.Log( quot 1 quot ) if (Physics.Raycast(ray, out hit, 100)) OnClicked(hit.transform.tag) Debug.Log( quot 2 quot ) if (hit.transform.GetComponent lt Unit gt ()) Debug.Log( quot 3 quot ) if (!selectedUnits.Contains(hit.transform.GetComponent lt Unit gt ())) Debug.Log( quot 4 quot ) selectedUnits.Add(hit.transform.GetComponent lt Unit gt ()) if (hit.transform.GetComponent lt Building gt ()) if (hit.transform.GetComponent lt Building gt () ! selectedObject) selectedObject hit.transform.gameObject Detecting a quot building quot always works and is fine, but clicking on a quot unit quot works anywhere between 0 and 5 times per play session before it returns nothing anymore like the object doesn't exist. I have tried to find where it gets stuck and it gets stuck after the 2nd debug (debug 1 and 2 print but 3 and 4 do not). This is the Unit in the inspector and this is it in the hierarchy When drawing the ray here you can see it hits the cube 3 times before it just passes right through the 4th time. it seems like after each hit the ray penetrates the collider more and more But how and why can it only hit it a couple of times before it passes through. After a certain amount of clicks with or without moving my mouse it just doesn't hit it anymore even though in the inspector nothing changes and there are no scripts that alter the box collider. I hope someone knows what's going wrong, thanks!
0
Checking if shapes will tessellate I'm trying to figure out where to start with getting code together to check if a shape tessellates. An example Consider that the shapes cannot be rotated, just as is. A 'compound' shape (as seen in the pic second and third shapes) will have a series of co ordinates that make them up. Where could I begin to getting the computer to figure out if they can tessellate? I'm using c amp unity. Thanks in advance.
0
Unity 2D Dealing damage when character is crushed between two solid objects Whats the best approach to dealing damage to a player when they get stuck between two solid objects? For instance, I'm trying to make moving platforms that the player can ordinarily touch. It's only when the player is caught in between the moving platform and the ceiling, for example, that damage is dealt or the player dies. So, what would be the best way to approach this? Thanks in advance!
0
Unity warning animations neck and head have scale I always get this warning if I import my model to unity Clip 'soldier idle' has import animation warnings that might lower retargeting quality Note Activate translation DOF on avatar to improve retargeting quality 'neck' has scale animation that will be discared. 'head' has scale animation that will be discared. Even though there are in fact no scale animations on the bones neck and head as you can see in my blender dopesheet. So why is this warning showing?
0
Equal 3D icon size visualization in Unity I have some Icons (Sprite rendered in 3d world) whose icons are equal size (scale 1). Now I am trying to implement a solution that icons visually show at same size. If you see the icon at distance then it looks very small when you near the icon then it look bigger. So I want to visualize them equally. For this reason, first I got the near scale value which is .5 (suitable) and far scale maybe around 1.5. Now, here is my code but it producing very large scale value. void Update() foreach (var item in iconsObjects) float size Vector3.Distance(activeCamera.position, item.transform.position) if (size lt 2000) for optimization purpsose only conside near object under 2000m distance float finalSize Mathf.Clamp(size, 0.5f, 2f) item.localScale new Vector3(finalSize, finalSize, finalSize) I thought Mahtf.Clamp will work within the context but it is not suitable here as it is applying scale 2 to the near objects where it should be around .5.
0
How do I change a Unity 4.6 Sprite's textureRect at runtime? I'm using Unity 4.6, and I've made a sprite like this AtlasFrameData frame testAtlas.GetFrameByIndex(0) Rect spriteRect new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y) Sprite theSprite Sprite.Create( testAtlas.AtlasTexture, spriteRect, new Vector2(0, 0)) The texture is an atlas, and I have a bunch of data read in from an XML file telling me where the frames are. I want to do this in Update() AtlasFrameData frame testAtlas.GetFrameByIndex( currentFrame) Rect spriteRect new Rect(frame.Position.x, frame.Position.y, frame.FrameSize.x, frame.FrameSize.y) theSprite.textureRect spriteRect But I'm unable to do this since .textureRect is readonly. I could create a new Sprite each frame, but I suspect this is not going to perform well with tons of Sprites.
0
How can I add a glow effect around a pair of wings in Unity without post processing? Basically I want to use post processing and then I found a tutorial to achieve my goal. However, the artist want a pure shader to achieve this, without any C script hanging in the main camera. Any idea to implement?
0
Unity not opening in Ubuntu I installed the latest version version of Unity for Linux from the official website, but when I try to launch Unity, it displays a blank dialog box. I waited for a long time, but nothing happens. These are my system specifications. I was running Unity on the same computer, several months ago, using Windows. Model Thinkpad R500 Processor Intel Core 2 Duo CPU P8600 2.40GHz 2 RAM 2Gb DDR3 RAM Storage 155Gb HDD Graphics Card ATI Mobility Radeon HD 3400 Series 128mb dedicated GFX Why is it doing this? Is there a problem with the latest build? What should I do to fix it?
0
Vive SteamVR Stereo Rendering mirror doesn't reflect lineRenderer lines steadily I'm creating a SteamVR game in Unity. I'm using the Vive SteamVR Stereo Rendering Toolkit to create the mirror effect. I also wrote a script to render three lines between headset, and two controllers, with lineRenderer. The lines are working fine, but in the mirror reflection, I can only see the lines rendered one at the time, as opposed to all three lines visible at the same time. Why is that? Edit 1 Add an image of what I see In my game, I used three balls to represent the headset, the left controller and the right controller. I see the lines between all three lines constantly (even though you can't see the ball in the headset obviously and the lines between the left right controllers to the headset are clipped, which is fine...), but I can only see one line at a time in the reflection, either the line between the head and left controller or the line between the head and the right controller. For example, if I move the left controller, the line between the head and the left controller in the reflection is working, while the other disappear in the reflection. Also, the line between the left and right controllers never appear in the reflection. Edit 2 Add another image to explain what I want vs what I have now
0
How can I avoid tight script coupling in Unity? Some time ago I started working with Unity and I still struggle with the issue of tightly coupled scripts. How can I structure my code to avoid this problem? For example I want to have health and death systems in separate scripts. I also want to have different interchangeable walking scripts that allow me to change the way the player character is moved (physics based, inertial controls like in Mario versus tight, twitchy controls like in Super Meat Boy). The Health script needs to hold a reference to the Death script, so that it can trigger the Die() method when the players health reaches 0. The Death script should hold some reference to the walking script used, to disable walking on death (I'm tired of zombies). I would normally create interfaces, like IWalking, IHealth and IDeath, so that I can change these elements at a whim without breaking the rest of my code. I would have them set up by a separate script on the player object, say PlayerScriptDependancyInjector. Maybe that script would have public IWalking, IHealth and IDeath attributes, so that the dependencies can be set by the level designer from the inspector by dragging and dropping appropriate scripts. That would allow me to simply add behaviors to game objects easily and not worry about hard coded dependencies. The problem in Unity The problem is that in Unity I can't expose interfaces in the inspector, and if I write my own inspectors, the references wont get serialized, and it's a lot of unnecessary work. That's why I'm left with writing tightly coupled code. My Death script exposes a reference to an InertiveWalking script. But if I decide I want the player character to control tightly, I cant just drag and drop the TightWalking script, I need to change the Death script. That sucks. I can deal with it, but my soul cries every time I do something like this. Whats the preferred alternative to interfaces in Unity? How do I fix this problem? I found this, but it tells me what I already know, and it does not tell me how to do that in Unity! This too discusses what should be done, not how, it does not address the issue of tight coupling between scripts. All in all I feel those are written for people who came to Unity with a game design background who just learn how to code, and there is very little resources on Unity for regular developers. Is there any standard way to structure your code in Unity, or do I have to figure out my own method?
0
How to make a class diagram and data model of a Unity3D game? I'm developing a 3D platformer video game on Unity3D and I've been asked to present its UML class diagram and data model. If I'm not mistaken Unity uses an entity component system, which necessarily doesn't use heritage. How would a class diagram from a Unity game look like, in that case? Also, I've been taught that usually data model refers to entity relationship models that represent a database. In the case my game doesn't use a database, how could I diagram the way the player's data is store on the game? I'm storing the player progress on a file in the user's computer.
0
Instantiate works fine in Editor and does not work after building game Here is the situation, In my project everything works fine. After I build the game for windows, the prefab does not instantiate. I don't know which part I missed. This is how I load the prefab from Resources folder private void Awake() areaButtonPrefab Resources.Load lt GameObject gt ( quot Prefabs AreaButton1 quot ) And this is how I instantiate prefab for each data in a List public void SetAreaToUI() foreach (var j in areaList) cloneItem Instantiate(areaButtonPrefab, originalRect.position, new Quaternion(0, 0, 0, 0), rect) TMP Text text cloneItem.GetComponentInChildren lt TMP Text gt () AreaButtonData buttData cloneItem.GetComponent lt AreaButtonData gt () buttData.area j text.text j.areaName cloneItem.SetActive(true) cloneItems.Add(cloneItem)
0
Unity Dropdown Stays Stuck Open As can be seen in the following video https youtu.be zb3uMUqub00 The dropdown stays stuck open when Unity launches the game. This happens even with a non modified dropdown that is plopped as a new UI object inside the canvas. I tried a blank project, and the issue does not reproduce. I tried in a blank project, and the dropdown works. I tried researching a solution, but not too sure how to find one with this problem. Maybe someone here will have an idea or two. The repo can be downloaded at https github.com DenisLabrecque Warglobe if desired.
0
How to get past Visual Studio "Setup Error" for Unity development? When I launch Visual Studio from Unity on my laptop, I get the following error Setup Error The setup for this installation of Visual Studio is not complete. Please run the Visual Studio Installer again to correct the issue. As instructed, I've tried reinstalling Visual Studio multiple times, or using the quot repair quot option, but nothing has resolved the error. How can I fix this?
0
Player wont rotate properly So Small problem. I'm able to rotate my camera around my player AND rotate the player when the camera moves around it, but the controls don't seem to move with it. Example W moves forward. If I look right then W should move forward in that direction. It doesn't, instead it will go left (the forward as it was before). SerializeField GameObject GameCamera private void PlayerRotateWithCamera() Quaternion CharacterRotation GameCamera.transform.rotation transform.rotation CharacterRotation private void FixedUpdate() PlayerRotateWithCamera() MovePlayer() I only think the player is rotating cause it looks like it is, but if you look at the move tool the axis dont seem to move with the Player Just in case my movement isn't getting along with the rotation private void MovePlayer() moveHorizontal Input.GetAxis("Horizontal") moveVertical Input.GetAxis("Vertical") more realistic ball movement Vector3 movement new Vector3(moveHorizontal, 0.0f, moveVertical) rb.AddForce(movement moveSpeed) I also have Tool handle rotation set to global because it's a ball, and well, those axis obvious go crazy while rolling around. Any help at all would really be appreciated!
0
Can I set a texture as the wallpaper of an iOS device? I have a game in Unity which creates drawings. I need to have a button which sets the drawing as the wallpaper (with permission from the user of course). Is it possible?
0
Limit buttontext to one line in Unity? I have many buttons in my game. There are different texts on them every time. But some texts are too long and get split up into two different lines. Is there any way I can fix this without resizing the button. How do I limit the button to one line. p.s I do have best fit on and need it.
0
Which is better practice in Unity? GetComponent() or making the variable public? There are two main ways I am aware of to modify an attached component. Say, the component attached to an object is of type Animator and the name is animator. So, in the script, I can write private Animator animator and then call the function animator GetComponent lt Animator gt () Or, I can define the variable as public public Animator animator and then, drag amp drop in the Unity UI. Which one is the better practice?
0
Inherited property in derived class reference only base class Context I am developing a game in Unity, and wanted to make a Game Manager. Like many examples out there, it uses a Singletron design pattern. But i have several other Managers, all using Singletron pattern, so i decided to make a Singletron base class and make all the managers derive from it. When trying to access the Instance property declared in Base Class within one method in Game Manager derived class, the Instance property refers to the Singletron base class, which is expected. But it s not the behaviour i need. I have tried to look for alternatives, but everytime i found a possible solution, i have to declare the member variables properties in the derived class, and there would be no need to a Singletron Base Class. I have also looked for generic alternatives (Singletron lt T ) but it was not clear how to use these without the need of another script calling it, which would be nonsense since the Game Manager should be the object to manage the game. I could use something like a root game object to creat the managers is instances, but it feels like a ugly and inelegant solution. The managers are all coded, and this refactor would improve code maintenance, in future. Code from Singletron Base Class public abstract class Singletron MonoBehaviour public static Singletron Instance get protected set protected virtual void Awake () if (Instance null) Instance this else Destroy (gameObject) DontDestroyOnLoad (gameObject) Pertinent code from Game Manager Derived Class public class GameManager Singletron public List lt GameObject gt gameObjectsList public static void SomeMethod() foreach (GameObject go in Instance.gameObjectsList) go.DoSomething() Question What can i do inside Singletron Base Class to make the Instance.gameObjectList refers the actual class (in example, Game Manager Derived Class) so that i could use the gameObjectsList? Should i cast it to the pertinent manager inside the method (which seens like an inneficient option)? Thanks in advance! Edit Looking into design patterns page in wikipedia, i found another design pattern related to singletron. In my case, each manager follows the singletron pattern, but its somewhat equivalent to my singletron base class following a Multiton Pattern
0
How to apply forces to character with gamepad in Unity? I've been following Brackey's tutorial on this, see the excerpt from my code below. In his tutorial it only teaches quot transform.Translate quot , how do I use this gamepad input system tool to add forces to the character to make them move instead? So I can have jump physics, and when they're in space they'll keep the momentum. NewControls controls Vector2 move Vector2 rotate private void Awake() controls new NewControls() controls.Gameplay.Jump.performed ctx gt Jump() controls.Gameplay.Walk.performed ctx gt move ctx.ReadValue lt Vector2 gt () controls.Gameplay.Walk.canceled ctx gt move Vector2.zero controls.Gameplay.Rotate.performed ctx gt rotate ctx.ReadValue lt Vector2 gt () controls.Gameplay.Rotate.canceled ctx gt rotate Vector2.zero private void Update() Vector2 m new Vector2(move.y, move.x) Time.deltaTime transform.Translate(m, Space.Self) Vector2 r new Vector2(rotate.y, rotate.x) 100f Time.deltaTime transform.Rotate(r, Space.Self) To move with rigidbody controls, you have to use things like forward or left but I want one joystick to control the forward, backwards, and side to side movements. I don t know how to use the joystick input for moving in all those directions. The tutorials have them as separate arrow keys does anyone have some sample code, or a tutorial to point me to, or just some explanation? it would be much appreciated.
0
Ability Skill Data and Method Structure (C , Unity3D) So I've come to design my game which players will be having a unique set of skill or ability to come with. I can store skill name, mana cost, cooldown, etc in database which each skill have in common, but as we gamer know, a skill is unique not just by its attributes, like the sequence of movement, the object will be instantiate in the world, it's just that very unique. So the question is, where do I put this "unique", the skill sequences? Do I make skill1.cs, skill2.sc for every single skill? xml for sequence then make script to read and define myXml? For example, in a game, the effect of each card is very unique for example card1 allow player to deal damage and draw card, card2 just deal damage, card3 deal damage to enemy and then draw a card, and so on, where and how they store this sequences or method of each card effect?
0
Why does duplicating my object cause its vertex animation shader to distort it? I used a vertex shader (based on this example) to animate a flag waving. When I have a single flag in my scene, it works correctly. When I duplicate the flag, all of the copies become wildly distorted after I hit play. Here is the shader code I'm using Shader "Custom Flag" Properties MainTex ("Albedo (RGB)", 2D) "white" Speed ("Speed", Range(0, 5.0)) 1 Frequency ("Frequency", Range(0, 1.3)) 1 Amplitude ("Amplitude", Range(0, 5.0)) 1 SubShader Tags "RenderType" "Opaque" Cull off Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" sampler2D MainTex float4 MainTex ST struct v2f float4 pos SV POSITION float2 uv TEXCOORD0 float Speed float Frequency float Amplitude v2f vert(appdata base v) v2f o v.vertex.y cos((v.vertex.x Time.y Speed) Frequency) Amplitude (v.vertex.x 5) o.pos mul(UNITY MATRIX MVP, v.vertex) o.uv TRANSFORM TEX(v.texcoord, MainTex) return o fixed4 frag(v2f i) SV Target return tex2D( MainTex, i.uv) ENDCG FallBack "Diffuse" How can I make this work with multiple flags using the same material? Should I use a new material instance for each object like this? It doesn't seem optimal material new Material (Shader) Create new material material.SetFloat (" Speed", Speed) material.SetFloat (" Frequency", Frequency) material.SetFloat (" Amplitude", Amplitude) material.SetTexture (" MainTex", MainTex) flagObj.GetComponent lt MeshRenderer gt ().sharedMaterial material Set values
0
How can I create "events" that are called in scripts without requiring subscriptions? I am creating an editor extension that includes an API for developers to use. It also includes events like (for example) "OnHealthChanged." The problem is that events I have stumbled upon would require a user to subscribe to them, which is not what I actually want. I want developers simply type in the event handler in their script, and it would just work. For example, I want a programmer to write a function "OnHealthChanged" in their own script. When the health changes, their code runs. void OnHealthChanged() code that is going to run when health changes Any idea where can I look? I want to create something like "OnCollisionEnter()" event in Unity, which runs code every time a game object collides with another game object. Hope it makes sense.
0
UGUI scripts stop my project from building Unity 2019.2.21 I am trying to build out my project to Android and I am getting the following error messages H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Toggle.cs(121,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core DefaultControls.cs(152,13) error CS0103 The name 'Undo' does not exist in the current context H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core GraphicRebuildTracker.cs(24,32) error CS0117 'CanvasRenderer' does not contain a definition for 'onRequestRebuild' H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime EventSystem InputModules StandaloneInputModule.cs(159,25) error CS0234 The type or namespace name 'EditorApplication' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Slider.cs(380,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Scrollbar.cs(168,18) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core Selectable.cs(771,48) error CS0234 The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) H unity versions 2019.2.21f1 Editor Data Resources PackageManager BuiltInPackages com.unity.ugui Runtime UI Core InputField.cs(2458,43) error CS0234 The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?) I tried updating Unity(from 2019.2.12 to current). Deleting some csproj files, and different settings in the Project settings Player. The problematic code is in an if UNITY EDITOR statement, and not meant to execute at all on builds, I guess. if UNITY EDITOR protected override void OnValidate() base.OnValidate() if (!UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this) amp amp !Application.isPlaying) CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this) endif if UNITY EDITOR
0
Change animation speed through the editor in Unity How can I change the speed of the animation through the editor if I have the following animation structure? I would like Adult1 walk to play faster.
0
Detect collision without reaction Okay, so this has been bugging me for quite some time now. I'm making an old school platformer type of game in 2.5D, I want objects to pass through each other, but I still want a collision to be detected. If the player gets hit by an enemy, I just want to detect a collision for receiving damage to the player, I don't want the player to move on impact, and I just want the enemy to continue moving where he was heading. I'm using rigidbodies and box colliders on my objects. First I thought using triggers combined with ignoring layers was the solution, but apparently trigger events aren't called when ignoring layers. I still want to be able to use AddForce and stuff for moving objects. Is there someway I can still utilize Unity's OnCollision... OnTrigger... Or other... for just detecting a collision and having no impact movement added when a collision occurs? Have a nice day!
0
Unity, depth behind a transparent object Is there a way to know how far away is any object behind a transparent object in shader? Like making water fully transparent when close to shore.
0
convert clock input into 24 hour format I have stuck in a logical problem I have a third party package of DayNight. It takes hours input(24 hour format) to show dayNight effects in scene My code is to transform 12 hours clock cycle into 24 hours is if (todsky.Cycle.Hour gt 0 amp amp todsky.Cycle.Hour lt 11.97) Debug.LogError("1st") var degree 360 hourniddle.transform.eulerAngles.z var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes ConvertMinutesToHours(degreeToMintues) else if (todsky.Cycle.Hour gt 11.97 amp amp todsky.Cycle.Hour lt 23.97) Debug.LogError("2ndt") var degree 360 hourniddle.transform.eulerAngles.z as rotation is anti clock getting rever degree var degreeToMintues degree 2 multiply each degree with 2 to get correct minutes var MintuestTo24HoursMintueCoverstion 720 degreeToMintues add 720 mintues into current minute in order to get 24 hour format ConvertMinutesToHours(MintuestTo24HoursMintueCoverstion) void ConvertMinutesToHours(float mintues) result TimeSpan.FromMinutes(mintues) Debug.LogWarning(result.Hours " " result.TotalHours " " result.Minutes " " result.TotalMinutes) todsky.Cycle.Hour (float) result.TotalHours Debug.LogWarning("setted hours " todsky.Cycle.Hour) But it is not working correctly . have made a clock GUI(360 degree) and as you know it only show 12 digits format not 24. I am getting clock needle movement which can be change through mouse drag. Needle z position up to 320 degree which means one degree is equal to 2 minutes and i am taking it as input from GUI. I write below code to integrate my clock needle with my DayNight package in order to integrate GUI with package and passing hour parameter into the package but it not working correctly. Problem is that else condition is skipping.
0
How do I calculate UV space from world space in the fragment shader? In my vertex shader I have calculated the world space o.worldSpacePosition mul(unity ObjectToWorld, vertIn.vertex) How do I convert that world space into uv space coordinates in my fragment shader? float4 frag(VertexShaderOutput i) COLOR SV Target0 float2 uv i.worldSpacePosition ??? I have tried float4 mvp UNITY MATRIX MVP 3 float2 uv mvp.xy p.w but that does not appear to work as the uv is always (0, 0) EDIT I am drawing a mesh on the screen in world space coordinates which needs to lookup into a screen space texture The way I am currently solving this is by calculating the uvs for each vertex of the mesh using the following calculation camera.WorldToViewportPoint(vertices i ) Unity uses normalised coordinates for the viewport 0,1 rather than 1,1 . This works fine but I wasn't sure of the behaviour if part of the polygon is off the screen. I presume I should clamp the uv? Screen space might not be the correct term for the uv coordinates. Perhaps texture space is a more appropriate term?
0
How can I play an animation as long as the player is on the pressure pad? I'm making a 2D platformer with Unity. Recently, I implemented a pressure pad system. Basically, when the player triggers the pad, a door near there should be opened. The system works properly but the only problem is when the player stays on the pad, the OpenWhenOn animation (an idle animation that is for the door opening) is not playing. I want to make this keep playing as long as the player is on the pad and if it exits the trigger, the DoorClosing animation should be played. I wrote this code mainly for playing the animation but it doesn't work and I get Null Reference error all the time. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.Events public class PressurePad MonoBehaviour private Animator anim public UnityEvent OnActivate public UnityEvent OnDeactivate public GameObject door public float deactivationDelay 2f int objectsInContact Coroutine waitingToDeactivate IEnumerator Timer() yield return new WaitForSeconds(deactivationDelay) Tell our listeners we're switched OFF. if (OnDeactivate ! null) OnDeactivate.Invoke() Return to ready to activate state waitingToDeactivate null void OnTriggerEnter2D(Collider2D other) if (other.CompareTag( quot Player quot )) anim.Play( quot OpenWhenOn quot ) door.GetComponent lt Animator gt ().Play( quot OpenWhenOn quot ) objectsInContact Pressure pad pressed. if (objectsInContact 1) if (waitingToDeactivate ! null) Cancel deactivation timer. StopCoroutine(waitingToDeactivate) waitingToDeactivate null else if (OnActivate ! null) Tell our listeners we're switched ON. OnActivate.Invoke() void OnTriggerExit2D(Collider2D other) objectsInContact Pressure pad released. if (objectsInContact 0) Start a delay before telling anyone. waitingToDeactivate StartCoroutine(Timer()) This is my Animator Controller. HasExitTime is disabled for all the transitions. The condition for the transition between OpenWhenOn and DoorClosing is set to false.
0
Refresh UI after changing source code I was trying following things. GameManager bool gameHasEnded false public GameObject completeLevelUI public void CompleteLevel() completeLevelUI.SetActive(true) public void EndGame() if(gameHasEnded false) gameHasEnded true Invoke( quot Restart quot ,2f) void Restart() SceneManager.LoadScene(SceneManager.GetActiveScene().name) EndTrigger public GameManager gameManager void OnTriggerEnter() gameManager.CompleteLevel() I get a log in the console quot END quot . Earlier I was using Console.Log( quot END quot ) on CompleteLevel(), but I changed that source code. The old code seems to be working and not the new one. It's like Unity couldn't refresh that source code. (And I am sure that I have successfully saved the C file.) using System.Collections using System.Collections.Generic using UnityEngine public class PlayerCollision MonoBehaviour public PlayerMovement movement void OnCollisionEnter(Collision collisionInfo) Debug.Log(collisionInfo.collider.name) if (collisionInfo.collider.tag quot obstacle quot ) movement.enabled false FindObjectOfType lt GameManager gt ().EndGame()
0
Smoothly resize minimap camera rect width and height I have an orthographic camera that is working as a mini map. Now I want to make it resizeable using mouse drag. I have applied some UI beside my minimap camera rect and those UI resizing perfectly with this code. But I have no clue that how to resize my camera rect with mouse drag void Awake() rectTransform transform.GetComponent lt RectTransform gt () public void OnPointerDown(PointerEventData data) if (!resizePanelFeatureActive) return rectTransform.SetAsLastSibling() RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out previousPointerPosition) public void OnDrag(PointerEventData data) if (!resizePanelFeatureActive) return if (rectTransform null) return Vector2 sizeDelta rectTransform.sizeDelta RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out currentPointerPosition) Vector2 resizeValue currentPointerPosition previousPointerPosition sizeDelta new Vector2(resizeValue.x, resizeValue.y) sizeDelta new Vector2( Mathf.Clamp(sizeDelta.x, minSize.x, maxSize.x), Mathf.Clamp(sizeDelta.y, minSize.y, maxSize.y) ) rectTransform.sizeDelta sizeDelta previousPointerPosition currentPointerPosition
0
Blender Unity Import Animation Failing by Overlapping Mesh Objects I'm new to both Unity and Blender. I created this penguin 3d model, rigged it up and animated it in Blender and all looked good. When I imported it into Unity, I noticed that this idle animation did not appear to be working correctly. As the body moves, the body mesh overlaps the belly mesh and covers a portion of it. This is not the case when viewing the animation from blender 2.9. The belly uses a shrinkwrap modifier with the body as a target. Is this a problem with Unity import, or how I modeled this penguin in Blender? Can anyone see what I have done wrong here? Any help is much appreciated!
0
Unity Opacity over Distance with Surface Shaders I want to tweak the alpha value based on the distance to the camera. But I see no way of passing the vertex position on to the surface function using surface shaders. Not a problem with frag shader. It's for fading out vegetation and creating LOD systems. Shader quot asdf quot SubShader CGPROGRAM pragma surface surf StandardSpecular alphatest Cutoff addshadow vertex vert struct v2f float4 pos TEXCOORD1 struct Input float2 uv Maintex v2f vert (inout appdata base v) v2f o o.pos mul(unity ObjectToWorld, v.vertex) return o void surf (Input IN, inout SurfaceOutputStandardSpecular o) Need vertex or pixel distance here float dist length(v2f.pos.xyz WorldSpaceCameraPos.xyz) o.Alpha saturate(50 dist) ENDCG
0
creating a trigger to play multiple animations at once I need a "button" like trigger. The player would walk within the invisible cube that is the trigger, once the player is in the trigger (and only in the trigger) they would be able to press 'e' on their keyboard which will cause the animations to play at once. After the animation plays, the screen fades to black and loads the next scene. I'm still incredibly new to Unity so a brief summary of the code you provide would be much appreciated! (but not at all demanded!) Personally I'm a lot more comfortable with C so if the code can be in that, it would really help. Thank you!
0
How to sample from six cubemap images for a skybox in Shader Graph? I'm trying to update a skybox shader to URP and reimplement it in Shader Graph. The shader code itself is pretty straightforward, but I don't know enough about Shader Graph yet to set up the basic skybox. It's a standard cubemap skybox made up of six textures for x, x, y, y, z, and z. Trying to Google different variants of "unity shader graph cubemap skybox" turns up tons of noise and nothing actually useful that I can see. Does anyone know what the basic node setup is I would need to input six images and output a skybox?
0
Why the while loop is not pausing the coroutine? I'm trying to find a way to pause the game the whole game. timeScale 0f is not working on coroutines. I have this script that pause the game on escape key using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class BackToMainMenu MonoBehaviour public static bool gamepaused false private void Update() if (Input.GetKeyDown(KeyCode.Escape)) gamepaused true Time.timeScale 0f And a script with a coroutine using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.PostProcessing public class DepthOfField MonoBehaviour public UnityEngine.GameObject player public PostProcessingProfile postProcessingProfile public bool dephOfFieldFinished false public LockSystem playerLockMode private Animator playerAnimator private float clipLength private Coroutine depthOfFieldRoutineRef void Start() if (depthOfFieldRoutineRef ! null) StopCoroutine(depthOfFieldRoutineRef) playerAnimator player.GetComponent lt Animator gt () AnimationClip clips playerAnimator.runtimeAnimatorController.animationClips foreach (AnimationClip clip in clips) clipLength clip.length var depthOfField postProcessingProfile.depthOfField.settings depthOfField.focalLength 300 StartCoroutine(changeValueOverTime(depthOfField.focalLength, 1, clipLength)) postProcessingProfile.depthOfField.settings depthOfField IEnumerator changeValueOverTime(float fromVal, float toVal, float duration) while(BackToMainMenu.gamepaused) yield return null playerLockMode.PlayerLockState(true, true) float counter 0f while (counter lt duration) var dof postProcessingProfile.depthOfField.settings if (Time.timeScale 0) counter Time.unscaledDeltaTime else counter Time.deltaTime float val Mathf.Lerp(fromVal, toVal, counter duration) dof.focalLength val postProcessingProfile.depthOfField.settings dof yield return null playerAnimator.enabled false dephOfFieldFinished true depthOfFieldRoutineRef null But when I hit the escape key the freeze for a second or two but then the blurry effect in this script is keep on going then it also keep on running the game after this script part. It seems that the timeScale is not pausing the game at all but only for few seconds if at all. Or pausing only some stuff. What I want is to pause the whole game. Maybe I should use a game state somehow? I don't want to disable enable the gameobjects in the hierarchy. I checked again now. For example the player I can't move it with the keys but I can rotate the player looking around with the mouse while in pause mode. But other things are paused like other npc's I have they stopped moving(Not using animation). So some stuff is paused but some stuff not.
0
My GUI stopped working? Okay I bought this asset online so I would like not to show the whole script. The problem is this asset stopped working when I updated from unity 5.0 to 5.1.2. The script is for a controller GUI interface but it seems to be giving me an error NullReferenceException Object reference not set to an instance of an object UnityEngine.UI.Selectable.Select () on this line of code selectedOject.GetComponent lt Button gt ().Select () so there is a null reference and its no longer recognizing the child objects as buttons is what I'm assuming if you want to have a better look at his set up he has a short video On youtube HERE I would like to continue to use this script and continue updating Unity.
0
Disable audio listener warnings? "There are no audio listeners...", "There are 2 audio listeners..." The scene I'm working in constantly spams the message There are no audio listeners in the scene. Please ensure there is always one audio listener in the scene. If I add a dummy camera with an Audio Listener, I then get There are 2 audio listeners in the scene. Please ensure there is always exactly one audio listener in the scene. I know this happens because our camera is created programmatically, with an audio listener. I also realize this will not affect the non development build in any way. Is it possible to disable these warnings completely?
0
How to add high score? I wanted to add a high score to my game but I don't know how I already tried to find some videos for it but I just can't find the right one. I already have a scoreUI on my game I just wanted to add a high score. Here is my UIManager's script which consists of different functions including the score system. using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.UI using UnityEngine.SceneManagement public class uiManager MonoBehaviour public Button buttons public Text scoreText int score bool gameOver Use this for initialization void Start () gameOver false score 0 InvokeRepeating("scoreUpdate", 0.5f, 0.25f) Update is called once per frame void Update () scoreText.text "" score void scoreUpdate() if (gameOver false) score 1 public void gameOverActivated() gameOver true foreach(Button button in buttons) button.gameObject.SetActive(true) public void Play() SceneManager.LoadScene("level1") public void Menu() SceneManager.LoadScene("Menu") public void Retry() SceneManager.LoadScene(SceneManager.GetActiveScene().name) public void Pause() if (Time.timeScale 1) Time.timeScale 0 else if (Time.timeScale 0) Time.timeScale 1 I got the score system from Charger Games. Here is the link to the Video and here is what my game looks like
0
Detect collision from a particular side I'm making a platform sidescrolling game. All I want to do is to detect if my character is on the floor function OnCollisionStay (col Collision) if(col.gameObject.tag "Floor") onFloor true else onFloor false function OnCollisionExit (col Collision) onFloor false But I know this isn't the accurate way. If I hit a cube with a "floor" tag, in the air (no matter if with the character's feet or head) I would be able to jump. Is there a way to use the same box collision to detect if I'm touching something from a specific side?
0
How to do pixel perfect movement with Unity3D? How would you be able to make sprites move pixel by pixel in Unity3D? I've tried the following things. int x (int) transform.position.x int x Mathf.FloorToInt(transform.position.x) int x Mathf.RoundToInt(transform.position.x) I don't know what else to try Because I'm making an SNES looking game, and when things move, there is very bad pixel crawl in the sprites.
0
Level Selector with possible future levels? Unity I have a level select screen which is a simple grid layout of my levels. The level data comes from a scriptable object for each level. The problem I have is what is the best method for populating the grid of levels that use the scriptable object and is able to add more levels to the grid layout if let's say I add an asset bundle in the future? My thought was that I use a levelDB which holds a list of all of the scriptable objects. Then when an asset bundle is used then it adds the content to the levelDB. The UI would then just use this levelDB to populate the screen. NOTE I have very little to no knowledge of how asset bundles work and what you can, and cannot do with them.
0
unity graphics initialization Pretty short question, when I load unity, I get this error Is this fixable with driver downloads, or do I need a new PC? if so, how do I find out my computer's default built in graphics driver?
0
Gfx.WaitForPresent performance issue I am making a 2D mobile game and it runs really well (60 fps) on my phone. However, in some cases the performance goes down drastically to the point where it runs at 20 fps or even less. It happens at random times so I can't pinpoint what is causing this. During the performance decrease Gfx.WaitForPresent appears in my profiler which eats a lot of power. I am aware that this might be because of Vsync being turned on, but I have it disabled, along with shadows, AA and everything else that absolutely kills mobile performance. What else can be the problem? My game relies heavily on good performance for gameplay so this needs to be resolved ASAP. Edit I also noticed that the GPU stays at 0 ms which is really odd as well.
0
Why is perlin noise generating flat terrain in Unity? I am trying to generate terrain using perlin noise however the terrain being generated is a plateau. Here is the code that I'm using var xlength 65.0 var ylength 65.0 var scale 4.1f var heights new float xlength, ylength function Start () for (var i 0 i lt xlength i ) for (var j 0 j lt ylength j ) heights i,j Mathf.PerlinNoise(Time.time i xlength scale 1000,Time.time j ylength scale 1000) i j gameObject.GetComponent(Terrain).terrainData.SetHeights(0,0,heights) What am I doing wrong here?
0
Unity immediate mode I have some existing C 2D game code that draws using immediate mode (i.e., each frame is drawn bottom up one sprite at a time by my game code not using a scene graph or other retained mode concepts). I'm wondering if I can port this code to Unity without having to rework the game code to operate in terms of retained mode (adding objects to a scene, removing objects, etc.). I have read that Unity has an immediate mode GUI option. But in my case I want to use this for the game sprites themselves, not just the UI elements. I realize that for a 2D game there isn't a big difference between UI elements and game sprites. But I need to be able to do things like rotation and render to texture, so I wasn't sure if I'd run into trouble "misusing" the immediate mode GUI mechanism to handle the whole game. Alternatively, does Unity have a more general immediate mode option? (I did search for it and didn't see anything aside from the immediate mode GUI stuff.)
0
How can I economically check if a UI DropDown is open or closed? I've recently come across a problem with the UI DropDown component. I would like to resize other UI components depending on whether the dropdown is opened or closed. Unfortunately, the dropdown dynamically creates and destroys its own "Dropdown List" component, making it difficult to check whether it is open or not, without having to check with Update or FixedUpdate (both being expensive on the performance). I have tried to implement a solution with event handlers, but it seems as if the even handler triggers before the "Dropdown List" is created. Thus this does not work. Am I simply missing an easy way to check whether the dropdown is open or closed?
0
FindWithTag returning a game object from "Preview Scene". What is that and why is it not detecting from the active scene? I have a script that fetches a transform using GameObject.FindWithTag("Tag").GetComponent lt Transform gt () . This has worked fine for a long time, but now it retrieves a transform from a preview scene(whatever that is). How do I prevent it from looking at preview scene?
0
Unity question on OnTriggerStay() function I'm currently working on a soccer game.I have a script for the ball that whenever the ball collides as trigger with the goal line,the ball will return to the middle point.But seems like the ball doesn't Lerp() back,afterward I tried to check if Unity counts it as collide or not with Debug.Log("Goal") but nothing is logged to the console.Please help me with that.Here is the first code public var smooth float private var newPosition Vector3 function Awake () newPosition transform.position function OnTriggerStay (ball Collider) var positionA Vector3 new Vector3(0, 0.3, 0) newPosition positionA transform.position Vector3.Lerp(transform.position, newPosition, smooth Time.deltaTime) Here is the second code (after changing to Debug.Log()) function OnTriggerStay (ball Collider) Debug.Log("Goal")
0
How can I parent an object whilst animating? Much like in Blender where you can parent an object to another, or the Armature, is it possible to parent an object to another, so when animating, the child object moves with the parent? I've tried dropping the object I want influenced onto the character's parent object in the hierarchy and accessed it via the Animation tab. I added the object as a property and adjusted it's position, but the results have been pretty mixed. How can I have an object automatically follow the animation without manually adjusting its curves for each frame?
0
How to make a 2D neon like trail effect in Unity Recently I've been toying around with neon ish effects for a game I'm making and wanted to share my results with you. If you guys have any other methods of achieving this result, please be sure to share.
0
Is it possible to make a randomly rotating terrain texture painting brush in Unity? I wanted to make a terrain in unity with a dirt texture painted onto the original grass texture to make a path, but when I tried, the dirt (and grass) looked repetitive and full of patterns. My question is, is there any way I can make a texture's tiles randomly rotate when being applied or painted onto an object?
0
Changing distance after some time on OnGUI Unity Though I am using IEnumerator to calculate the distance travelled value, the distance is updated very frequently, how can I change that? and why exactly increasing the time in WaitForSeconds function not changing the behaviour? void OnGUI () GUI.contentColor Color.black GUI.Label (new Rect (40, 40, 140, 40), "Speed " speed, "color") StartCoroutine (distancetravelled ()) GUI.Label (new Rect (40, 100, 100, 140), "Dist " Mathf.RoundToInt (distance 1000) " Kms", "color") IEnumerator distancetravelled () timeInHours (Time.smoothDeltaTime 60) 60 if(PlayerControl.collision ! true) distance speed timeInHours yield return new WaitForSeconds (60)
0
RaycastHit2D.point is acting weird when used with circlecast2d When I make circleCast2d intersects with another circle collider, I get a RaycastHit2D.point that doesn't point at the tip of the collision as it states in the documentation. Instead it always points at the centre of the intersected junction or pointC as shown in the figure below. I checked this numerous times with different values to make sure the error was not from my end. Is this intended? If so is there another way where I can actually find the closest point from collider(B) to the centre of collider(A) which corresponds to point(D) in the figure? This is a picture of what looks like A circleCast B collided object C where RaycastHit2D.point is pointing at D where I'd like it to point.
0
Unity Change the type of a Texture2D to "Normal map" through script I am making procedural terrains through c script, and while I achieve to produce a texture, a heightmap and a normalmap to Texture2D, it seems they are not being applied correctly to the material. the texture (albedo) is applied the noise map is applied (but as a "default" texture, I think?) the heightmap is not even selected The trick I currently use is to also save the Texture2D to files. After generation I manually affect the file normalMap and it goes fine. But you'll understand this is not satisfactory, I want the script to set the normal map correctly. I suspect this is because the file's texture type is force to normal map. But I cannot see how I can change the type of an in memory Texture2D through code. Researches gave nothing fitting my concerns, any help will be appreciated. Thanks ) EDIT I tricked by passing a pre made normal map as parameter, to use instead of the one I generate. Guess what? It works instantly.
0
Add Rigidbody and MeshCollider at runtime is it a bad practice? Good day. To simulate an explosion of a vheicle, I decided to do this When I need to explode veichle , at runtime, i add rigidibody for every single part of veichle (5 10 part door, wheel, hood etc), and collider (mesh). I detach them from parent I apply an AddExplosionForce to every single part This cause a big lag in my game, so I'm supposing this is not the efficent way. The other way could be to add Rigidbody and Collider in my prefab, with Rigidbody.gravity false, and isKinematic true, then enabling after explosion, but also this is not good for performance. Do you have some suggestions to achive my scope, considering that I could have a lot (5 10) enemy veichles at time on my scene ? Thanks
0
UI Button sprite not changing on click I'm trying to make the sprite of my button change on click, and i used this script to achieve it public Button botonPlayMaster i assign the button on the inspector Image imagenBoton public Sprite botonPlay same with the sprites, i send them on the inspector public Sprite botonStop Start is called before the first frame update void Start() imagenBoton botonPlayMaster.GetComponent lt Image gt () i get the component from the button public void cambiaSprite () if (imagenBoton.sprite botonPlay) imagenBoton.sprite botonStop else imagenBoton.sprite botonPlay This script is attached to a GameManager GameObject. I assign the sprites and the GameObject Button on the inspector, and then send the GameManager object to the OnClick() function on the button's inspector and select the cambiaSprite() function. But when i click, nothing happens. Any help would be appreciated. Thanks!
0
Code Logic's execution with respect to time Events I have to show complete 24 hours cycle in Unity3d Scene. Where different kind of task will be executed in different Times. Suppose at 2pm I have to move a car, at 6pm An Aeroplane will land on airport at 07 07pm I have to open the door of Market's Buildings and so on different task works execution at different timing. Now, I have some basic animation e.g., car, Aeroplane and door etc.,. Now I am confuse that how to play and stop my animation according to the time. And time can also be changed manually using GUI. If currently 6pm (animation working) then user can switch to 8am to view 8am time's animation (or code execution). And User can also fast the timing to view complete hours in a single minutes or in an hour. I can use if else in Update Events but I guess this is not the right way to do and will be very difficult if I require to show significant number of works in different time duration (which means significant number of if else statements). Just like below void Update() if(time 1) logic if(time 2) logic if(time 3) logic ... so on, tedious way ... and also not possible if time require between the hours, suppose 06 06pm What to do ? How to handle this?
0
Is it cheaper to let each tile have its own collision? I'm just now playing around with Tiled, and I think this is the way I'm going to go to create tilesets for my game maps, but I'm curious about the cost (memory CPU) difference between setting a collision for a specific tile so that Tiled creates them all individually versus manually drawing collision polys around larger sections by hand. For instance By Tile Manual There are fewer polygons in the manual draw (4), and it's not terribly difficult to create them, but is there a benefit one way or the other?
0
Bubble Text appears issue? I'm trying to make a dialogue between characters using bubbles witth text. But the text appears not clear to player. The Cam is far from the canvas 13.5f. What to do fix it ?
0
Move ball based on direction of force? I'm trying to make a ball that will move in the direction I push it from, and later pull it to me based on where the player is standing. using UnityEngine using System.Collections public class BallForce MonoBehaviour public float thrust public Rigidbody rb Use this for initialization void Start () rb GetComponent lt Rigidbody gt () Update is called once per frame void Update () if (Input.GetMouseButton (0)) rb.AddForce (transform.forward thrust) This seems to work, but I'm not sure how I get it to move based on the position of the player. How would I do this?
0
Old tv effect in shader graph I am trying to use Unity's shader graph to create this old tv effect I thought about using a noise node, and somehow randomize the noise's seed. Can anyone help me?
0
How do I rotate a gameobject towards a point in world space? I wanted to create a very simply turret. This turret should aim at the point on the screen where the mouse pointer is currently located. I have added a cube to serve as a very simple turret in my scene. To visualize its aiming direction, I'm drawing a ray from it. To rotate the quot turret quot to the mouse pointer position, I have created a script and added it to the quot turret quot gameobject void Update() var mousePos Input.mousePosition mousePos Camera.main.transform.forward 10f Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) transform.LookAt(aim) RaycastHit hit int layerMask 1 lt lt 8 layerMask layerMask Color color if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask)) color Color.green else color Color.red Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) 10000, color) However, there must be something wrong in my code. In this screenshot, I have added a red arrow that points to the position of the mouse pointer The mouse pointer is over that orange tool. However, the turret is rotated towards the floor while it should be rotated upwards to the orange tool. I do believe that my turret is well positioned (the blue arrow points forward) How do I change my code so that it aims correctly, and what is my mistake? I guess the problem is in these 2 lines, but I don't see what's wrong about it mousePos Camera.main.transform.forward 10f Make sure to add some quot depth quot to the screen point var aim Camera.main.ScreenToWorldPoint(mousePos) Thank you. Edit I finally understand what Kevin wanted to tell me. I made a thinking mistake, and really need the Raycast to determine where my Worldspace point actually is. Here is why Even though the Y screen coordinate of the mouse position is just a few pixels different in each game window on the right side, the worldspace point is totally different (as can be seen in the scene view window on the left side). I thought in 2D space, while I should have thought in 3D space.
0
Unity C Changing Button Color? void OnMouseDown () foreach (Button thisButton in buttonArray) thisButton.GetComponent lt SpriteRenderer gt ().color Color.black GetComponent lt SpriteRenderer gt ().color Color.white This code results in whichever button I select changing color to white while the rest are black. However, I am not understanding how this works. How does it know to specifically change ONLY the selected button to white while the rest are black. Seems contradictory to me...
0
How to find the angle of an arc for reflection I am using the following code to calculate points for a circle arc drawn with a Line Renderer. for (int i 0 i lt pts i ) float x radius Mathf.Cos(ang Mathf.Deg2Rad) float y radius Mathf.Sin(ang Mathf.Deg2Rad) arcLine.positionCount i 1 arcLine.SetPosition(i, new Vector2(x, y)) ang (float)totalAngle pts How can I change the angle ang to create a reflected arc along the line P1P2 as in the image below? Please note that totalAngle represents the portion of the circle that is to be drawn between 0 and 360.
0
How can I fix this shadow slicing the mesh on Android? I have a golf ball in my Unity game for Android, which is an icosphere (imported from blender) with a baked normal map. There are 18 tracks located in one level around the (0, 0) coordinate, rotated in different directions. The game uses Distance Shadowmask to create realtime shadows for near objects. In the editor and Windows builds, this works perfectly. On Android, the shadow has a lower resolution, which is fine, but it seems to slice through the ball. It is visible in the following screenshot. If the ball moves, it looks like it passes through several planes casting a shadow. This is heavily depending on the current track the ball is on. In 3 of the 18 tracks, there are very noticeable errors. Some other locations show very small errors. However, those tracks are on seemingly random position. While the heavy errors appear on tracks located mainly in this ( x, z) area, the small errors appear on arbitrary other positions. I already tried changing shadowmap resolution changing the directional light's near plane changing the directional light's bias and normal bias changing the directional light's position and rotation rebaking the ball's normal map using another ball mesh removing the normal map from the material using a different device
0
Syntax error in multi pass Surface Shader I'm trying to make a Surface Shader that uses multiple passes, with two different blending functions for each one, but I get the following error I don't understand Parse error syntax error, unexpected TOK PASS, expecting TOK SETTEXTURE or ' ' at line 28 SubShader ZWrite Off Tags "QUEUE" "Transparent" "IGNOREPROJECTOR" "true" "RenderType" "Transparent" "PreviewType" "Plane" Pass transparency Blend SrcAlpha One CGPROGRAM pragma surface surf Lambert pragma target 3.0 struct Input sampler2D void surf (Input IN, inout SurfaceOutput o) ENDCG Pass alphabend Blend SrcAlpha OneMinusSrcAlpha CGPROGRAM pragma surface surf Lambert pragma target 3.0 sampler2D fixed4 struct Input void surf(Input IN, inout SurfaceOutput o) ENDCG
0
Load the prefab in the array by name in Unity I'm using this line of code to select my level, and currently I have different scenes for each levels. I want to be able to reuse the same scene to change levels as well but I don't know how, here's the line button.GetComponent lt Button gt ().onClick.AddListener(() gt Levels("Level " button.levelText.text)) Since I'm using string to load my scene with the function below void Levels(string value) SceneManager.LoadScene(value) I really wish I could use prefab name instead the scene name and I don't want to have 20 scenes for it. Any help would be appreciated.
0
Trouble with assigning a model's own mesh to a mesh collider in Unity I'm trying to use a mesh collider on the player's avatar, rather than the box collider. I've added the mesh collider to the game object (which also has a rigid body) and selected the "convex" checkbox. However, the player still falls through all geometry, including Unity primitives, terrain, and other models. In the mesh collider's property box, there's a value for "Mesh", which I have set to "None (Mesh)". I was led to believe this defaults to the model's own mesh, but now I'm not certain. If I change the value to something else from the "select mesh" list, like the cube, the collisions work. When I click over to Select Mesh Scene, the list is empty. I'm assuming I need to add the model's mesh to the list, but I can't find any documentation about that.
0
Orthographic Camera Movement inside Rotated Boundary Rectangle Weird Behaviour Unity3d Basically I have an orthographic camera that is looking at a simple square. The camera is sitting above the square and tilted by x 45 and y 45 , so the camera sees the square as a rhombus diamond shape. I want the camera to be moveable within a rectangular boundary that appears to be leveled with the camera, so it would need to be rotated by 45 around the y axis (up vector in Unity) in World coordinates. I already figured out the math to constrain the camera to this shape, but there is a weird thing going on when the movement gets clipped The camera doesn't follow the outline perfectly, but in a rounded shape (see screenshot). Could this be due to a rounding error? Code snipped below. using System using UnityEngine using static UnityEngine.Mathf public class InputController MonoBehaviour private const float CamHeight 10f SerializeField private GameObject gameBoard SerializeField private GameObject camBounds SerializeField private float camBoundRadius 5f private Vector3 camOrigin private MeshCollider collider private Vector3 difference Change in position of mouse relative to origin private Camera mainCamera private Vector3 origin Place where mouse is first pressed private Plane worldPlane private void Start() mainCamera Camera.main if ( mainCamera is null) throw new Exception( quot No main camera could be found! quot ) Set the camera so that the board is always in the center camOrigin new Vector3( CamHeight Sqrt(2f), CamHeight, CamHeight Sqrt(2f)) mainCamera.transform.position camOrigin collider gameBoard.GetComponent lt MeshCollider gt () worldPlane new Plane(Vector3.up, 0) For dragging the camera around private void LateUpdate() if (Input.GetMouseButtonDown(0)) origin MouseWorldPosition() if (Input.GetMouseButton(0)) difference MouseWorldPosition() transform.position var newPos origin difference var absDiff newPos camOrigin var angle Angle2Pi(Vector3.right, absDiff) var constraint SawTooth(angle) if (absDiff.magnitude lt constraint) transform.position newPos else transform.position camOrigin absDiff.normalized constraint private Vector3 MouseWorldPosition() var clickedPoint Input.mousePosition var ray mainCamera.ScreenPointToRay(clickedPoint) var worldPos Vector3.zero if ( worldPlane.Raycast(ray, out var raycastHit)) worldPos ray.GetPoint(raycastHit) return worldPos private float SawTooth(float theta) var x 4f PI camBoundRadius (1f 1f Sqrt(2f)) x Abs(theta (PI 2f) PI 4f) x camBoundRadius Sqrt(2f) return x private static float Angle2Pi(Vector3 from, Vector3 to, Vector3 normal default) if (normal default) normal Vector3.up var angle Vector3.Angle(from, to) (PI 180f) var sign Sign(Vector3.Dot(normal, Vector3.Cross(from, to))) angle 2f PI angle sign return angle
0
WHY !! CountDown not Working inside the IF Condition? i need a way to make the countdown decreasing inside the if statement i am stacking in this problem for more than 3 days .. Don't suggest to me Coroutine cause it will not working in my case cause i am using clones (initiated prefabs) i know that the countdown will work only one frame if it's inside an IF Statement ... Any Ideas to make it working ...Ty The game is about cars ... and every instantiated car has a random countdown timer void Update() if(carNumber lt cars) SpawnCars() and this is the spawn function void SpawnCars() randomSpawnPoint Random.Range(0, spawnPoints.Length) randomSpawnCars Random.Range(0, Cars.Length) GameObject obj Instantiate(Cars randomSpawnCars ,spawnPoints randomSpawnPoint .position, Quaternion.Euler( 90, 180, 0)) as GameObject carNumber obj.gameObject.tag "select" k rcf obj.GetComponent lt RayCastForward gt () TextMesh txt FindObjectOfType lt TextMesh gt () time Random.Range(4, 20) txt.text (time Time.deltaTime).ToString("0") print(time) print(carNumber) EDIT time is the timer
0
Unity3d Do I need to destroy gameobject AND script? From proper leak protection do I need to delete both of these or will getting rid of one take care of both? Currently I am destroying the script AND the gameobject private void OnDestroy() Destroy(this.gameObject) Destroy(this)
0
Moving panel between two positions smoothly? I'm trying to make my panel moving from one position to another one smoothly. What I get is more faster no matter what I did to make it slower never get slow !! Both Vector3.Lerp and Vector3.MoveTowards did not give me a slow movement. Here is my script public GameObject gunsWindow private Vector3 a, b public bool open use inspector void Start() a gunsWindow.transform.position b new Vector3(100.0f, gunsWindow.transform.position.y, gunsWindow.transform.position.z) void Update() if(open) gunsWindow.transform.position Vector3.MoveTowards(a, b, Time.deltaTime 1) weaponPlane.transform.position Vector3.Lerp(a, b, Time.deltaTime) panel shaking else gunsWindow.transform.position Vector3.MoveTowards(b, a, Time.deltaTime 1) weaponPlane.transform.position Vector3.Lerp(b, a, Time.deltaTime) shaking
0
How to make AI detect a target behind a wall, who is only partially exposed? I'm making an FPS game where, even when a target's whole body is behind a wall or box, but its finger or foot exposed, the AI should be able to detect it and shoot its finger. So far the way I've thought of to implement this it so traverse all the targets, find who is near a wall, and compare their position with the corner of wall. But I don't know how to check whether its finger is exposed. I could use a raycast forward from the AI's gun, but would I need to add a collider to every small body part of every target?
0
Make a door in a cube wall I have created a wall using a cube in Unity. Now I want to create a door in it. How can I make a door in that cube? Consider that the cube is automatically generated, so i have to generate the door in a C script.