_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
0 |
How to slow down this rotation My goal here is simple. I am making a top down shooter kind of game, and I want the player to simply rotate in one axis, towards where the mouse is on the screen. I got it working, but it rotates so fast that everything is out of control. The following method is called in Update() on my player's game object void RotatePlayer() var targetPosition new Vector3(Input.mousePosition.x, Input.mousePosition.y, 100) targetPosition Camera.main.ScreenToWorldPoint(targetPosition) targetPosition.y transform.position.y Time.deltaTime transform.LookAt(targetPosition) That rotates in the direction of the mouse, but like I said it rotates so fast that you cannot control it. As you can see I tried to multiply by delta time, but that did not seem to do anything. Also, changing that last parameter of "100" to a lower number also does not do anything. Any help is greatly appreciated.
|
0 |
Unity Animator default values overwriten I have created a project to reproduce the problem I'm currently facing. I'm running a simple unity animation that moves a game object and expect to be able to reset the gameobject position. This can be done by adding an empty animation, that (since it does not change anything) simply writes the default values, thus returning our gameobject to its original position. But here is where things get complicated if the animator gameobject is set inactive while the animation is running, new incorrect defaults values will be saved when gameobject is activated, and I am unable to reset my gameobject position. To reproduce this issue, run the attached project (Download from here) Change the stop method to "PlayEmpty" Hit Start Animation and watch the left "Hello world" text travel. While it is traveling, click Disable Text GO. The left text disappears. Click Enable Text GO and see the text comes back at its last location. Click Start Animation and watch the left "Hello world" text travel. Click Stop Animation the text is returned to the position where it was when enabling the gameobject, rather than its original position. Any help is welcome, suggestions on how to change the code to make the above scenario work. Thanks, Yaniv
|
0 |
Verlet rope between two moving points connected with a spring joint? I'm connecting two moving rigidbodies using a spring joint in Unity. Between them, a rope will be rendered using a line renderer and I want it to move realistically as the joints move, without physics. I've read about verlet integration, but only found examples where one point moves, and the other one is calculated, for example a guy with a grappling gun, swinging back and forth. Here's the current implementation with spring joints. The second image shows a nice and smooth verlet rope with a line renderer. It's a little too lenient, but looks good. As this doesn't use physics, it doesn't let me move the object or affect the ship, for example if it was stuck on something. How do I make an elastic rope like the second image, between the spring joints, without the physics engine?
|
0 |
How to Load PDF file in runtime using PDF Renderer Asset in unity? Hello Guys I am working in Unity PDF Renderer. I will purchased that Asset but i need to Know, How to load PDF file one by one in run time in File path mode but old PDF File will remove and Load new PDF file in run time. can any one help
|
0 |
rigidbody cube falls off the ground Inspite my ground and cube contains colliders as i apply rigidbody it falls down....use gravity
|
0 |
Flexible and extendable system of level objectives (victory failure conditions) in Unity I'm trying to come up with a flexible system of level objectives for a Unity game. What I'd like to achieve is to have a system that on each level (scene) can accept a different set of (configurable) success failure conditions. Conditions can be repeated between levels but on every level a given type of condition should accept different parameters. For example on one level success conditions would consist of destroying all enemy units and on the other level success conditions would require destroying a specific enemy unit and escorting a friendly unit to a specific place on map. Failure conditions would for example be player death (on all levels) or not reaching a specific destination within a given time. First I've tried to approach this problem by using ScriptableObjects but abandoned this idea as it's not possible to save scene object references in a ScriptableObject. So I've come up with a kind of polymorphic system like this (pseudocode) public interface Condition bool IsFulfilled() public abstract class VictoryCondition MonoBehaviour, Condition public virtual bool IsFulfilled() public abstract class AllUnitsKilledCondition VictoryCondition public List lt Unit gt units public bool IsFulfilled() foreach (Unit unit units) if (unit.IsAlive) return false return true public abstract class FailureCondition MonoBehaviour, Condition public virtual bool IsFulfilled() public abstract class TimeOutCondition FailureCondition public float timeLeft void Update() timeLeft Time.deltaTime public bool IsFulfilled() return timeLeft lt 0 The idea here is to have a level manager that is given a set of victory failure conditions in the editor and have it continuously monitor all those conditions. In a simplest scenario a level is won if all victory conditions are fulfilled and lost if any failure condition is fulfilled. Unfortunately, I'm not sure how to create a LevelManager component that would expose those lists letting me add various conditions and configure them (for example letting me add a list of units from scene to AllUnitsDestroyedCondition). I think it would be doable with a set of custom property drawers for each type of condition but I'm wary of digging into this until I'm sure there is no other, easier way. I've come up with a way of adding various conditions by adding multiple condition components to a GameObject and then dragging those components to victory failure conditions lists in LevelManager. But this solution seems awkward and inflexible because it's not possible to dynamically add and configure new conditions in runtime and creating more complex conditions (for example some condition activating only after some other condition is fulfilled) seems like a sure way to create a huge pile of unmaintainable condition component mess. Please, let me know if I'm approaching this problem correctly and if not, what are other, simpler, more flexible solutions.
|
0 |
Helicopter controller, spherical world with faux gravity I followed this tutorial to create a planet with faux gravity that attracts objects. Further I'm trying to create a helicopter like controller that could move vertically and horizontally and that when the player presses control buttons this would compensate the faux gravity applied with AddForce to Rigidbody and the helicopter could fly. I implemented that in a way that when player presses buttons faux gravity with AddForce is not applied, but still the control feels very awkward. What would be the best way to compensate the faux gravity to move the helicopter? Edit I only need it to move in XY plane (so only up down left right). The camera looks on helicopter from its right side. The attractor script works in 3 axis and this is ok for now. Player controller (assigned to the helicopter) public class PlayerController MonoBehaviour public float moveSpeed 15 private Rigidbody rb private Vector3 moveDir private float h private float v void Awake() rb GetComponent lt Rigidbody gt () if(!rb) throw new Exception("Game Object must have Rigidbody!") void Update () GetControls() moveDir new Vector3(h, v, 0).normalized void GetControls() h Input.GetAxis("Horizontal") v Input.GetAxis("Vertical") void FixedUpdate() rb.MovePosition(rb.position transform.TransformDirection(moveDir) moveSpeed Time.deltaTime) Faux Gravity Attractor (assigned to the planet) public class FauxGravityAttractor MonoBehaviour public float gravity 10 public void Attract(Transform body) Vector3 gravityUp (body.position transform.position).normalized Vector3 bodyUp body.up Rigidbody bodyRb body.GetComponent lt Rigidbody gt () bodyRb.AddForce(gravityUp gravity) Quaternion targetRotation Quaternion.FromToRotation(bodyUp, gravityUp) body.rotation body.rotation Quaternion.Slerp(body.rotation, targetRotation, 50 Time.deltaTime) Faux Gravity Body (assigned to the helicopter) public class FauxGravityBody MonoBehaviour SerializeField float gravity 10 public FauxGravityAttractor attractor private Transform myTransform void Start () Rigidbody rb GetComponent lt Rigidbody gt () rb.constraints RigidbodyConstraints.FreezeRotation rb.useGravity false myTransform transform void Update () attractor.Attract(myTransform)
|
0 |
Unity, Does camera ALWAYS render to RenderTexture? I have a camera that renders a simple model to a RenderTexture. I then use that RenderTexture as a texture for my UI with a RawImage component. However, sometimes I disable my UI and therefore you can not see the RenderTexture. My question is Does the camera continue to render to the texture in the background even when the texture is not visible? If I understand how this works I believe it should. If so, simply disabling the camera should prevent it from rendering in the background? Thanks.
|
0 |
Joint based destructible physics (like Armadillo Run) I've implemented a destructible terrain system like Worms before (where weapons create holes in the terrain), but for the game I'm designing I want something more like Armadillo Run https www.youtube.com watch?v 4JoPlcyxxb4 where everything is made from individual parts connected by physics joints. I've figured out how to make a chain of planks using Unity's joints that can fall, swing off each other, bend if unsupported, and break at the joints. But I can't think of how to make planks break instead of the joints. There's an example of what I want at 2 25 in the video, where the plank on the right breaks (not the joints, but the actual plank itself). Obviously I'd just have to destroy the plank object, but how do I decide when to do that? I'm using the Unity engine (2D physics), but I'd be perfectly happy to implement something myself if someone can direct me to some research on the subject or anything else to help me get started.
|
0 |
How to customize player script with different abilities in each scene? I'm making a game with Unity. I wanted the player script to not have some features in some scenes but couldn't remove them from the script because I needed them for other scenes. So far, I just unpacked those player prefabs, created new scripts for each of them and removed the lines that I didn't want to have. I know this was not the best idea but I don't know any other way. One of its problems is that it makes managing the scripts hard and confusing. Is there a way that I can change them without creating new ones? Since I'm going to switch to the new Input system, I want to avoid the possible problems and headaches around these scripts. I also did this (creating a new script) for pause menu script as well. I provided two examples below to make the situation more clear. Example A) The player can use a shotgun in one of the scenes and I chose to not let him to use the knife in there. So I created a new script for that player and copied and pasted the original script (which had the melee attack ability) and then removed those lines from the new script. Example B) Pause menu can disable the health bar game object whenever the escape button is pressed. But for one of the levels, I don't want to use the health bar, so I pasted the code in a new pause menu script and removed the line that disables the bar.
|
0 |
Finding when shapes overlap and lines intersect but exclude points edges I've been looking for a c algorithm to help determine if shapes and lines intersect but want to exclude boundary overlaps. Here's an example My true problem is finding if polygons intersect but exclude boundary overlaps. I broke down the problem to look at the individual lines of that polygon and check each line segment from the shape1 against each line segment from shape2. A Is this an efficient correct way to do the checking? B How do I ignore when they are on the boundary as illustrated above? Here's some code I found here I've been testing for line segments but it fails on fig 2, when the end point of the 2nd line segment finishes on the end point of the 1st segment. private bool DoesLineIntersect(Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2) float denom ((end1.x start1.x) (end2.y start2.y)) ((end1.y start1.y) (end2.x start2.x)) AB amp CD are parallel if (denom 0) return false float numer ((start1.y start2.y) (end2.x start2.x)) ((start1.x start2.x) (end2.y start2.y)) float r numer denom float numer2 ((start1.y start2.y) (end1.x start1.x)) ((start1.x start2.x) (end1.y start1.y)) float s numer2 denom if ((r lt 0 r gt 1) (s lt 0 s gt 1)) return false return true
|
0 |
How To calculate camera boundaries Is it possible to calculate the exact camera bounds? By this I mean the white lines that represent the camera area e.g the lines in the picture I'm using Camera.main.screenToWolrdCoordinates to convert screen coordinates to world coordinates because I want to position the player exactly on that white line that the camera represents But when I calculate the boundaries using Camera.main.screenToWolrdCoordinates I get this The players legs are outside of that lower camera bound on y axis, it will also happen on x axis when I strict the players movement by using the value that I got from Camera.main.screenToWolrdCoordinates , I also have bouncing balls in my game that I want to strict by the same boundaries. So my question is how can I calculate camera bounds exactly by this I mean again these white lines that represent the camera view, I hope that my question is clear enought. Just to make it more clear, when I calculate the bounds using Camera.main.screenToWolrdCoordinates I just assign the Y value that I got from that calculation to the Y position of the player.
|
0 |
Having trouble making game time pause and unpause I've been trying to make it where when the player does a certain task, the game's time will pause. When the player does another action, the game's time would unpause and continue. I had my code like so using UnityEngine using System.Collections using UnityEngine.UI public class timeScript MonoBehaviour uGUI Items public Text date public Text playerCash Times public static int week public static int month public static int year 1980 amount of cash public static int myCash 10000 public AlertBox alert public Text timeText bool timeActive true int time int day void Start() InvokeRepeating("Timer", 0, 1) public static void Timer() timeText.GetComponent lt Text gt ().text "W" week.ToString() "" year.ToString() playerCash.GetComponent lt Text gt ().text " " myCash.ToString() region YEAR Check if month equals 13 (allows for 12th month to be counted) if (month 13) year month 0 endregion region MONTH Check if week equals 5 (allows for 5th week to be counted) if (month 5) month week 0 endregion region WEEK Check if day equals 8 (allows for 7th day to be counted) if (day 8) week day 0 endregion region DAY Check if Time equals 5 (allows for 4 seconds) if (time 2) day time 0 else time endregion I tried using CancelInvoke(timeScript.Timer()) in another c file but all it did was give me an error that stated I couldn't convert from string to void.
|
0 |
Unity WebGL Responsive content I was trying to develop a simple drag and drop items for Web. What I was trying to do is to make the UI elements from web view to mobile view when the aspect ratio is changes. I need this web view change to mobile view as below when the screen changes. Changing Canvas settings does not seems to be work. Could someone please help with this issue?
|
0 |
Manage vertical levels rendering I've been working on a semi professionnal project for more than one year. The game is in 3D with a TopView camera. In this game, the player will be in very vertical spaces, with lots of ladder and stairs. The actual problem is that I need to show only what is at the actual height of the player. I have made a shader that 'cut' the objects above a given height. The problem is that my mesh are open above this height, and we just see nothing inside. If you have any idea on how to make something to fill an open mesh or any other system that will do the job, i'll be very pleased to read you ) This is what I have This is what I aim to (black above top of walls)
|
0 |
Offsetting ground texture doesn't work in WebGL so I've created a 2D sidescroller game, the technique I used is to keep the player on the same place, and move the obstacles towards him. I also offset the ground and backdrop constantly to create the illusion of player moving. The ground texture is on a quad, and the texture wrap mode is set to repeat. In the editor everything is running fine as I wanted, however when I build it (WebGL), in the browser the ground doesn't seem as if it is set to Repeat but rather Clamp. Here's how it looks You can see from the left part of the image the ground doesn't repeat, the strange thing is that, after the game runs for a few more seconds it fixes, and then in a few seconds becomes like that again. heres the code attached to the ground to keep it offsetting constantly using System.Collections using System.Collections.Generic using UnityEngine public class Offset MonoBehaviour public float scrollSpeed public Material mat private float offset Use this for initialization void Start () mat GetComponent lt Renderer gt ().material Update is called once per frame void Update () offset Mathf.Repeat(Time.time scrollSpeed, 1) mat.mainTextureOffset new Vector2(offset, mat.mainTextureOffset.y) What may I be doing wrong, and how can I fix it? Thanks in advance!
|
0 |
How can I hide an object for one eye for the unity oculus rift DK2 platform? I am trying to build a game for my son for the Oculus Rift DK2 to help treat his lazy eye using Unity. I need objects that Appear only to his left eye Appear only to his right eye Appear for both eyes. (this helps force the brain to use both eyes together to form the complete scene) How can I pull this off? Thanks!
|
0 |
What is "Avatar" in the "Animation Controller" used for? I'm using animation layers for a model of type quot Generic quot . The quot Base quot layer contains an quot Idle quot animation. The quot Shooting Layer quot contains a pistol shooting animation. I want the shooting layer animation to only affect the upper body. To do that, I need to use an Avatar Mask, I think. In the avatar mask, I have to select if I want it to be of type quot Humanoid quot or of type quot Generic quot . I will not use a quot Humanoid quot avatar mask because my animations are perfectly tailored for my model, and I don't need any retargetting. Instead, I wanted to use the quot Transform quot avatar mask type. However, it seems to expect an avatar However, I haven't had the need to create one yet. Do I really need to create an avatar? I don't want any quot Humanoid quot , I want to have full control over my animations and over what's going on. I have tried quot Humanoid quot before, and for me, it's a total loss of control as I can no longer tell what is a bug mis use by me and what is automatic retargetting done by Unity, so I want to avoid it by any means. Why do I have to create an quot avatar quot ? What is it actually? Unity already has my generic model to work with, so it knows the transform. Why does it want an quot avatar quot ? Edit The strange thing is I can create an avatar the usual way gt quot Rig gt Create Avatar quot gt quot From this model quot . Then I have an avatar. In the avatar mask, I need to feed an avatar. I do this, then it shows my transform. Now I can delete the avatar, and it still remembers my transform. Strange... not sure why Unity can't simply use the transform.
|
0 |
change one object into another, and then back again in Unity For example, I would like to change a cube into a sphere, then change that sphere into a capsule, by pressing the up arrow. I would also like to be able to change in the other direction. Change the capsule into a sphere, then change the sphere into a cube, by pressing the down arrow. It would be great if i could add extra objects in, say a pyramid etc. Ultimately i would want to do this with something like a seed, sapling, and tree. Each with there own properties.
|
0 |
Build and Run results in an empty window Out of nowhere my builds are broken. The .exe just always gives me this little blank window but it runs fine in the editor. Here are some things I have tried Deleted the previous build files Deleted the Library folder Upgraded to 2020.2.4f1 Uninstalled Reinstalled Unity Deleted AppData Files Deleted branch and pulled it back down (the branch works fine for other people) Here are my resolution and presentation settings
|
0 |
Unintended sliding blocks Unity (5) physics A game I'm working on right now relies on the Unity physics system for collisions, gravity etc. This all works well except for one strange thing. When an explosive is placed on a stone cube, it'll slide right off. A video displaying the sliding behavior https www.dropbox.com s lr6lhnn30x61tvf Unity 202015 02 19 2013 41 39 54.avi?dl 0 The stone gameobject settings http puu.sh g3BFn c15483b8ea.jpg The explosive has the same settings except for that the Mass is 1. What could cause this weird sliding and how can it be fixed?
|
0 |
Make Build and Run faster Is there a way to build an apk faster? (by disabling some shader compilation, for example Hidden Post FX Uber Shader takes most of the build time) p.s. Yes I know about Unity Remote and use it this time I need exactly Build and Run.
|
0 |
How can I places objects to specific facial landmarks ? like ears and hats I'm currently trying multiple AR plugins in unity and I'm stuck in how to place certain objects in specific landmark positions. I used the landmark positions to spawn certain objects but they are way off from the intended areas I wanted. Here is the code sample I'm using the get the facial landmarks of the ears, mouth, nose and eyes MatOfPoint2f imagePoints imagePoints new MatOfPoint2f () Mat rgbaMat webCamTextureToMatHelper.GetMat() Rect detectionResult faceLandmarkDetector.Detect() List lt Vector2 gt points if(detectionResult ! null amp amp detectionsResult gt 0) points faceLandmarkDetector.DetectLandmark(detectionResult 0 ) if(points ! null) imagePoints.fromArray( new Point((points 38 .x points 41 .x) 2, (points 38 .y points 41 .y) 2), Left Eye Facial LandMark Position new Point((points 43 .x points 46 .x) 2, (points 43 .y points 46 .y) 2), Right Eye new Point(points 30 .x, points 30 .y), Nose new Point(points 0 .x, points 0 .y),Left Ear new Point(points 16 .x, points 16 .y) Right Ear )
|
0 |
www.texture and www.LoadImageIntoTexture both just show red question mark I'm trying to use this code I found in the Unity docs to display a remote image on a plane. However, no matter what URL I try, it only displays a red question mark. using UnityEngine using System.Collections public class KnowledgeWall WeatherMap MonoBehaviour The source image public string url "https radar.weather.gov Conus Loop northrockies loop.gif" public string url "http www.gstatic.com webp gallery 1.jpg" IEnumerator Start() Texture2D tex tex new Texture2D(4, 4, TextureFormat.DXT1, false) using (WWW www new WWW(url)) yield return www www.LoadImageIntoTexture(tex) GetComponent lt Renderer gt ().material.mainTexture tex I also tried the code here, which is slightly different. It gave the same result. Unfortunately this project is Unity 5.3.6. How can I fix this so Unity 5 displays the remote image?
|
0 |
FullSerializer Update serialized property name Currently we have some ScriptableObjects that are referenced by their name. This comes with some issues as names may change and also they don't have to be unique. We would like to switch to UUIDs. using FullSerializer System.Serializable fsObject(Converter typeof(CharacterDataConverter)) public class CharacterData public CharacterSO player public CharacterSO mentor The mentor field is currently serialized as mentorName. With the changes the serialized field name would be mentorUid. This is handled by the CharacterDataConverter, but this has to be updated all the time when CharacterData class changes and is often forgotten. Much simpler would be to use fsProperty using FullSerializer System.Serializable public class CharacterData fsProperty(Converter typeof(PlayerConverter) public CharacterSO player fsProperty(Converter typeof(CharacterSOConverter), Name quot mentorName quot ) public CharacterSO mentor But this can handle only either mentorName or mentorUid. Is there another solution? Maybe using versioning?
|
0 |
How to make it possible to change the width of the stripes? I am making a shader to create stripes based on this tutorial, but I cannot set the width for each stripe and make a shader that accepts light. Shader quot Unlit Stripes 2 quot Properties IntRange NumColors( quot Number of colors quot , Range(2, 4)) 2 Color1( quot Color 1 quot , Color) (0,0,0,1) Ratio1( quot Width 1 quot , Float) 0.1 Width for first color. Color2( quot Color 2 quot , Color) (1,1,1,1) Ratio2( quot Width 2 quot , Float) 0.1 Color3( quot Color 3 quot , Color) (1,0,1,1) Ratio3( quot Width 3 quot , Float) 0.1 Color4( quot Color 4 quot , Color) (0,0,1,1) Ratio4( quot Width 4 quot , Float) 0.1 Tiling( quot Tiling quot , Range(1, 500)) 10 WidthShift( quot Width Shift quot , Range( 1, 1)) 0 Direction( quot Direction quot , Range(0, 1)) 0 WarpScale( quot Warp Scale quot , Range(0, 1)) 0 WarpTiling( quot Warp Tiling quot , Range(1, 10)) 1 SubShader Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot int NumColors fixed4 Color1 fixed4 Color2 fixed4 Color3 fixed4 Color4 int Tiling float WidthShift float Direction float WarpScale float WarpTiling struct appdata float4 vertex POSITION float2 uv TEXCOORD0 struct v2f float2 uv TEXCOORD0 float4 vertex SV POSITION v2f vert(appdata v) v2f o o.vertex UnityObjectToClipPos(v.vertex) o.uv v.uv return o float2 rotatePoint(float2 pt, float2 center, float angle) float sinAngle sin(angle) float cosAngle cos(angle) pt center float2 r r.x pt.x cosAngle pt.y sinAngle r.y pt.x sinAngle pt.y cosAngle r center return r float random(float2 uv) return frac(sin(dot(uv, float2 (12.9898, 78.233))) 43758.5453123) fixed4 frag(v2f i) SV Target const float PI 3.14159 float2 pos rotatePoint(i.uv.xy, float2(0.5, 0.5), Direction 2 PI) pos.x sin(pos.y WarpTiling PI 2) WarpScale pos.x Tiling int value floor((frac(pos.x)) NumColors WidthShift) value clamp(value, 0, NumColors 1) switch (value) case 3 return Color4 case 2 return Color3 case 1 return Color2 default return Color1 ENDCG
|
0 |
Maximum number of controllers Unity3D can handle I've been trying to find out the maximum amount of xbox controller Unity3D can handle on one editor. I know through networking, Unity is capable of having as many people as your hardware can handle. But I want to avoid networking as much as possible. Thus, on a single computer, and in a single screen (think Bomberman and Super Smash Brothers) how many xbox controllers can Unity3D support? I have done work in XNA and remember that only being capable of support 4, but for the life of me, I can't find any information that tells me how many Unity can support.
|
0 |
Extend distance for rendering grass and tree objects on terrain I am trying to make an adventure game with a big landscape (made the terrain with terrain tools) with 3D models of grass (that I placed using terrain tools) but it only shows the grass trees that are within a small area. Here is a pic of what I am talking about I would not want to totally remove this because otherwise the framerate will go too low. I just want to make the circle bigger. thanks (
|
0 |
Look rotation viewing vector is zero in Unity when making UI How can I tackle the problem Look rotation viewing vector is zero? Here is how I get it I add an Image from UI. When the Image is added I click on it in the Hierarchy view. When focus is on an Image I take the Canvas border and move it left. I get the Exception. Here are some screenshots of the process which takes place In the last screenshot I selected the Canvas and tried to focus on it by pressing F in the Scene view. As you can see I am not able to resize the canvas anymore. That means that I would have to create a new Canvas and copy everything into it, which is pretty tiresome and error prone. That is a reason I am concerned with the Exception. Will appreciate any attention.
|
0 |
Character rotation according to camera causes rapid flipping when game starts When I load my scene, my character rotates 90 and 90 on the X axis very fast about 4 or 5 times, and then he stops at 90 on X axis (lays back down). When I move the character, the rotations are just the way I want them, but I need to fix that weird bug at the beginning of the game. Here's my character's movement logic. It's based on the rotation of the camera, which is a child of my character object. void Update() Vector2 vec new Vector2(horizontal, vertical) vec Vector2.ClampMagnitude(vec, 1) Vector3 camF cam.transform.forward Vector3 camR cam.transform.right camF.y 0 camR.y 0 camF camF.normalized camR camR.normalized transform.position (camF vec.y camR vec.x) Time.deltaTime MoveSpeed Vector3 deltaPosition transform.position prevPosition if (deltaPosition ! Vector3.zero) transform.forward deltaPosition prevPosition transform.position
|
0 |
How should the physics be on an halfpipe like in a skate game in Unity? I am making a inline skating game. My player is skating based on the normals of the surface of the ground. But when I skate up a halfpipe it flies in the Air but doesnt comes down like it should be, it changes position in the Air and my player falls horizontally on the ground I cant get up anymore like this when he is lying on the Ground. I want it to be physically jump up and come down again the player should align on the ramp again not just fly in the air and drop down on the ground? What infos should you need to answer this question properly I will edit the question then?
|
0 |
Player jittering against wall when held down button So, I'm making a top down RPG. Everything's going excellent, but this problem is quite annoying. Now, when the character moves against the wall, the player jitters back and forth. I'm guessing it's because the player is trying to move into the wall, and then the wall collision is pushing it back, which makes an annoying back and forth movement. My question is obviously, how do I stop this from happening? Thanks! PS I'm using transform.translate to move the player, and I'm using C . EDIT I'm also using a 2D Rigidbody, and 2Dbox colliders on both.
|
0 |
Is it possible in Unity to Flip a 2D Sprite Without Flipping the Object it is Assigned to? I 'built' (followed a tutorial) on a collision detection system, and when I flip the object to go left and right the collision messes up. So I have three options find a way to modify the collision detection, have sprites for all animations for left and right or to flip the sprite but no the object. if anyone has used RaycastHit2D, and has figured out a way to do it correctly, that would also be great.
|
0 |
Unity Static Camera Perspective, Walls Obscure Player Pretty simple and common problem here. The world I'm designing is fully explorable, no invisible walls or tricks. It's presented as a single seamless area, a School complex with 9 buildings, some of which have 2 or 3 floors and contain many rooms. The perspective I've chosen is simple, inspired by topdown RPGs A problem arises with walls. They obscure the player. I've tried some shaders which draw a silhouette of the player ontop but I don't like this approach, other objects and decoration remains obscured behind the wall. Some kind of dissolve effect allowing you to see through the walls would be preferable, but writing my own shaders is not my fort ... Another problem is with large buildings outside. The camera is at a fixed distance, about 14 metre's away. If the player walks behind a large building (over 10 metres tall) then the camera cuts off the top of it as it is now within the building. The only way I can think of fixing this is to adjust the distance between player and camera, but some of the buildings are so tall the zoom out looks very unusual and impractical. I suppose this is why you don't see this simplistic camera setup in large explorable games... While I've been developing games for some years now, I've only come to 3D and Unity fairly recently, so there might be a jaw droppingly simple solution which I'm not seeing. Anyway, I'd like to hear some interesting or novel approaches towards fixing these problems, besides the simple ones I've suggested. I hope that's not asking too much.
|
0 |
How do I handle loads of (prefab?) objects in Unity2D 3D? I have been looking around for information regarding this process but I was unable to come across anything that would help me out. Basically, in a game where you may have many items or enemies or player objects, how would one go about creating these objects? Am I supposed to be creating every single one of these objects as a prefab and then load them into the game when needed? Or is it possible to create one object that has references to the different variables needed to create the above objects and then load in from an external source all the necessary information? And then during run time, depending on what object I am looking at, the script will 'create' the object with the information from the external source. Meaning, if I decide to have 50 different enemies in my game, do I need to make 50 prefabs, one for each enemy? Or just one prefab that loads in data pertaining to the 50 different enemies and then build upon that information? Thank you!
|
0 |
Standard Asset package import in unity 2018.3 I am using iMac, I don't see any for import standard package in unity. My working project need to import standard packages. I use unity version unity 2018.3.0f2. Please guide me from where I get the unity standard asset package. Thanks.
|
0 |
Unity create water issue I use daylight water in my project but by the default it has not got any waves or light tracing effects. But in some tutorials I see how the user add standard water asset and it has got beautiful world reflection on the surface and beautiful waves. Is this issue because that I am using not a PRO version?
|
0 |
Unity3D animation trigger reset How can I reset conditions for animations using an animation controller? I have a door that will open when a boolean property in a script is set to true. This then calls setTrigger on the animator to play the open door condition and then reset the boolean property to false. After 5 seconds I then close the door. However when I change the boolean to true again to open the door, either the setTrigger isn't working again on the animator, or the trigger for the door close is conflicting. How would I resolve this? Is there a way in the animator to set a condition to false when a particular animation has finished? Initially I was using a boolean condition in the animator but ran into the same problem. I looked at the 2D sample project which used trigger instead and assumed this would only fire once. However I guess something else could be wrong. The code in my script is as follows (where anim is the animator component) void Update() if (open) OpenDoor() open false void OpenDoor() anim.SetTrigger ("OpenDoor") Invoke("CloseDoor",5) void CloseDoor() anim.SetTrigger ("CloseDoor") As I say the animation fires correctly the 1st time but not on subsequent times. I'm just trying this by changing the public "open" property in the inspector thanks
|
0 |
Particle spawn on collision spawns too many particles So i have the following code private void OnCollisionEnter(Collision collision) foreach (ContactPoint contact in collision.contacts) if (contact.otherCollider.CompareTag("Ground")) Instantiate your particle system here. Instantiate(Effect, contact.point, Quaternion.identity) Now this works great however it spawns way too many particles (as the animation I am doing with the item hits the ground a lot). Is there a way to limit the particles in a sensible way?
|
0 |
PlayClipAtPoint() playing multiple times on enemy death I am having problems with PLayClipAtPoint(). I want to play a given sound as soon as a gameObject is destroyed. Here is my code (the concerned parts) void Update() if (health lt 0) StartCoroutine(Death()) public IEnumerator Death() anim.SetBool("isDying", true) AudioSource.PlayClipAtPoint(dmgSounds 0 , transform.position) Destroy(gameObject, 3f) yield return null I assume that the problem is due to the fact that as soon as the conditions are achieved, in this case the health reaching zero, the coroutine starts and it will keep starting for each frame, but how else should I call it? Anybody has some hint to give? EDIT I have already tried to wrap the logic in a bool as suggested in the comment so that it would work only when the bool condition is valid, without success. Here is the code with the flag bool void Update() if (health lt 0) if(isAlive) isAlive false StartCoroutine(Death())
|
0 |
How can I rotate a cylinder so the top points at specific transform? I have a GameObject (goA) with a LineRenderer that has a single line drawn, on which I'd like to place cylinders so the top of the cylinder points to each end of the straight line that the cylinder sits on, (similar to a cylindrical bead on a straight piece of string, or a Candlestick chart). The cylinder GameObject (goB) is a child of the goA which the LineRenderer is sat on (goB.transform.parent goA.transform). goA is not rotated itself, and the Line drawn could be any angle relative to the GameObject, and it would be a bit of a hassle to refactor so that the Line is always vertical and instead rotate goA, and it seems this should be an easily solvable problem! I'm attempting to use either LookRotation or LookAt on the cylinder but for whatever reason all permutations I can think of simply are not working. Thanks for any advice!
|
0 |
Unity SpriteRenderer. Trying to make sprite from code using Texture2d.whitetexture I have been trying to write a method that fills a rectangle with a color. I've tried it as a new 2D and 3D project just in case, but this gives the same results. Basically, i want the script to make a new GameObject, give it a SpriteRenderer component and then fill the given rectangle with the given color. I have tried to work from the Unity docs and other sources of info, but no matter how much I look around, this now looks correct to me but doesnt work. The result (as pictured) shows the new object with the sprite renderer and even shows the right size (there are blue 'corner' icons in the scene view I can see but no sprite or rectangle of any kind. using UnityEngine public class GameBoard MonoBehaviour const ushort cellCount x 10 const ushort cellCount y 24 only 20 will be visible to player const ushort cellsize 50 GameObject testBlock SpriteRenderer testBlockRen private void Start() testBlock new GameObject() testBlockRen testBlock.AddComponent lt SpriteRenderer gt () testBlockRen.sprite CreateRectSprite(new Rect(0, 0, cellsize, cellsize), Color.red) Sprite CreateRectSprite(Rect rect, Color color) Texture2D tex Texture2D.whiteTexture tex.SetPixel(0, 0, color) tex.Resize((int)rect.width, (int)rect.height) Sprite sprite Sprite.Create(tex, rect, Vector2.zero) return sprite By the way I have made sure the camera 'z' is less than 0 (it's 10). And the camera is centred where the sprite is supposed to appear. Note I can get a sprite to render fine if I create a texture in gimp and then use Resources.Load() . But I am trying to create the sprite using no source texture whatsoever (other than Texture2d.whitetexture)
|
0 |
A trigger collider in Unity doesn't allow the player to pass through It's my understanding that checking "Is Trigger" on a collider should allow rigid bodies to pass through without collision prevention, but my trigger isn't doing that consistently. The player cannot pass through, but other objects can. The trigger is a cube primitive with "mesh rendered" unchecked so that the cube won't be visible. The cube has a box collider with "is trigger" checked, and also a script. The script currently doesn't do anything except output from Debug.Log in OnTriggerEnter() as a test. Primitives are able to pass through. The test is just a basic Unity sphere with all the default settings, including a sphere collider. The only change was that I added a RigidBody. Imported models also pass through. I have a simple .blend model with a rigid body and box collider. The player does not pass through. The main difference between the player's object and the other imported model is that the player is using a custom mesh collider which is different than the player's rendered mesh. The rendered mesh is the game object and the low poly collision mesh is a child of that object. I've tried several variations, including switching the player from a mesh collider to a box collider, and also moving the box collider to the main mesh rather than a child mesh, but the results are the same. The player stops moving as soon as he hits the location of the trigger's box collider. Any ideas are appreciated. Thanks in advance. MORE INFO Here's a screenshot of the scene layout, with the invisible trigger collider selected. Also pictured is the hierarchy showing that the trigger collider ("Jump Pad Trigger") has no children. On the right is displayed every component that the trigger object has. I've also moved the collider from its original location several times to prove that it's not another object in the scene that the player is colliding with.
|
0 |
Character controller falling with positive speed I'm having very weird problems with my player's vertical movement. I'm using a Character Controller component with a capsule collider and no rigidbody. For testing purposes, I've ended reducing my jump script to just this line owner.CharacterController.Move(new Vector3(0, 0.01f, 0)) When executing this script, the player should just fly upwards at a constant speed, right? Well, what ends up happening is that the player starts jumping in place repeatedly. The jumps are smooth, as if the movement was being affected by gravity. I thought that the standard Character Controller doesn't handle gravity automatically and you have to do it yourself, so I can't understand what's going on here. There is no other code affecting the player, if I comment that line it just rests in place. If I try a different direction (like (0.01f, 0, 0)) the player moves in a straight line in the provided direction as expected. But when moving vertically, weird stuff happens S
|
0 |
NULL REFERENCE EXCEPTION Object reference not set to an instance of an object So I have 3 scripts first for my player movementscript second for my speed powerup speedscript third for my obstacle box script i I'm trying to get the component of box script in speed script, to get the function 'added' (which is in box script) into speed script but it keeps giving me nullreferenceexception error Here are those scripts public class box MonoBehaviour SerializeField GameObject effect public int damage 1 SerializeField float Speed 10f SerializeField GameObject audioexplosion void Update() transform.Translate(Vector2.left Speed Time.deltaTime) void OnTriggerEnter2D(Collider2D col) if(col.CompareTag("Player")) Instantiate(audioexplosion, transform.position, Quaternion.identity) Instantiate(effect, transform.position, Quaternion.identity) movment tmp col.GetComponent lt movment gt () tmp.health damage Destroy(gameObject) public void added(float spd) Speed spd And here is my speed script. public class speedscript MonoBehaviour SerializeField GameObject effect SerializeField GameObject speedaudio SerializeField public float speed public float add v 5 private float timeindue SerializeField public box io void Start() io GetComponent lt box gt () Debug.Log(io) void Update() transform.Translate(Vector2.left speed Time.deltaTime) void OnTriggerEnter2D(Collider2D sp) if (sp.CompareTag("Player")) Instantiate(speedaudio, transform.position, Quaternion.identity) Instantiate(effect, transform.position, Quaternion.identity) box io GetComponent lt box gt () Debug.Log(io) io.added(add v) Destroy(gameObject)
|
0 |
Applying velocity to parent that ignores children's mass not working I am making a VR data visualisation app in Unity and I have a parent with many children (just some primitive cubes) that I can toss around the scene by just setting the parent's rigidbody to the same velocity as my tracked VR controller. Rigidbody rb GetComponent lt Rigidbody gt () Vector3 controllerVelocity Player.instance.rightHand.GetTrackedObjectVelocity() how I ref the controller velocity in SteamVR rb.velocity controllerVelocity 2f the 2f is just to speed up the velocity The above code works fine, but the problem is I think the scale of the children objects, which can be adjusted by the player, is affecting the velocity the parent moves at. Or maybe just when the children are very large...the controller velocity is comparatively too slow? Basically I need this to not be the case I want the parent's rigidbody to move at roughly the same velocity no matter the children's scales masses. So to achieve that I thought to use Rigidbody.AddForce but it doesn't seem to be making any difference i.e. larger children are still moving slower. Here is what I have so far Rigidbody rb GetComponent lt Rigidbody gt () Vector3 controllerVelocity Player.instance.rightHand.GetTrackedObjectVelocity() rb.AddForce(controllerVelocity 2f, ForceMode.VelocityChange) I also tried ForceMode.Acceleration but then nothing moved at all? Am I using AddForce incorrectly? Or do I just need a scaling multiplier based on the size of the children? Any help is welcome.
|
0 |
Unity3D object fill shader I've been researching this for a while, and had no luck yet. I figured I'd ask here to see if anyone had any good ideas. Essentially what I want is a shader that can make only part of an object transparent based on a slider. Similar to fill effects on 2D sprites, the object would fill from the bottom up, when the slider was set to 0 the whole object would be transparent, when it was set to 50 just the bottom half would be visible, and when it was set to 100 the whole object would be visible. I've tried various masking effects, but it would be best if I could build this in to existing shaders or have a separate mask. Is there perhaps a way to adjust the alpha on individual pixels used for the diffuse texture without incurring great performance loss?
|
0 |
Volumetric Fog Shader Camera Issue I am trying to build an infinite fog shader. This fog is applied on a 3D plane. For the moment I have a Z Depth Fog. And I encounter some issues. As you can see in the screenshot, there are two views. The green color is my 3D plane. The problem is in the red line. It seems that the this line depends of my camera which is not good because when I rotate my camera the line is affected by my camera position and rotation. I don't know where does it comes from and how to have my fog limit not based on the camera position. Shader Pass CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform float4 FogColor uniform sampler2D CameraDepthTexture float Depth float DepthScale struct v2f float4 pos SV POSITION float4 projection TEXCOORD0 float4 screenPosition TEXCOORD1 v2f vert(appdata base v) v2f o o.pos mul(UNITY MATRIX MVP, v.vertex) o.projection ComputeGrabScreenPos(o.pos) o.screenPosition ComputeScreenPos(o.pos) return o sampler2D GrabTexture float4 frag(v2f IN) COLOR float3 uv UNITY PROJ COORD(IN.projection) float depth UNITY SAMPLE DEPTH(tex2Dproj( CameraDepthTexture, uv)) depth LinearEyeDepth(depth) return saturate((depth IN.screenPosition.w Depth) DepthScale) ENDCG Next I want to rotate my Fog to have an Y Depth Fog but I don't know how to achieve this effect. It seems that this is caused by CameraDepthTexture, that's why depth is calculated with the camera position. But I don't know how to correct it... It seems that there is no way to get the depth from another point. Any idea ? Here is another example. In green You can "see" the object and the blue line is for me the fog as it should be.
|
0 |
Best C technique to pass variable from Instantiated object to GameObject There are lots of instantiated prefabs. Info from it is transmitted while it crosses a trigger zone. Some of these are calculated custom variables. I can print the custom variables from the instantiated prefabs. I can get the trigger zone to report standard things like "...transform.position" or "...transform.localEulerAngles", but not stuff I make up. Intellisense seems to see everything I am trying to get, and everything compiles. What's the best manner to perform this? Here's what I've tried Prefabs' Script public float infoToSend void Update() float infoToSend 10f ...actually, there's some math here, but it's a float. print("Sender " infoToSend) Works. Receiver Script on Trigger Zone void OnTriggerStay2D(Collider2D other) print("Receiver " other.transform.position) Works Fine. print("Receiver " other.transform.localRotation) Works Fine. float infoReceived other.GetComponent lt PrefabsScript gt ().infoToSend print("Receiver " infoReceived) Does not work! Any help, either fixing this arrangement or directing me to a different method, would be appreciated. Thanks. Edit to display the solution Corrected Prefabs' Script (changed third line down) public float infoToSend void Update() this.infoToSend 10f ...actually, there's some math here, but it's a float. print("Sender " infoToSend) Works. Correct Receiver Script on Trigger Zone void OnTriggerStay2D(Collider2D other) print("Receiver " other.transform.position) Works Fine. print("Receiver " other.transform.localRotation) Works Fine. float infoReceived other.GetComponent lt PrefabsScript gt ().infoToSend print("Receiver " infoReceived) Does not work! Many thanks, again! There's so many places to begin with, it's tough to find a "Beginner course" to cover everything.
|
0 |
What would be the best way to find a Game Object that is closest to another Game Object in unity? I made a 2d space shooter game awhile ago and I want to go back into it and overhaul some things. I'll provide a link to the game so anyone can play and get a better understanding of what I'm trying to do. https your pal drewdle.itch.io starspeed With how the game is currently set up, all the enemies are constantly setting their rotation to be facing the position of the player. I want to go back in and add a co op mode where there are 2 players, however, if I just added a second player without changing any code, the enemies would always be facing Player 1, never directly facing Player 2. I was thinking that I could get around this by giving each enemy an invisible circle with the center at the enemies position that would constantly expand until it hit one of the two players, I could then set the enemies rotation to face the point where the circle collides with one of the players. In theory, this would make it so that each enemy is facing towards whichever player is closest to it. So my question is How could I go about implementing this in unity? Or, is there a better or more efficient way to do this that would yield the same result? I've spent a decent amount of time researching this and I haven't had much luck. All help is appreciated, if you need more explanation just let me know and I will do my best to explain in more detail.
|
0 |
Why players who join late can't see other people data? I want to show the name of the players above their head but I have a problem where people joining late doesn't get other players' name. For example Player 1 joins to the server with the name Peter. Player 2 joins to the server with the name Josh. Peter (Player 1) sees Josh's name perfectly, but when Josh joins Peter's name is not synchronized correctly. My sync code looks something like this SyncVar private string NAME public override void OnStartClient() if(networkPlayerData is null) networkPlayerData BTNetworkController.Controller.playerData NAME BTNetworkController.Controller.playerData.Name SendPlayerNameToServer(NAME) Command private void SendPlayerNameToServer(string name) RpcSetPlayerName(name) ClientRpc void RpcSetPlayerName(string name) gameObject.GetComponentInChildren lt TMP Text gt ().text name So my question is how can I sync data to newly joined players and refresh player names accordingly.
|
0 |
Finding if 2 polygons intersect using clipper library After realising my code was pretty inefficient at checking for polygon overlaps, I've turned to a mentioned library Clipper but finding it difficult to know hot to use it for this operation. I am using unity Vector2 for my shape descriptions Square Vector2 square new Vector2 new Vector2(0,0), new Vector2(1,0), new Vector2(1,1), new Vector2(0,1) I want to be able to do the above boolean comparison of 2 shapes. If anyone knows Clipper well, what methods can I use to do this check? I've recently tried the following but the result is always true even when the test shapes are completely separate from each other public bool CheckForOverLaps(Vector2 shape1, Vector2 shape2) List lt IntPoint gt shape1IntPoints Vector2ArrayToListIntPoint (shape1) List lt IntPoint gt shape2IntPoints Vector2ArrayToListIntPoint (shape2) List lt List lt IntPoint gt gt solution new List lt List lt IntPoint gt gt () c.AddPath (shape1IntPoints, PolyType.ptSubject, true) c.AddPath (shape2IntPoints, PolyType.ptClip, true) c.Execute (ClipType.ctIntersection, solution, PolyFillType.pftNonZero, PolyFillType.pftNonZero) return solution.Count ! 0 private List lt IntPoint gt Vector2ArrayToListIntPoint (Vector2 shape) List lt IntPoint gt list new List lt IntPoint gt () foreach (Vector2 v in shape) list.Add (new IntPoint (v.x, v.y)) return list And the tests Square Vector2 square new Vector2 new Vector2(0,0), new Vector2(2,0), new Vector2(2,2), new Vector2(0,2) Square Vector2 square2 new Vector2 new Vector2 (1, 1), new Vector2 (3, 1), new Vector2 (3, 3), new Vector2 (1, 3) Square Vector2 square3 new Vector2 new Vector2 (2, 0), new Vector2 (4, 0), new Vector2 (4, 2), new Vector2 (2, 2) Square Vector2 square4 new Vector2 new Vector2 (4, 0), new Vector2 (6, 0), new Vector2 (6, 2), new Vector2 (4, 2) Assert.IsTrue(tc.CheckForOverLaps(square,square2)) Assert.IsFalse(tc.CheckForOverLaps(square,square3)) Assert.IsFalse(tc.CheckForOverLaps(square,square4)) Many thanks.
|
0 |
Unity Array of custom class with a superclass using generics does not show in the inspector I want to create 2 classes for Scriptable Object Weapon and Armor. Because both have similar functionality, I made a base class for both of them. using UnityEngine public abstract class Gear lt T gt ScriptableObject public int price public int level public Sprite image Header("Levels List") public T levels public T CurrentLevel() return this.levels this.level public T NextLevel() return this.levels this.level 1 public bool UpgradesLeft() return this.level 1 lt this.levels.Length public void Reset() this.level 0 public bool Upgrade() if (!this.UpgradesLeft()) return false this.level return true System.Serializable public abstract class StatsLevel public int price Both weapons and armors have the properties in common like they all have a price, they all have a Sprite Image, and so on... and more importantly they all have an array of Stat Levels. Meaning that every armor or weapon can have different levels, and depending on their level, the stats will be different. For that I used Generics. So when I created the Armor, I did it this way using UnityEngine public enum ArmorStat Low, Med, High, Super CreateAssetMenu(fileName "Armor", menuName "NARG Armor", order 1) public class Armor Gear lt ArmorStatsLevel gt Armor custom logic System.Serializable public class ArmorStatsLevel StatsLevel public int weight public ArmorStat blunt, slash, range in this class I define the stats unique to an Armor. Up to here everything looks peachy. But the issue comes with the Inspector As you can see, the inspector is not showing the array with the list of Stats on different levels, and I after a lot of research, I think it has to do with the Generics. If instead of unifying the common code between Armor and Weapon on the Base, I duplicate it each subclass, the Array is shown without problem. How could I make it so that the array information is shown in the inspector?
|
0 |
M bius effect in Unity This morning I've seen the following animation on Twitter. It is a kind of M bius strip effect. It's cool! Isn't it? So I've decided to build something similar using Unity, just for fun. I want to build the effect using just the cameras, as this way we can use it for any rotating scene. The first step has been to create a circle scene and make it rotate Note that the camera uses an ortographic projection so perspective does not deform it. This is important so we can merge different views later. Then I've replaced the main camera by two different ones, located in opposite positions (horizontal and vertical) and rendering to textures. A simple Canvas with two panels (divided vertically) shows the partial result (one camera texture per panel) I know this is cool, but not perfect yet, as the center of the rendered output shows clearly where a panel finishes and the other one starts. Look at the center of the rendered output above. The original inspiration video shows no perspective in the center, and I think that is the trick, but I cannot achieve that with an orthographic camera (or I don't know how). Do you know any approach to distort the camera or something similar, so the cameras are perpendicular in the middle of the scene (and only in the middle)? Are you able to think a solution to dissimulate the joint of both camera views? As a first approach (dismissed for the moment) I've tried to add another camera, perpendicular to the scene so there is no perspective in that point. Then I render its output in the UI in another panel on top of the previous ones. And it is not too bad, but again the joint is too obvious and now I have two joints instead of one
|
0 |
Click to move get NavMesh layer I'm using NavMesh, and NavMeshAgent for my character movement and Pathfinding. I made a testing NavMesh with 2 area layers 0 Walkable 3 Water. In have a click to move script, and i need to get the ID of the NavMesh Area where the player clicked. I tried to get the ID of the layer where the player clicked, using NavMeshHit.mask but is always resulting 0, even if I click where the NavMesh area ID is 3. From Unity documentation Mask specifying NavMesh area at point of hit. Script RaycastHit hit NavMeshHit nHit Ray ray Camera.main.ScreenPointToRay (Input.mousePosition) if(Physics.Raycast(ray, out hit)) bool hasHit NavMesh.Raycast (this.transform.position, ray.direction, out nHit, NavMesh.AllAreas) if (hasHit) Debug.Log ("Area ID " nHit.mask) targetPosition hit.point
|
0 |
How can I stop showing camera image in my Scene? Unity How can I stop showing camera image in my Scene in Unity? As you can see on the screenshot there is an image of a camera inside a player in the Scene view. How can I disable the image?
|
0 |
Updating game objects already placed in scene I have about 20 game objects placed in certain positions in my scene. I then realized i need to attach two additional game objects to each one of these as children. Is there a simple way of doing this? I really don't want to remove them all update the prefab and then place them back. Is there a way that i can add the two children to the prefab and all 20 something objects in the scene will also be updated?
|
0 |
JSON Parse (Invalid Value) My settings.json (generated with JsonUtility.ToJson) "masterVolume" 0.10000000149011612, "fullScreenMode" 1, "cheatsEnabled" false Offending line SettingsData sd JsonUtility.FromJson lt SettingsData gt (Application.dataPath " Settings settings.json") My SettingsData class. System.Serializable public class SettingsData SerializeField public float masterVolume SerializeField public int fullScreenMode SerializeField public bool cheatsEnabled public SettingsData(float masterVolume, FullScreenMode fullScreenMode, bool cheatsEnabled) this.masterVolume masterVolume this.fullScreenMode (int)fullScreenMode this.cheatsEnabled cheatsEnabled I really can't fathom why it's having trouble reading this back in, I even tried to save the enum as an int instead, but still no luck.
|
0 |
How to Subscribe to Events from Unity's VRInput Script I am new to Unity and trying to modify the Unity tutorial Interactive 360 Sample. I want to be able to call a function when a user swipes using an Oculus Go Controller. I noticed that the VRInput script is included in the project, which seems to be able to detect swipe gestures. But where do I attach that script, and how do I subscribe to the OnSwipe event. I am currently trying by making an empty game object, and attaching the InputVR script as well as my own script called "GestureHandler" (I'm not sure whether InputVR is already attached to something else in the sample project, or whether I need to attach it at all). In my GestureHandler script I currently have the following using System.Collections using System.Collections.Generic using Interactive360.Utils using UnityEngine public class GestureHandler MonoBehaviour void onEnable() VRInput.OnSwipe HandleSwipe void onDisable() VRInput.OnSwipe HandleSwipe void HandleSwipe() Debug.Log("swipe") and currently have the following errors An object reference is required for the non static field, method, or property 'VRInput.OnSwipe' Assembly CSharp No overload for 'HandleSwipe' matches delegate 'Action lt VRInput.SwipeDirection gt ' Assembly CSharp An object reference is required for the non static field, method, or property 'VRInput.OnSwipe' Assembly CSharp No overload for 'HandleSwipe' matches delegate 'Action lt VRInput.SwipeDirection gt ' Assembly CSharp
|
0 |
Null instance on manager class extending from singleton class I have four classes class A, which is abstract and partial extending from singleton class C. class A1, which is partial and extending from class A . class B, extending from class A. class C, a singleton which has code to throw an exception if the instance is null, and otherwise uses DoNotDestroyOnLoad(). In scene view, I add class B to the scene. It works, but throws a null instance exception for class A, as it's instance is not present in scene. I think this is because class A extends from a singleton class, and it has ability to throw exceptions when the instance is null. I can not add the class A to the scene because it is abstract. What can I do to in order to add the class A component to the scene, or otherwise not to get this error?
|
0 |
Using points to unlock next scene in Unity Below is my code and I'm a beginning game designer trying to make my first game for art school teehee! ) I'm not sure how to unlock the next level with a scene I've already made called Rust Room Any ideas? o I also attached the error codes I'm getting! using System.Collections using System.Collections.Generic using UnityEngine.SceneManagement public class Example HUD hud int points const int ScorePrefix "Score " int score public void LoadLevel() if ("Score 45") load the nextlevel SceneManager.LoadScene(SceneManager.GetSceneByName(Rust Room)().buildIndex 1)
|
0 |
How to lock aspect ratio when resizing game window in unity? I want a scalable game window that when resized stays at 16 9 aspect ratio. The goal is for the user to be able grab the window on the right or bottom and resize it. The game should adjust the corresponding side of the view port to lock the aspect ratio. I've tried forcing certain values in the update line of a script on the camera, but it did not work. the game is 2d and most of the elements are scripted using the gui functions. I'm having a very hard time finding exactly what I'm looking for as it is, most of what I've found is in an attempt to create black bars and keep the game from stretching, but that doesn't help ongui using matrices. here are the resources I've tried so far http goo.gl 8FuyRC this one is a script someone wrote that I attached to the main scene camera, I then built it, however that didn't work. http goo.gl qZ5DAl this is something from the unity website regarding camera aspect ratio. I put a line of code in the update function of my camera object pragma strict function Start () function Update () Camera.main.orthographicSize 3.596306 as well as pragma strict function Start () function Update () Camera.aspect 1 none of the above worked. http goo.gl MbTDcz was the last thing I tried, and it just made some more black bars... so far nothing has worked. not sure why. to reiterate, the goal I'm trying to accomplish is that, when the user grabs the edge of a windowed player, and drags it, the corresponding x or y axis will follow in suit to keep the aspect ratio the same.
|
0 |
Unity game crashing when dialogue with NPC initiated I have 3 NPCs in my "Game". When the player walks up to any of them, they're supposed to have their own dialogue I've tested this, and they do. I tried to create a display that shows this dialogue text using a TextMeshProUGUI attached to a blank GameObject called dialogDisplay (tagged DialogDisplay). There is one DialogDisplay object in the scene that I'm trying to get each of my NPC's to use. I tried to make the display object inactive in the NPC Start() function, and enable it when it's time to display the NPC's next sentence. When I run my game, I get an error on line 21, where SetActive() is called "Object Reference Not Set to an Instance of an Object". Here's the NPC script (DisplayNextSentence() is at the bottom, where dialogDisplay is used) public class NPC Character private bool charInRange public Dialogue dialogue public bool talkedTo false private Queue lt string gt sentences public TextMeshProUGUI textPro public GameObject dialogDisplay private bool isTalking Use this for initialization void Start () charInRange false textPro FindObjectOfType lt TextMeshProUGUI gt () dialogDisplay GameObject.FindGameObjectWithTag("DialogDisplay") dialogDisplay.SetActive(false) Update is called once per frame void Update () if player is in range and presses space, triggers NPC dialogue if (charInRange amp amp Input.GetKeyDown(KeyCode.Space)) TriggerDialogue() if Player gameObject is in NPC collider, player is in range void OnTriggerEnter2D(Collider2D other) if(other.gameObject.tag "Player") charInRange true if player exits NPC collider, player is not in range void OnTriggerExit2D(Collider2D other) if (other.gameObject.tag "Player") charInRange false if NPC has been talked to before, displays next sentence if not, loads dialogue and displays first sentence private void TriggerDialogue() if (!talkedTo) talkedTo true StartDialogue(dialogue) else DisplayNextSentence() loads a queue with lines from Dialogue and displays first sentence public void StartDialogue(Dialogue dialogue) sentences new Queue lt string gt () foreach (string sentence in dialogue.sentences) sentences.Enqueue(sentence) DisplayNextSentence() displays next sentence in the queue public void DisplayNextSentence() string sentence bool done false if last sentence in the queue, display it again if (sentences.Count 1) sentence sentences.Peek() textPro.text sentence Debug.Log(sentence) return sentence sentences.Dequeue() textPro.text sentence dialogDisplay.SetActive(true) while (!done) Debug.Log("In WHile Looop") if (Input.GetKeyDown(KeyCode.A)) done true dialogDisplay.SetActive(false) Grateful for any insight or tips you can provide. Happy to provide further information if it helps. Thank you!
|
0 |
Limit rotation angles for Quaternion I have a short snippet that's rotating the meshes of the wheels as I'm driving forward, but it's also rotating wheels to match the direction I'm turning, and I wish to turn this off completely. Quaternion quat Vector3 position m WheelColliders i .GetWorldPose(out position, out quat) m WheelMeshes i .transform.position position m WheelMeshes i .transform.rotation quat How would I lock what angles I don't want the wheel meshes rotating?
|
0 |
Screen Space vs World Space Canvas When should I use one over the other? I'm pretty sure I understand the key differences, but I'm not sure which use cases would prefer one over the other. For example, let's say I have objects on the ground in my 3D game and they have UI Images above them with the objects' names. Which method is better? Should I stick to world space for objects which are located in the 3D world and screen space for overlay type stuff?
|
0 |
Why do my animations need to be marked as "legacy?" I'm in the beginning of a project and I'm not really using 3D models but rather a hierarchy of primitive shapes. I made a couple of animations that suddenly don't work anymore. I get an error about that I need to mark them 'legacy'. I came across this suggestion to mark them as legacy in the rig tab via the model, but I'm not using a model so that doesn't help. I don't understand how the animations that I made in Unity yesterday don't work today? What is this legacy problem?
|
0 |
How to Change position rotation of a parent while keeping X and Z Rotation Sooo this question is a problem , a evolution by another solution of this problem here How can I change the parents rotation so the childs rotation is looking at a specific direction Basically We have a "Eye" (HTC Vive). We have a "Parent" which is the Parent of "Eye". We can not change the position or rotation of the Eye in code. We can only change the position and rotation of the Parent. 1.We want to modify the Parent Position so that Eye to goes to a certain "Target 1" position. 2.We want to modify the Parent Y Rotation so that the Eye looks at a certain "Target 2" position. 3.While doing this we dont want to modify the Parent X or Z , because this would lead to a Rotated game experience. The Parent Position changes so the Eye gets to "Target 1" position. The Parent Position changes so Y Rotation should look at Target 2 position The Parent X Z Rotation should not modify the Eye X Z
|
0 |
how to transform the position of an object I am trying to transform the position of an object. I have totally 3 Objects and 2 triggers, objects are 1. Left Wall, 2. Right Wall, 3. Obstacles. 1st trigger for transform the position of an objects y 50, 2nd trigger for transform the position of an objects y 7. Left wall and Right Wall are placed inside the environment. the environment will instantiate automatically for looping. if the player crossed the first environment previous environment will delete automatically. at that time in second clone environment if the player triggered means it will display a message as MissingReferenceException The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. In first Clone environment its working perfectly. second clone environment its not working.
|
0 |
Creating a custom Editor Window using a Multi Column Header Hey there I'm trying to use the MultiColumnHeader to create a tool to view materials in the scene, inspired by the light explorer. The problems I'm facing are two fold. First I can't figure out how to place the content of the MultiColumnHeader in a scrollable view and secondly I can't figure out how to give the rows a different background color that alternates like in the light explorer. This is my OnGUI code void OnGUI() windowVisibleRect.width position.width windowVisibleRect.height position.height draw the column headers var headerRect windowVisibleRect headerRect.height columnHeader.height float xScroll scrollPos.x columnHeader.OnGUI(headerRect, xScroll) draw the column's contents for (int i 0 i lt columns.Length i ) calculate column content rect var contentRect columnHeader.GetColumnRect(i) contentRect.x xScroll contentRect.y contentRect.yMax contentRect.yMax windowVisibleRect.yMax Rect rowRect new Rect(contentRect.x, contentRect.y, windowVisibleRect.width,20) for (int j 0 j lt analyzerList.Count j ) Rect MatcellRect columnHeader.GetCellRect(0, rowRect) Rect ShaderCellRect columnHeader.GetCellRect(1, rowRect) Rect GameObjectsRect columnHeader.GetCellRect(2, rowRect) rowRect.y 25 EditorGUI.ObjectField(MatcellRect, GUIContent.none, analyzerList j .mat, typeof(Material), false) EditorGUI.ObjectField(ShaderCellRect, GUIContent.none, analyzerList j .shader, typeof(Shader), false) analyzerList j .ShowGameObject EditorGUI.Foldout(GameObjectsRect,analyzerList j .ShowGameObject, quot Show quot analyzerList j .gameObjects.Count quot GameObjects quot ) if (analyzerList j .ShowGameObject) foreach (GameObject go in analyzerList j .gameObjects) GameObjectsRect.y GameObjectsRect.height EditorGUI.ObjectField(GameObjectsRect, GUIContent.none, go, typeof(Material), false) rowRect.y GameObjectsRect.height If a Editor GUI guru could explain to me how to do it like I'm a child that would be great ). I don't do custom GUI stuff and most of this is beyond me. As per requested I'm uploading two example images. One from unity and one I randomly found from the net. Note that I do not need the quot stacking quot (I dont know how to call them) headers from the second example. I do how ever require a vertical and horizontal scrollbar like in the second example. And finally just for reference this is what my code does so far
|
0 |
Gameobject with Canvas child (Unwanted inspector behavior) When I try to focus (by double clicking or pressing f) on gameobjects in my scene which have a Canvas as a child, the scene view zooms out to show the Canvas. I would like to be able to see the gameobjects themselves when focusing on them. Is there a way to do this?
|
0 |
Global variables in a multiplayer environment I would like to know what's the best approach to solve this problem. In a racing game, i need to create the final result chart. In a single environment i've tought something like private string arrivalOrder void playerArrived(string playerName) arrivalOrder arrivalOrder.getLength() 1 playerName I would like to know how to do in a multiplayer environment. How the client can communicate to server "my player finishes the racing"? Thanks
|
0 |
Is it possible to use an SVG as a texture for a 3d object? I'm using the Vector Graphics plugin for Unity 2019 and am able to drag an SVG into the scene. However, I am not able to drag it onto a 3d object as I am with a PNG. My goal is to make 3d cubes that rotate with a particular icon on each side of the cube. I came across this related post SVG textures for 3D game objects in Unity? but I'd like to make sure there haven't been any advancements since 2017 in this area. Also, would it be possible to add an SVG to a material? I can't figure out a way to do it but I am not very experienced with Unity.
|
0 |
Serialize classes based on Generics. Is it different? I have a certain ScriptableObject. public class Biome ScriptableObject ... If I write the following in a component public List lt Biome gt list1 This is what appears in the inspector So far so good. But if I try to make my list more generic, like this public class DistributedList lt T gt public List lt T gt items System.Serializable public class BiomeList DistributedList lt Biome gt This is what I get on the inspector All I can seem to be able to add now is just a name, not the Object itself. Why is this?
|
0 |
Quaternion.Lerp does not actually rotate object when called inside an "if" clause Let's say I have a RotatableObject class, which inherits from MonoBehaviour. Here is its Start() method private void Start() this.startingLocalRotation this.transform.localRotation this.finalLocalRotation Quaternion.Euler(this.startingLocalRotation.eulerAngles.x, 150f, this.startingLocalRotation.eulerAngles.z) Initialize other private fields It has a method called Rotate(), defined as follows private void Rotate() this.transform.localRotation Quaternion.Lerp(this.startingLocalRotation, this.finalLocalRotation, 0.2f) Given the following Update() method, the object rotates as expected private void Update() this.Rotate() However, if I make the following changes to Update(), then the object does not actually rotate, even though the Rotate() method is hit private void Update() if (this.SomeCondition) this.Rotate() this.SomeCondition always has the value true over multiple frames. What is my mistake, and how can I fix it? EDIT In response to this comment When you say "the object rotates as expected" do you mean that the object rotates from starting angles until final angles and then stops rotating (without the if) ? Yes. could you provide some more details about what SomeCondition is? this.SomeCondition is determined by the state of another object, say, Puppy. E.g. if puppyInstance.Mood Mood.Happy, then this.SomeCondition is true. Did you try replacing the condition with the word true No, I have not tried that. However, when stepping through the call stack in debug mode, I can see that this.SomeCondition is true and Rotate() is called I managed to step into the Rotate() method itself. EDIT I tried the first approach described in this answer. However, it did not produce the effects that I was aiming for. I set a breakpoint here transform.localRotation Quaternion.Lerp( startingLocalRotation, finalLocalRotation, rotationProgress ) Every single time the breakpoint was hit in the Update() call, I could see that the value of rotationProgress was steadily increasing. However, the value of transform.localRotation never actually changed it was always ( 0.7, 0.7, 0.0, 0.0). If I updated transform.localRotation outside of an if clause, however, that game object rotates as expected transform.localRotation gets updated as rotationProgress gets updated. EDIT Never mind, I am an idiot. The problem lies elsewhere in the code. The suggested approach works and I have accepted it as the answer.
|
0 |
Unity's CharacterController vs. Rigidbody with Collider With a few friends I started to make a 3D game in the style of the old platformers la Super Mario 64 Spyro Banjo Kazooie. So now we are thinking about the controls and how to do them. There seem to be two mutually exclusive options Giving our character a rigidbody and however many colliders we want OR using a character controller. At the moment we have a rigidbody with a collider which technically works, but we have to make our own grounded check, and movement, while those two in particular are relatively easy to implement. If we start to use a character controller OTOH, we won't have all the collisions anymore and programming logic needs to be applied in a different way. Let's take a jumppad as example If we use a Rigidbody, the jumppad itself checks if someone is standing on it, and if so it increases the jumpstrength while that someone stands on it. If we use a CharacterController, we'd have to check not only if we are standing on a jumppad, but also on which one, to determine the actual jumpstrength, as they might differ between pads. So, is there a clear winner to use in a 3D platformer with fighting elements or do we have to work with limitations on either and just have to work around them?
|
0 |
How to detect a sign out from Google Play achievements or leader boards UI? I am making an android game in Unity (C ), in which I've used the Google's official plugin for Google Play Services. My question is how to detect that a player has clicked on sign out button on Google's UI
|
0 |
Player is instantly teleported back I built a teleporter that changes a players position and rotation. He is instantly teleported back. Why? I'm using the standard FPS Controller.
|
0 |
What the difference between public int and int? I was trying to understand the difference of int and public int by checking how unity respond to it using UnityEngine using UnityEngine.Assertions.Must using UnityEngine.SceneManagement public class Bird MonoBehaviour int CurrentState 1 int PreviousState 1 Void Update() (if CurrentState ! PreviousState) transform.localScale new Vector3(transform.localScale.x 1,transform.localScale.y 1,transform.localScale.z 1) Since the equality is false, the scale of object remail unchange and in my next step, I changed quot int CurrentState 1 quot to quot public int CurrentState 0 quot and quot int PreviousState 1 quot to quot Public int PreviousState 1 quot . Isn't that this time, the equality is true as 1 ! 0 but the scale of object remained the same. Once I deleted the word quot public quot on both currentstate and previousstate, the scale increase indefinitely. I thought the word quot public quot basically meant there no access restriction but why it looks like the quot if quot statement couldn't retrieve the info correctly?
|
0 |
Cinemachine third person camera movement causes misalignment I'm working on third person movement using CinemachineFreeLook as the player camera. At first I thought it was working fine but I've noticed that moving left right actually moves the character with a curve instead of straight left right. This behavior can be observed in the following video https imgur.com sLGIia8 As you can see when trying to make the character move left right the character doesn't stay on the grid but instead curves a bit to the left right. I'm inclined to believe that this occurs because of cinemachine camera but I am unsure what exactly is going on and how to fix this. I feel that this is a bit over my head and am thus asking for help in figuring this out. The simplest form of movement code is as follows (the exact code that moves the character in the video) private void FixedUpdate() Vector2 input playerInput.MoveInput bool hasInput Mathf.Abs(input.x) gt float.Epsilon Mathf.Abs(input.y) gt float.Epsilon if (hasInput) get camera direction Transform cameraTransform Camera.main.transform Vector3 cameraForward cameraTransform.forward Vector3 cameraDirection Vector3.Scale(cameraForward, Vector3.right Vector3.forward) transform camera direction vector to a quaternion Quaternion cameraRotation Quaternion.LookRotation(cameraDirection) transform input vector2 into x z vector3 Vector3 inputDirection new Vector3(input.x, 0f, input.y) create desired velocity from input and current camera rotation Vector3 desiredVelocity cameraRotation inputDirection settings.Speed Vector3 delta desiredVelocity body.velocity delta.y 0f Vector3 acceleration delta Time.deltaTime if (acceleration.sqrMagnitude gt settings.SqrMaxAcceleration) acceleration acceleration.normalized settings.MaxAcceleration body.AddForce(acceleration, ForceMode.Acceleration)
|
0 |
read in an xml server from Unity3D 4.xx I need examples of how to read an xml from a server, using Unity3D.. I think it's something like this.. but I can not retrieve the information from the nodes.. An example would be of great help.. thank you.. var url "http server.com test2.xml" var www WWW new WWW (url) yield www var xml XmlDocument new XmlDocument()
|
0 |
Avoid players getting stuck by placing items in the same place Let's assume a multiplayer game of two players. These two players have to place six elements at six different positions. The order or exact place does not matter. As the items are placed correctly, they cannot be replaced anymore. Issue Both place an item at the same position and now there are basically two items at a position where only one should be. This makes the task impossible to complete, as one item is missing now for the last position. My assumption is that while both are really doing that in parallel, the communication between both computers is too slow so the other player can't know there is already an item. I encountered this issue in a game recently and I wonder how to avoid this. The simplest solution would be that the items can be replaced when placed. But let's see it more technical A correctly placed item cannot be replaced so how to circumvent or how to avoid this situation?
|
0 |
Flatten transform hierarchy at build time Nested hierarchies cause a performance overhead when they include moving objects. Every time a GameObject moves, altering its transform, we need to let every game system that might care about this know. Rendering, physics, and every parent and child of the GameObject needs to be informed of this movement in order to match. As the scope of a game increases, and the number of game objects skyrockets, just the overhead of sending out all these messages can become a performance problem. However, nested hierarchies are useful in organising a scene and keeping logical groups of gameobjects separate. What options exist to save performance whilst keeping the hierarchy? Is there any pre existing solution to flatten a hierarchy when building only?
|
0 |
How to physically move a rigid body up the stairs? When an object is controlled by a CharacterController, it is easy to make it climb ramps with a certain slope, or climb steps with a certain height. When the object is controlled by a RigidBody instead, it can still climb ramps naturally I just use AddForce and it walks on ramps just like on any other surface. I do not have to add any special logic for a ramp. However, it does not climb stairs. Is there a natural "physical" way to make the RigidBody climb stairs, without explicitly checking that there are stairs ahead?
|
0 |
Physics2D.IgnoreCollision not work when rb not moving I want to use Physics2D.IgnoreCollision for ignoring collision between enemy and player, when player have shield. But I have enemy who some time is static and some time jump only on y axis. When enemy not moving Physics2D.IgnoreCollision not work and physics collision between player and enemy occur even Physics2D.IgnoreCollision is called. When i add some velocity to enemy in update method Code (CSharp) rb.velocity new Vector2(0.1f, rb.velocity.y) IgnoreCollision work like it should. Can some one tell me why this happens? Thanks
|
0 |
How to make switch work with enum? C Unity I'm working on a script to fade UI elements in Unity, similar to a selector, where you can select the type of fading, and duration, and image to fade I found that enum is the best option to achieve that result, but I have a problem, when I run the code only element of the enum work and the other don't, no matter if I use switchor if just the first statement run, I don't know what's wrong with the code Please explain your answer Please explain why the code is wrong Please give feedback on how to improve I'm using Unity version 5.3.5f1 and Visual Studio Community 2015 Goal Make the enum work properly using either switch or if Be able to use the variables inside the FadeOperations class to make the calculations inside the Test class Select from an array the type of desired operation Select an UI element from Heriarchy and fade it Steps Create new Unity project (2D or 3D) Create UI Image Create Empty game object Create new C script (I called it Test) Attach new script to empty game object Code Here's my code so far... using UnityEngine using UnityEngine.UI public enum FadeManager fadeIn, fadeOut System.Serializable public class FadeOperations Tooltip("Type of fading") public FadeManager fadeType Tooltip("Duration time of the fading") public float duration Tooltip("Select the image to fade") public Image fadeImage public class Test MonoBehaviour Tooltip("Select your type of fade") public FadeOperations fadeOperations Reference to the class FadeOperations private FadeOperations fo new FadeOperations() Loop for debug private void Update() switch ( fo.fadeType) Debug.Log( fo.fadeType) This statement works case FadeManager.fadeIn Debug.Log("Fadein") Only this piece of code works break This statement doesn't work case FadeManager.fadeOut Debug.Log("Fadeout") break The result of the Log ( fo.fadeType) before the switch fadeIn UnityEngine.Debug Log(Object) Test Start() (at Assets Scripts Test.cs 34)
|
0 |
UI clicks hitting game objects below I have a canvas with a panel with set width height inside. The canvas rendermode is set to ScreenSpace Overlay. My clicks on the panel are falling through and hitting the game objects below triggering their mouse events. The little green circle is a Sprite with the following event public void OnMouseDown() Debug.Log("click") Vector3 newPos Camera.main.WorldToScreenPoint (this.transform.position) newPos.x panel.GetComponent lt RectTransform gt ().rect.width 2.0f newPos.y panel.GetComponent lt RectTransform gt ().rect.height 2.0f panel.transform.position newPos I've been reading through the docs but I'm missing something... How do I stop my clicks hitting the game objects below the panel?
|
0 |
StartCoroutine from other MonoBehaviour is not working I am trying to replicate the model of Unity documentation about coroutines, but I want to partition it in another class I have these two public class A MonoBehaviour void Start() print("Starting " Time.time) B test new B() StartCoroutine(test.WaitAndPrint(2.0F)) print("Before WaitAndPrint Finishes " Time.time) public class B MonoBehaviour public IEnumerator WaitAndPrint(float waitTime) yield return new WaitForSeconds(waitTime) print("WaitAndPrint " Time.time) It prints, ignoring the coroutine Starting 0 Before WaitAndPrint Finishes 0 The two methods work well in the same class.
|
0 |
How to capture image from camera with post effects? Mysteriously only get emission(?) pass I have a separate camera from my main camera, whose purpose is to take screenshots, or render a quot live feed quot of the action, at different angles. Hierarchy as such The game object labeled as quot main camera quot captures the 3D scene just like a normal main camera would, including post processing components. The GUI camera captures just the UI layer. The canvas and image are simply a watermark, rendered by the GUI camera. I have removed this and it has no bearing on the issue at hand. I point both the main camera and GUI camera to the same target render texture. The result of the render texture appears to be correct in the inspector. One way or another, it appears that I can only get access to the quot bloom, quot and nothing else (On black so it's easier to see.) If I assign the render texture onto a Raw Image canvas element, it only shows the quot bloom. quot If I try to convert the render texture to a regular texture, it also only shows the quot bloom. quot RenderTexture.active renderTexture destination.ReadPixels(new Rect(0f, 0f, renderTexture.width, renderTexture.height), 0, 0) destination.Apply() (I have also tried AsyncGPUReadback. Its resulting texture looks like a flat gray without variance in the inspector.) I have found if I disable post processing, everything works as intended, no changes required. Of course, I am missing the post processing, which I want! Somehow, somewhere, Unity is getting data external of the texture itself, depending on context Using Unity's ReadPixels method only picks up the quot bloom. quot Using Unity's EncodeToPNG method only picks up the quot bloom. quot Putting the RenderTexture on a Raw Image only picks up the quot bloom. quot If I use a separate PNG encoder using the same Color32 data, I get the final correct image. The inspector successfully renders the final correct image. I have actually run into this issue multiple times, and never found a proper solution, and definitely never a real time solution, which I now desperately need.
|
0 |
In Unity Move a GameObject at Animator State I want to move one of my GameObject to a different vector 3 position, when animator transit to a new state. How do I do it? Also there shouldn't be any delay.
|
0 |
How to force Landscape Mode Unity3D Android Game? I am developing a small side project on Unity that will ultimately be for Android but I cannot figure out how to force landscape on the device and when I have tried it out the game just goes all over the place! I am using Unity Canvas and have spent a long time with binding position points etc. but I cannot work it out! Could someone please tell me how to force the phone into landscape mode?
|
0 |
.NET Framework version is fixed for Unity scripts? It seems that the C project that Unity creates uses version 4.7.1. But I want to use only the latest version and do not want to install lots of older versions of .NET Framework targetting packs that I do not use. Even if I change the version to 4.8 and save the project, if I add a new script asset, then the version changes back to 4.7.1. So, my question is, do I have to use the version that Unity sets by default? Or is there a way to make Unity always use the latest .NET version such as 4.8, in this case? If the answer is the former, I will give up and install 4.7.1.
|
0 |
Score does not increment by 1 in Unity I have made a simple code where once the player moves through the collider that acts as a trigger then Unity adds a score. However, it increases by increments of 8 and I am not sure why. using System.Collections using System.Collections.Generic using UnityEngine public class Game MonoBehaviour public int Score 0 void Start() Update is called once per frame void Update() private void OnTriggerEnter2D(Collider2D other) AddScore() void AddScore() Score
|
0 |
How to export a terrain from Unity to Blender? I'm trying to make an environment for my scene that consists animations and other objects such as trees. Making a terrain in Unity seem to be a lot easier than in Blender, so I want to export that environment which I've made in Unity to Blender. How can I do this?
|
0 |
What would be the best way to implement a multi directional "board game" movement system? I'm pretty new to game dev, and can't figure out how to do this, even though it is probably really easy. If you need more reference, look up some gameplay of the Wii game Dokapon Kingdom, that's the kind of system I'm trying to create. I also made a picture to help you better understand my dilemma. Thank you all so much in advance!
|
0 |
Unity 2D map and walkable collisions I have a 2d player who can only walk on black area. There is a red collider so player can't walk past it. Player has capsule collider. The problem is player can't walk toward the edge with his feets becasue of the it's collider. But player would probably want to walk toward the edge. Here is a sketch I've made. Is there a way to tweak this ?
|
0 |
Smooth Scene transitions with SceneManager and additive scene in Unity I'm trying to work with the new SceneManager class with Unity, I'd like to have smooth transitions between scenes. Currently I suppose that the only way to do those transitions is to manually implement them on the scene objects leveraging on the fact that scenes can be loaded additively. In pseudo code I image something like for gameObject in previousSceneGameObjects gameObject.animateSceneExit() endFor for gameObject in nextSceneGameObjects gameObject.animateSceneEnter() endFor I feel that there is something I'm missing P which is the best approach that you'd suggest? Is it my approach valid?
|
0 |
Strange momentum on projectiles shot out of "parent" object I'm trying to shoot a projectile out of a moving quot parent quot object. Both objects move off of rigidbody physics, so I'm using addforce for the projectile. Whenever I move the quot parent quot object and turn while it's moving and shoot the projectile, I instantiate the projectile, copy the projectile spawn position to the projectile's position, copy the rotation of the quot parent quot to the projectile, then add force to the projectile. It'll shoot but I notice it moves in the direction of the momentum of the quot parent quot rather than straight forward from where it was created. I'm pretty sure this is just me not understanding how rigidbody physics works for adding force but if anyone has any suggestions as to how to make the projectile move straight forward from where it's created rather than copying the momentum of the parent I'd appreciate it greatly. My code for moving and creating a projectile looks like this void FixedUpdate() if (Input.GetKey(KeyCode.W)) player.transform.Translate(Vector3.forward 10f Time.deltaTime) this.GetComponent lt Rigidbody gt ().AddForce(transform.forward 15) if (Input.GetKey(KeyCode.S)) this.GetComponent lt Rigidbody gt ().AddForce(transform.forward 15) if (Input.GetKey(KeyCode.A)) transform.Rotate(Vector3.up 15 Time.deltaTime) if (Input.GetKey(KeyCode.D)) transform.Rotate(Vector3.up 15 Time.deltaTime) void ShootBullet() create bullet GameObject bullet Instantiate(bulletPrefab) set location where bullet will spawn from bullet.transform.position bulletSpawn.position set direction of the bullet bullet.transform.rotation bulletSpawn.transform.rotation add force to the bullet bullet.GetComponent lt Rigidbody gt ().AddForce(bulletSpawn.forward bulletSpeed, ForceMode.Impulse) destroy bullet after x time Destroy(bullet, lifeTime)
|
0 |
Unity3D How to just center a mesh inside a character controller! Hi I have a simple character mesh and it's parented to my character controller invisible capsule object and all the moving code is applied to the parent (if that's relevant), but the point Is I'm trying to line up the mesh to be exactly inside the capsule to make it look like the player is walking ABOVE the ground (pretty normal ...?) So by default the character controller is origined in the center so I move it up by half of it's height to try to get it to line up with the character mesh, which has it's origin below it's feet a little, and this is the result as you can clearly see, his feet slightly go into the ground, I have no idea why this is happen, then should be just above the ground like any other normal feet! Here's the code for setting the capsule up half of it's width, since it starts by lining up the mesh in it's CENTER for some reason Vector3 tempPos player.transform.position tempPos.y (capsuleSize.y 2) chassidSize.y 12 chassid.transform.position player.transform.position player.transform.localPosition tempPos chassid.transform.parent player.transform and here's a picture of the mesh (which is just a blender file, easier for import) As you can see, in the blender file, the origin is slightly below the characters feet, IN THE CENTER, so I don't know why it's not working as planned. Also, you can see in the first picture that he's slightly moved to the center of the controller on the z(?) axis, but I want him to be completely centered in, any idea how to fix this?
|
0 |
Why does using .Lookat() cause the enemy to look left instead of at player, and how can I fix it? I am new to Unity. I have searched but I couldn't find any answers on this. Here is my code somethingPosition new Vector3(player.transform.position.x, transform.position.y, player.transform.position.z) transform.LookAt(somethingPosition) The somethingPosition only allows rotation of the Y axis so. Anyways, I have this script on the enemy AI. The issue is this the enemy looks at the player but looks to the left of the player. The same issue occurs when I have my follow code happen transform.position Vector3.MoveTowards(transform.position, player.position, speed Time.deltaTime) The enemy will continue going to the left of the player but will not hit the player. What are some suggestions you guys can survive? Thanks! I am aswell using a NavMesh and NavMeshAgent
|
0 |
For creating a distant moon in a 3D game, is it better to use a model or texture? I'm working on my indie game and I want to create a moon (it's a 3D game) however I am unsure if I should create a model and put it far away, or if I should use a texture on a plane and have it constantly move so the face of the plane is facing the player. The problem I had last time I tried a model is the render view, as the model was really far away (as when I did it very small, you could sort of tell it was a tiny model rather then a far away moon) and with the texture I'm not sure if it comes across as tacky. I'd really like to hear the pros and cons of each, since I'm planning to use the 'render objects only when in view' method and basically want advice on which I should go with.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.