_id
int64
0
49
text
stringlengths
71
4.19k
0
How do I raycast to detect which hexagonal tile was clicked? I want to detect the hexagonal tile a unit is on upon clicking on the unit. I was thinking of using a ray cast I can't get it to work. I'm trying to get the raycast to shoot from the bottom of the unit and change the material of the collided object. if (Input.GetMouseButtonDown (0)) Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hit if(Physics.Raycast(ray, out hit)) Debug.Log (hit) string hitTag hit.transform.tag if(hitTag "player") if(Physics.Raycast(user.transform.position,Vector3.down,10)) Debug.Log ("I'm on something!") hit.collider.renderer.material.color Color.red What might be going wrong?
0
Unable to add button in Unity I am wanting to add a button to my scene in order to mute unmute music. I can add the button to my scene, but it's not appearing on the UI. I can't see it anywhere, not on the scene nor the game when running. Below is a screenshot of the editor. You can see the button in front of the camera and in front of the scene itself, but it doesn't appear. I can't actually see a button, just a 'move' control'. Things I have tried Changing the 'Layer' of the button to default Adjusting the z axis (I've tried 0, 1 5, 1 5) Giving the Image (Script) a material inside the Inspector The button has text, which isn't visible either. I could create a sprite and do a raycast, but that seems like overkill just to do a simple click action. Any ideas?
0
Unity How to add bones to procedural mesh Basically this is the set up An N amount of prefabs are bundled together into a new GameObject. This is then merged into a single main mesh composited of M amount of material submeshes. The shape is standing upwards on the Y axis and is a bunch of arms. The goal is to move these by adding bones. I wasn't able to find many examples on how to properly assign bones to a procedural mesh which isn't a simple cube. The problem is assignment of vertices to the boneweights. I'd like for the transform Y 0 vertices to have no weight and the Y furthest vertices have full weight. I am not sure how the assignment should be done.. Any pointers? ) So far the Lower and Upper bone transforms are in the right place, but when moving them the mesh isn't bending as I hoped it would in a nice curve, half of the vertices are simply moved uniformly with a thin mesh line connecting the two halves. private void AddBones() if(m SkinnedRenderer ! null) Make bone weight for vertices BoneWeight weights new BoneWeight m MainMesh.vertexCount int halfway (weights.Length 2) for (int i 0 i lt weights.Length i ) if(i lt halfway) weights i .boneIndex0 0 weights i .weight0 1 else weights i .boneIndex0 1 weights i .weight0 1 m MainMesh.boneWeights weights Make bones and bind poses Transform bones new Transform 2 Matrix4x4 bindPoses new Matrix4x4 2 bones 0 new GameObject("Lower Bone").transform bones 0 .parent m MergedRoot.transform bones 0 .localRotation Quaternion.identity bones 0 .localPosition Vector3.zero bindPoses 0 bones 0 .worldToLocalMatrix m MergedRoot.transform.localToWorldMatrix bones 1 new GameObject("Upper Bone").transform bones 1 .parent m MergedRoot.transform bones 1 .localRotation Quaternion.identity bones 1 .localPosition new Vector3(0, 1.5f, 0) bindPoses 1 bones 1 .worldToLocalMatrix m MergedRoot.transform.localToWorldMatrix m MainMesh.bindposes bindPoses m SkinnedRenderer.bones bones m SkinnedRenderer.sharedMesh m MainMesh m SkinnedRenderer.rootBone bones 0
0
Detecting Left and Right Mouse clicks on UI Text objects that are dynamically created So, in my game I create a bunch of UI Text game objects dynamically (in the C script), but I just can not find out how to properly detect Left and Right mouse clicks on these UI Text that were dynamically generated. I have tried adding Colliders and Colliders2D to the UI Text game objects for raycasting, but with no luck. And differently from UI Button, it seems that Unity has left proper "on mouse click" functions out from UI Text Can anyone help out on how to accomplish that? PS no, I can not use UI Buttons, it has to be Texts. And the UI Texts have to be generated on the fly, not in the editor
0
Issue calculating new angle for player to look at some 3d world object I am working on a Unity game where the Euler angles of the player display some weird behaviour that I cannot understand. There seem to be two full 360 degrees rotations, one positive and one negative. Depending on the direction you go when you are at 0 degrees, it will either take the negative path or the positive path. This means the player can have totally different yaw values depending on if it takes the green or red path. See the following image to get an idea of what is happening The issue now comes when I want to calculate the new angle for the player to look at some specific object in the 3d world space. I calculate this angle using some simple math make player the origin, so the target is relative to the player Vector3 delta player.angles target.angles float magnitude delta.Length() float pitch asin((delta.y) magnitude) (180 M PI) float yaw atan2(delta.x, delta.z) (180 M PI) This will give me back correct angles, but the yaw is from 0 to 180, then 180 to 0 again. I correct for this doing this makes sure the calculated angle is from 0 360 if (yaw lt 0) yaw 360 normalize yaw So, right now this is aligned with the red rotation line illustrated in the picture above. If I would set the players rotation to the new calculated angle, it would look correctly at the target object directly. But ONLY when the player is on the red rotation path. If the player for example is on the green rotation path the calculated angle doesn't fit for the current users rotation. If I would set the rotation now, things get quirky. Somehow I need to compensate the calculated new player angle. What is going on here? and is it possible to manipulate the new calculated angle (which ranges always from 0 360) so it is based on the current players rotation path (either green or red)? I hope my question makes sense, I found it quite hard to follow what is going on. I hope someone could explain me the situation and ultimately help me out to fix the new calculated angle so it adjusts to the current player rotation path! Any help is appreciated, thanks in advance! EDIT So I came up with the following to make sure the player is always rotated the shortest amount, taking both green and red rotation paths into consideration normalize angles for when using negative rotation if (localAngles 1 lt 180) angles 1 360 double diffPitch (angles 0 localAngles 0 ) double diffYaw (angles 1 localAngles 1 ) this makes sure we always take the shortest amount of degrees to target if (diffYaw lt 180) diffYaw 360 if (diffYaw gt 180) diffYaw 360 I will have to test some more to be sure this is the solution.
0
How do I fix the YAML error in Unity 5? I'm using Unity 5 and I'm getting an error in a YAML file. The error is "Unable to parse YAML file mapping values are not allowed in this context at line 1" This comes up every time I open the engine. I've seen some say to open the YAML file and change some stuff in it. But I can't even find the YAML files. I've also seen that it's caused by meta file issues and version control. The project is local but I don't know if it matters if it's local or cloud based. Does anyone have a solution for this issue?
0
How can I toggle enabled on a specific script within an object in Unity? I have the CarController script inside my car GameObject. I need to set it to disabled at the start so the countdown timer can start the race. I thought I knew how to do it but once again I have failed Any ideas why this doesn't work?? void TogglePlayerEnabled(bool b) playerCar.GetComponent lt CarController gt ().enabled b void ToggleAiCarEnabled(bool b) aiCar.GetComponent lt CarController gt ().enabled b If I use a print line saying "Toggled" or something, that appears in console as expected. But the CarController script seems like it stays active as both me, and the AI car can just drive whilst the countdown is happening still. Here's the full class public class GameManagerControl MonoBehaviour public GameObject playerCar public GameObject aiCar public int sceneChangeZValue private string countdown "" private bool showCountdown true Use this for initialization void Start () Update is called once per frame void Update () TODO This will change the scene when the track ends. if (player.transform.position.z gt sceneChangeZValue) SceneManager.LoadScene("race track lake") if (showCountdown) StartCoroutine(GetReady()) call this function to display countdown IEnumerator GetReady() countdown "3" TogglePlayerEnabled(false) ToggleAiCarEnabled(false) yield return new WaitForSeconds(1.5f) countdown "2" yield return new WaitForSeconds(1.5f) countdown "1" yield return new WaitForSeconds(1.5f) countdown "GO" TogglePlayerEnabled(true) ToggleAiCarEnabled(true) yield return new WaitForSeconds(1.5f) showCountdown false countdown "" GUI void OnGUI() if (showCountdown) GUI.color Color.red GUI.Box(new Rect(Screen.width 2 100, 50, 200, 175), "GET READY") display countdown GUI.color Color.white GUI.Box(new Rect(Screen.width 2 90, 75, 180, 140), countdown)
0
Unity game crashes when opened on some computers but not all I'm facing a weird issue where every time I attempt to run a Unity application, it just crashes with no error message or log being generated. I tried running the game, it works on some computers (3) but fails on most (35). Upon attempting to run the application, I get a box that pops up for a second with a red exclamation point, which then crashes. See screenshot below I have found people having similar problems, but no real solution. https forum.unity.com threads solved crash when running any unity application.599953 https forum.unity.com threads crash when opening any unity application.873133 My game is made in Unity (v2018.1.9f2). Attaching the error logs for your reference. Unfortunately, I do not have the admin privileges to try the citrix solution in lab computers (since they are controlled by the University office). Error logs https pastebin.com mcMaD9im https pastebin.com M0e9a9GG https pastebin.com DSRrU8bZ
0
Unity3d iOS build restarts when regaining focus from browser I have an app made in Unity3d for android and iOS. In it, the user has the ability to link their accounts with Facebook and Twitter. For Facebook I use their Unity plugin, for Twitter, I open an external browser page that lets them accept or decline Twitter integration that then redirects to a php page the calls the app URI to return focus to Unity. On Android this all works perfectly using an Intent in the Manifest. In IOS I'm running into issues though and I don't really know my way around XCode. I'm using the newest version, XCode 7 Beta 2. The App runs as expected but for both the Facebook and Twitter authentications, upon returning focus to the App from the Browser, it completely restarts the App as if just launched rather then returning from a suspended state. In the Unity build I have "Run in Background" selected. I setup the URL Scheme in XCode. Its a pretty basic app so I don't think its being closed due to Memory usage. Any ideas or any settings I can change in XCode that might be preventing it from resuming? Note, if I just hit Home and send the App to the background it will properly resume, its only when called by the URI from the browser that it seems to completely restart.
0
Accelerometer input for flying game I'm trying to create an infinite flying game where the gameobject (a plane) keeps moving forward and at a particular height throughout the game. I want to be able to roll and pitch the plane but not move it up down. I added a rigid body to the plane and selected "y" position constrain. However the plane doesn't stay in the 'y' position but starts move up or down. I just have a script that translates the plane in the z direction. Not sure how to implement the mobile input and keep at the same "y" position throughout. Update Here is the code for the plane. Its very basic as I'm not sure how to use the accelerometer public class Player MonoBehaviour public float speed 1.0f void Update () float tempx Input.acceleration.x float tempy Input.acceleration.y float tempz Input.acceleration.z transform.Translate(0, 0, 10) move forward in z transform.Rotate( 0, tempy speed, tempz speed) As for the freezing of the 'y' position, I'm just selecting the y constraint available in the inspector that comes along with the rigidbody.
0
How can I create a custom PropertyDrawer for my Point struct? I created a Point struct System.Serializable public struct Point public int x public int y I am trying to create a property drawer for it, so that when it shows in the inspector, it is shown in a Vector2 field. I have the following script in the "Editor" folder using UnityEditor using UnityEngine CustomPropertyDrawer(typeof(Point)) public class PointEditor PropertyDrawer public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) EditorGUI.Vector2Field(position, label, property.vector2Value) It shows up in the inspector the way I want, but the values are locked at 0. Basically, I am trying to access the Point instance from inside the OnGUI method, but this could be the completely wrong approach. How can I make this so that when the values are changed in the inspector, the respective Point is also changed?
0
How do you make the first person object the main camera? How can a first person object character be made to be the primary viewing camera in unityscript? Do I remove the main camera? or just turn one or the other on off?
0
Move camera around player while facing player My player has the following hierarchy Hero (GameObject) Model (child of "Hero", centered at 0 0 0) Camera (child of "Hero") The camera should be allowed to change its position around the Model in a circle ("rotate around the center") rotate so that it always faces the Model move up and down move nearer and further from to the Model I know how to do that using Quaternions, but as I'm doing this in a coroutine and using Lerp, I found myself in situations where the camera would get right through the model as this was the shortest path between the destination and the target vector. I would now like to use pure angles (Sin and Cos), preferrably without LookAt. Can somebody share how I would position and rotate the camera according to the angle, perhaps even taking a camera height variable into account as the camera should also be able to move up and down, still facing the player? That would be the bomb!
0
Why can't I play 2 animation track at the same time in Timeline for additional Camera? I try to move and rotate camera at the same time in timeline. To do this, I added two animation track to camera. One animation track changes position of the camera. And the other one changes rotation of camera. But they are not working at the same time. When I press quot preview quot button, only rotation of camera changes This video may help understanding if question is not clear https vimeo.com user133731359 review 517045792 43b6c6ec49
0
Can ARToolKit be used for color detection? I'm trying to make an app that will show an object from different sides, but the target will be too small for any real marker detection. Think of a cube with one or two centimeter sides. The camera distance is not a problem but it has to be at least ten centimeters out or what I'm trying to do won't work. I was wondering whether it was possible to color one side of the cube differently than others and make ARToolKit recognize the color to know which side it's looking at. Is this possible or just not in the range of things ARToolKit can do? If so, is there any kind of AR that can do this.
0
Performance problem when multiple enemies are grouped up I have enemy with simple behavior Reach the player's current position. In game are increasing waves, which are increasing the number of enemies. But when are more enemies (like 14), and they got too close to each other, there is big physics spike in profiler. There are significant drop of performance... And as Profiler says, it's because of Physics... Now I am little lost, I tried turn of the ignore collision on layer (which was turned on), so they don't overlap, but there is still little touch of course, when they group up, so still so much to process... What is the best solution here? I build it around rigidbodies for the use of Velocity, and detection of collisions with walls (edge collider), so when the object reaches there, it is easily stopped... But for this cases it seems now like not the best solution.
0
How to force play area corners to Lighthouses in Unity I'm working for a guy that wants to recreate real environments in VR and superpose them for business demos. Think of one of those mall kiosks where you "enter virtual reality" and at first it looks exactly the same as regular reality until you start interacting with objects and the virtual elements start being superposed. Basically, AR in VR. To do this, I have an exact model of the kiosk, but I need to be able to force the play area in vive and unity to be always the same and equal to the dimensions of the real space, so that my model can superpose the actual world objects. Is there a way to force the play area to be the same as the distance between the lighthouses? Additionally, is there a way to force the lighthouses to never recalibrate after the initial setup(as it does when someone moves in front of them for example)?
0
Rotate an object on itself, from one random Quaternion to another I have a situation I have a 3D object in the world. let's say a sphere. I have 2 random directionnal vector vector A, and vectorB My question is How to I rotate over time my object, from A to B ? The vector A is important I don't want to simply rotate the forward of the object from current forward to B. I know I can use the function vector3 C Vector3.SmoothDamp(...) in unity to lerp between my 2 vectors A amp B. but then ok, I have vector3 C, how do I apply the rotationof my object to C ? if don't want to do gameObject.transform.forward C I want something like gameObject.transform.rotation SomeQuaternion(C, initial rotation A). or something. Thank you for help ! PS I don't want to parent unparent gameObject or something like that, i want the math answer, using Quaternion.
0
Unity3d calling a web service in unity editor works, but not in standalone. Why? I have this line of code SDE3D webService new SDE3D() int result webService.UserLogin(txtLoginUsername.text, hashString) My UserLogin function looks like this System.Web.Services.Protocols.SoapDocumentMethodAttribute("http www.something.com UserLogin", RequestNamespace "http www.something.com ", ResponseNamespace "http www.something.com ", Use System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle System.Web.Services.Protocols.SoapParameterStyle.Wrapped) public int UserLogin(string username, string password) object results this.Invoke("UserLogin", new object username, password ) return ((int)(results 0 )) In the Unity Editor it works well. At runtime, in my Unity game build, it doesn't work and doesn't return any error message! What is the issue? Thanks
0
transform.Rotate needs to change axis of rotation So I'm making a game in Unity. After many failed attemps from either being bored of the idea, or something going wrong and me giving up I think (hope) that will be the good one. I have made a simple racing game with a track and a car. I am using transform.Translate to move it, but when I use transform.Rotate to turn it goes around the x axis. How do I change the axis it goes around? I cant find anything online. if (Input.GetAxisRaw("Horizontal") gt 0.5f) transform.Rotate(Vector3.right Time.deltaTime handling) if (Input.GetAxisRaw("Horizontal") lt 0.5f) transform.Rotate(Vector3.left Time.deltaTime handling) if (Input.GetAxisRaw("Vertical") gt 0.5f Input.GetAxisRaw("Vertical") lt 0.5f) transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") moveSpeed Time.deltaTime, 0f)) Thanks for any help you can give me.
0
How can i loop over all the childs of childs? In top of script i added public Transform parentToSearch Then private void OnGUI() if (hasDescription true amp amp clickForDescription true) foreach (Transform child in parentToSearch) if (child.GetComponent lt ItemInformation gt () ! null) ItemInformation iteminformation child.GetComponent lt ItemInformation gt () if (child.name objectHit) var centeredStyle GUI.skin.GetStyle("Label") centeredStyle.alignment TextAnchor.UpperCenter GUI.Label(new Rect(Screen.width 2 50, Screen.height 2 25, 100, 50), iteminformation.description, centeredStyle) But when i make the loop foreach (Transform child in parentToSearch) It will find the first level childs of the first parent but this childs have also childs and so on. And i want to loop all the childs and childs of childs under the Transform. For example in the Hierarchy i have Test Test1 Test2 Test3 Test31 Test32 Test4 Test5 Test51 So now it will loop only over Test 1,2,3,4,5 but I want also to loop over Test31,Test32,Test51
0
AddForce results in stuttering movement I'm currently developing a simple breakout arkanoid mobile game. Now, I noticed that my ball movement is noticably stuttering. I've read various approaches about how to make the ball move and decided to go for AddForce so I don't have to do any physics calculations myself. The only thing im currently doing is using AddForce on my ball's rigidbody2D and have it collide with the walls and blocks. There's nothing done manually in Update or FixedUpdate and there are no other scripts running while the ball is moving. The scene is pretty empty actually. Things I have tried so far without success Disable V Synch Increase the velocity iterations (I tried values 15 500) Set the RigidBody2D's interpolation mode to Interpolate Extrapolate Using different mass values and force values in AddForce Checking, whether it's just an optical illusion (it seems to run more smoothly in editor and other breakout arkanoid games don't have that problem on my Galaxy S7) RigidBody settings of the ball Body Type Dynamic Material Friction 0 Bounciness 1 Mass 0.025 Linear Drag 0 Angular Drag 0 Gravity Scale 0 Collision Detection Continous Sleeping Mode Start Awake Interpolate Interpolate The walls and blocks are simple BoxCollider2D components. And I'm calling AddForce(new Vector2(0f, GameConstants.DESIRED BALL SPEED)) on the ball's RigidBody2D. Edit public void OnPointerUp(PointerEventData eventData) if(! ballStarted) PaddleController.ShootStickingBalls() ballStarted true public void ShootStickingBalls() int stickyBallsAmount stickingBallsRigidBody2D.Count for (int i 0 i lt stickyBallsAmount i ) stickingBallsRigidBody2D i .AddForce(new Vector2(0f, GameConstants.DESIRED BALL SPEED)) stickingBallsRigidBody2D i .transform.SetParent( nonStickyBallsTransform) Sticky false
0
How do I avoid fetching duplicate tetromino shapes from a Shape array in Unity C ? I'm working in C in Unity on a tetrominoes game. I have seven basic shapes (I, J, L, O, S, T, Z) but each of the four component squares on each shape is labelled with an identifier unique to the shape set. So the shapes include, e.g., an S 1,2,3,4, S 5,6,7,8, S 9,10,11,12, J 13,14,15,16, J 17,18,19,20, Z 21,22,23,24.... Currently, in my Spawner class, I have the following to fetch a shape randomly from the shape array, m shapeSet1 public class Spawner MonoBehaviour public Shape m shapeSet1 Shape GetRandomShape() int i Random.Range(0, m shapeSet1.Length) if(m shapeSet1 i ) return m shapeSet1 i else return null I thought it would be simple to use m shapeSet1.RemoveAt(i) before the final closing brace after each fetch to avoid fetching, and later spawning (there is another function to spawn shapes), a duplicate shape. BUT, Visual Studio responds with (1) the RemoveAt request is unreachable and (2) Shape has no definition for RemoveAt and no extension for it. (I'll have to add a Do While or another control to this as I cannot retrieve a shape from the empty array I hope to create once I'm able to get only a unique shape.) Anyway, how do I get a shape without duplication?
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
Only part of my model animates, the rest stays still I made an animation for when my character grabs a ledge, which has him set his arms and head into a position, and have him swing his legs back and forth, however only his legs move and his arms and head stay in the default resting position of the model. I have a video of what's happening. you can see the intended animation on the bottom right, and you can see what happens instead in the video. Video link https youtu.be PwrBdEsvgpY
0
When an animation involves movement, where is the movement better to implement? For context, I am using Blender and Unity. Regarding the question, as an example, in some games, when you get hit, your character tucks a bit and gets knocked back a few distance. The tucking animation I want to implement in Blender but how about the knockback distance? Do you move your model in Blender (tuck and knockback), or do you do the tuck animation only (tuck in place) and then handle the knockback in Unity (basically triggering the tuck animation and then moving the model backwards a bit). My question basically is, what's commonly done and if there's any specific reason, why?
0
Is there a way to start UI animation transition with code in unity? I have made an animation for a button in unity's UI prefab, but i want it to start only at certain times, when i command it with code. How can i do this?
0
CS0118 framerate is a field but a type was expected I'm making a mobile game in Unity and I'm trying to write a script that will set the game to either 30 or 60 frames per second based on a public bool, but I am getting error CS0118 on line 12 with fps.framerate is a 'field' but a 'type' was expected. I am pretty new to Unity so I need help with this? using System.Collections using System.Collections.Generic using UnityEngine public class fps MonoBehaviour public fps framerate Use this for initialization void Start () framerate GameObject.Find("gameSettings").GetComponent lt framerate gt () lt error CS0118 if (framerate true) Application.targetFrameRate 60 else Application.targetFrameRate 30
0
Unexpected results during collisions in Unity I've got a basic car based game I'm starting in Unity. Currently the scene has only a floor, a car (player controlled), and one building. Bumping into the building at low to medium speeds works as expected. When getting the car up to max speed and smashing into the building, though, weird results happen. Originally, the car was being pushed through the floor and falling off the map. I changed the floor from a plane to a cube that was stretched to be broad and flat (scale 2 height), and that helped. Now the car seems to clip right through the building at top speed, sometimes flipping itself into the air when it emerges. So what gives? The car and building are both imported .fbx models and both have box colliders stretched to the outer bounds of the models. The car has a rigid body with gravity. The building used to have a rigid body, but I removed it once I realized it was making the building fly into the air on impact (which was definitely not what I wanted). Here are the relevant parts of the movement code bool key up false float top speed 1f float current speed 0f float acceleration .01f void Update () if (Input.GetKeyDown (KeyCode.UpArrow) amp amp !key up) key up true if (Input.GetKeyUp (KeyCode.UpArrow) amp amp key up) key up false if (key up) if (current speed lt top speed) current speed acceleration else if (current speed gt .1f amp amp current speed lt .1f) current speed 0f if (current speed ! 0f) current speed current speed 0.9f transform.Translate (0f, 0f, current speed) Update After switching the camera to a fixed position (rather than following the car), I've gotten better observations. The car will clip right through at any speed if I keep pushing forward. There's initial resistance from the collision detection and some stuttering from the car, but it always breaks through and then flips into the air on its way out. I've added the following function to the car code void OnCollisionEnter (Collision collision info) current speed 0f current speed is what's being used to translate the car forward each frame. This has slowed the bug down, but the car always eventually pushes through if I hold down the gas long enough. It looks as if Unity's collision detection isn't moving the car back far enough on each frame that the car is colliding. Must I handle that portion on my own?
0
How to fix this NullReferenceException error? I am trying to fix an error that says quot Object reference not set to an instance of an object quot . The purpose of this script is to spawn a prefab that follows the mouse when you click a UI button. The script works fine despite showing the error(yellow triangle), but when I add a line referencing another scripts array(marked gt gt gt ) in the HandleNewObjectHotkey function) the game refuses to run(red stop sign). For context, this script shown is attached to an empty game object. The button retrieves the script from this game object, and specifically uses the HandleNewObjectHotkey Function. I would like to know how I can fix the placeable Object Prefab from producing an error, or a suggestion to bypass it. Things I've tried making placeableObject prefab public, removing serialize field, attaching the prefab to the script itself in assets, change everything from private to public. SerializeField private GameObject placeableObjectPrefab shows error here in visual studio, suggesting to make read only (doesn't fix the problem) private GameObject currentPlaceableObject private float mouseWheelRotation public int objectsSpawned Money stuff private float money private MoneyDisplay moneyDisplay private ObjectCostDisplay objectcostDisplay private void Awake() moneyDisplay GameObject.FindObjectOfType lt MoneyDisplay gt () objectcostDisplay GameObject.FindObjectOfType lt ObjectCostDisplay gt () private void Update() if (currentPlaceableObject ! null) MoveCurrentPlaceableObjectToMouse() RotateFromMouseWheel() ReleaseIfClicked() private void ReleaseIfClicked() if (Input.GetMouseButtonDown(0)) currentPlaceableObject null private void RotateFromMouseWheel() mouseWheelRotation Input.mouseScrollDelta.y currentPlaceableObject.transform.Rotate(Vector3.up, mouseWheelRotation 10f) private void MoveCurrentPlaceableObjectToMouse() Ray ray Camera.main.ScreenPointToRay(Input.mousePosition) RaycastHit hitInfo if (Physics.Raycast(ray, out hitInfo)) currentPlaceableObject.transform.position hitInfo.point currentPlaceableObject.transform.rotation Quaternion.FromToRotation(Vector3.up, hitInfo.normal) public void HandleNewObjectHotkey() error says issue is in this function. money objectcostDisplay.CostsList 0 gt gt gt adding this is what causes unity to refuse to run the game due to error mentioned. Deleting this lets game run, error still present. if (objectsSpawned lt 3 amp amp money lt moneyDisplay.currentMoney) if (currentPlaceableObject null ) currentPlaceableObject Instantiate(placeableObjectPrefab) objectsSpawned moneyDisplay.UpdateMoney(money) if(objectsSpawned 3 amp amp money lt moneyDisplay.currentMoney) Debug.Log( quot You have reached the limit for this item! quot ) if(objectsSpawned lt 3 amp amp money gt moneyDisplay.currentMoney) Debug.Log( quot You don't have enough money for this! quot )
0
Is there any way to automaticaly rig a sprite? I'm making an AR test where the player takes a photo, them i get the bones from the pose and set a t shirt sprite's bones position to match the ones from the photo. I was wondering if there's any way to make the sprite rigging process, with just the main bones like LRshoulder,LRelbow and LRHip, automatic in Unity.
0
How do I get a Light's Range value in Shader? I'm trying to write a simple frag vert shader that, depending on whether it is in the range of a light, will paint the appropriate colour from either the 'lit' texture or from the 'unlit' texture. Therefore, I need to compare the distance between the light to the range of the light. I've been googling all kinds of things, but I can't seem to find a way of accessing the range value of the light. Is there a way to do so? If not, is there some kind of derived data I could use as an alternative? I was able to find this method here, which seems to be the most promising so far, however after playing around for a bit, I still can't seem to get what I need. There's some talk about LightMatrix0 not being populated. Can anyone confirm? I've also had it suggested to use SetFloat() and pass in the range like that...however, that provides no easy way of telling one light apart from another short of using the light's position as a key. As several key lights in the game will be moving this is just ugly and inefficient. Update I found the variable unity LightAtten in the Unity Shader Variables documentation. However, this is only used for Vertex Lit shading, which isn't exactly ideal, especially considering the lack of console support. Could there be a way to pipe this variable to Forward Rendering? Update 2 For clarification, shading should otherwise be 'flat' (ie no need for diffuse etc) Also, what I've currently got (albeit, not currently working as desired and currently using a workaround) Shader "Lantern Flat Pullup" Properties LitTex ("Lit (RGB)", 2D) "white" UnlitTex ("Unlit (RGB)", 2D) "white" Falloff ("Falloff", 2D) "white" Pullup ("Pull up Point", Range(0,1)) 0.7 SubShader Pass Tags "LightMode" "ForwardBase" LOD 200 CGPROGRAM pragma vertex vert pragma fragment frag include "UnityCG.cginc" uniform sampler2D UnlitTex uniform float4 UnlitTex ST uniform sampler2D LitTex uniform float4 LitTex ST uniform float Pullup uniform float4 LightColor0 struct VI float4 vertex POSITION float4 tex TEXCOORD0 struct V2F float4 pos SV POSITION float4 tex TEXCOORD0 float4 posWorld TEXCOORD1 V2F vert(VI v) V2F o o.pos mul(UNITY MATRIX MVP, v.vertex) o.tex v.tex o.posWorld mul( Object2World, v.vertex) return o float4 frag(V2F i) COLOR float3 flatReflection LightColor0.xyz (1 length( WorldSpaceLightPos0.xyz i.posWorld.xyz)) float4 color Improve for light color etc if(length(flatReflection) gt Pullup) color tex2D( LitTex, i.tex.xy LitTex ST.xy LitTex ST.zw) else color tex2D( UnlitTex, i.tex.xy UnlitTex ST.xy UnlitTex ST.zw) return color ENDCG FallBack "Diffuse"
0
Efficiently rendering lots of the same mesh in Unity3D, but with different colors? I'm working on a tile based game, where grass is spreading from tile to tile, so soon lots of grass appear on the board. Instancing is on, so the FPS is kind of good, even with 300k triangles (1 grass leaf consists of 90 triangles). BUT Tiles can be wet and dry on floating scale, which makes the grass leaves turn from green to yellow. Currently I implemented this simply as such var r originalColor.r 0.27f (1f (ground.Status 100)) renderer.material.color new Color(r, originalColor.g, originalColor.b) Which creates a new material for every grass... Obviously I can't change the sharedMaterial's color, because that would change all other grass' colors as well. So how could I efficiently render grass on a big spectrum from yellow to green? One thing I came up with is that I create only like 100 materials, with 1 percent steps. first material is 100 yellow, and the last one is 100 green. And when a grass turns a bit more green, it doesn't have to create a whole new material with 3.47 green, but instead can use the already created 3 green material. Any better ideas? Thanks!
0
How do I enable a Box Collider when a timer reaches 0? I'm pretty new to Unity, and I am trying to enable a BoxCollider from another object when the timer reaches 0, using this code using UnityEngine public class Testv2 MonoBehaviour public GameObject otherGameObject private BoxCollider Target public float timeLeft 30.0f void Awake() Target otherGameObject.GetComponent lt BoxCollider gt () void OnMouseDown() timeLeft Time.deltaTime void Update() if (timeLeft lt 0) Target.enabled true My issue is that the timer won't go down unless I keep clicking on the object. How do I enable the timer to start when someone clicks an object, and start counting down?
0
Get all objects of Additively loaded Scene? (LoadSceneMode.Additive) I learned how to Load and unload scenes in unity. using LoadSceneMode.Additive. I like to spit up my scenes as much as possible and retain the stuff I need as I go along. I'd like to be able to find all objects loaded from a specific scene. Obviously Unity knows but I can't find how to get them. For now, my workaround is to put them in a specifically named empty or have them tagged in a certain way, but that is a workaround. Is there an easier way?
0
Unity, Replace or modify camera with own script I am making an RTS game which has a slowdown when many units are on screen at once. I have a plan to write my own camera script to speed this up. Since I have an efficient way to find where units are without the raycast, I want to write scripts to replace the camera and check raycasts against only the few objects that my scripts will identify as in the correct area for that raycast? Alternatively is is possible to have the camera ignore certain entities on one part of the screen, and then a different set on another part of the screen? Edit I am very grateful for people helping in anyway, but I wanted to know if this Could be done even if in my case it shouldn't be.
0
How can I make Maya or Blender model work with mecanim? I'm working on a simple game project, where I need a stick figure. Due to being stubborn and the desire to learn a new skill, I want to make the stick figure myself! I have followed several tutorials in both Maya and blender. For Maya, I'm using the student version. I have my stick figure rigged within Maya and blender, both utilizing their respective bone tools. I can manipulate their limbs well, enough. However, I can't seem to get the models to work with Mecanim. I have the Kinect adapter for the PC and would like to be able to use it to create the animations utilizing a tool such as the Kinect v2 mocap animator. How I can get my model to work with Kinect based mocap?
0
UIButton fails to play sound I'm doing this game where with cards you assign different beats to different channels. You drag and drop the beat to a channel and it gets added to the mixer. What I'm having trouble with is when i try to play each channel individually with an UI Button. This is the script attached to the channels public class ManageChannel MonoBehaviour public AudioSource thisAudioSource bool chequeo string Nombre public AudioMixer audioMixer public void AsignaCanal () Nombre this.name tomo el nombre del canal actual thisAudioSource this.GetComponent lt AudioSource gt () var carta this.transform.GetChild(0) llamo a la carta hija de este objeto thisAudioSource.clip carta.GetComponent lt AudioSource gt ().clip thisAudioSource.outputAudioMixerGroup audioMixer.FindMatchingGroups(Nombre) 0 asigno al AudioSource el grupo correspondiente public void comienzaAudio () if (!thisAudioSource.isPlaying) thisAudioSource.Play() else thisAudioSource.Stop() Start is called before the first frame update void Start() chequeo true Update is called once per frame void Update() if (this.transform.childCount ! 0 amp amp chequeo) AsignaCanal() chequeo false thisAudioSource.Play() What the script does is when a card is dropped, it takes the clip of the card and get its into the AudioSource of the channel, and that AudioSource gets outputted to its respective channel (for example, the GameObject quot Channel 1 quot goes to the mixer group quot Channel 1 quot and so on). Then i've tried to build the buttons to reproduce the track of each channel individually, but using AudioSource.Play() since I believe I cannot do it with the AudioMixer directly. What i did is create a UIButton and then assign the respective GameObject Channel to the OnClick() section on the inspector, and then i choose the following function on the script that i showed before public void comienzaAudio () if (!thisAudioSource.isPlaying) thisAudioSource.Play() else thisAudioSource.Stop() Then, every time i press the button, that function should be called. The problem is nothing happens. I'm positive the button is working because i tested with a bool value and a Debug.Log() to see if it changes values with every click, and it does. So, i honestly have no clue what the issue is. Any help would be appreciated. Thanks!
0
Show Sprites on Overlap (Shader Graph) 2D I have a character sprite mesh and mesh renderer (The black wavy box). I am hoping to be able to overlay the black box onto the character covering the sprites but I am not sure how to do that. I looked at this question Unity How do I only show parts of objects that overlap 2D But this works more as a cover that you can see through. I am hoping to have the variable black mask the sprites of the character but I cant seem to layer these correctly. Is there a way to do this using the LWRP and shader graph? The over arching idea is to use this as a damage marker. Moving the black box up or down depending on the health lost.
0
How to recycle unity scroll list of game objects? In my game, I have a scrollrect which its content have a VerticalLayout component. When I fill that with so many count of GameObjects, the game will fall in problem! I know that I have to recycle my objects, but I don't know how!
0
How do I slow down my character while running? void Movement() transform.Translate(Vector3.forward 10 Time.deltaTime) if(Input.GetKey(KeyCode.S)) transform.Translate(Vector3.forward 3 Time.deltaTime) if(Input.GetKeyUp(KeyCode.S)) transform.Translate(Vector3.forward 10 Time.deltaTime) I tried this code but seems to me, it didn't work as I expected it to. What I expect my character moves along at a speed of 10 automatically when the S key is held, the character slows down to a speed of 3 instead when the S key is released, the character goes back to their default speed of 10 What I observe the character does not slow down when the S key is pressed How can I fix this?
0
Draw trajectory arc predictor in game I found this tutorial on youtube and it works pretty well, but I want to add more to it. How can I draw a smooth arc path in the game view (right now the path is only visible in the editor)? Here is the code public class BallLauncher MonoBehaviour public Rigidbody ball public Transform target public float h 25 public float gravity 18 public bool debugPath void Start() ball.useGravity false void Update() if (Input.GetKeyDown (KeyCode.Space)) Launch () if (debugPath) DrawPath () void Launch() Physics.gravity Vector3.up gravity ball.useGravity true ball.velocity CalculateLaunchData ().initialVelocity LaunchData CalculateLaunchData() float displacementY target.position.y ball.position.y Vector3 displacementXZ new Vector3 (target.position.x ball.position.x, 0, target.position.z ball.position.z) float time Mathf.Sqrt( 2 h gravity) Mathf.Sqrt(2 (displacementY h) gravity) Vector3 velocityY Vector3.up Mathf.Sqrt ( 2 gravity h) Vector3 velocityXZ displacementXZ time return new LaunchData(velocityXZ velocityY Mathf.Sign(gravity), time) void DrawPath() LaunchData launchData CalculateLaunchData () Vector3 previousDrawPoint ball.position int resolution 30 for (int i 1 i lt resolution i ) float simulationTime i (float)resolution launchData.timeToTarget Vector3 displacement launchData.initialVelocity simulationTime Vector3.up gravity simulationTime simulationTime 2f Vector3 drawPoint ball.position displacement Debug.DrawLine (previousDrawPoint, drawPoint, Color.green) previousDrawPoint drawPoint struct LaunchData public readonly Vector3 initialVelocity public readonly float timeToTarget public LaunchData (Vector3 initialVelocity, float timeToTarget) this.initialVelocity initialVelocity this.timeToTarget timeToTarget I found a way to Instantiate projectile along the path. Now I just need to know how to convert that line in debug mode to make it visible in game mode
0
An object reference is required to access non static member UnityEngine.Material.GetTextureOffset(string) I am watching a tutorial where it seem to work. But in my case, I am getting this error. I get it that non static members have to have an object. But, I don't know much about how to fix this error. using UnityEngine using System.Collections public class AnimatedTexture MonoBehaviour public Vector2 speed Vector2.zero private Vector2 offset Vector2.zero private Material material void Start() material GetComponent lt Renderer gt ().material offset Material.GetTextureOffset (" MainTex") void Update() offset speed Time.deltaTime material.SetTextureOffset (" MainTex", offset)
0
Shadows in Android using Unity 5 The point lights in my scene cast shadows when it's in the editor mode but the light passes through walls in the build or play mode. I checked the quality settings and set it to hard and soft shadows for all quality settings but that didn't fix it. It does work when I increase the quality when I build it for Standalone but not when I build for Android. I've removed the dx11 option in the PC Mac Standalone settings. I've changed both forward and deferred rendering options. I'm testing it on a Moto G 1st Gen XT 1033 .
0
Light point buggy on old device after migrating to URP Light point is very buggy on Samsung A5 after migrating to URP, it works well on PC and Samsung A7. Altought it has light points, these are really few and using lowest settings by default, all other graphic stuff is lightweight and runs well. Does someone know if it's expected or what can I do? I tried to reduce the lightning settings and add OpenGL ES 2, but I've got the same results.
0
Follow Player which moves over a sphere After hours of googling and pulling several hairs out, I decided to open this thread. I want to make a game, in which the player walks around a sphere (like super Mario galaxy) and the camera should stay fixed over the player and point down on its head but I can't seem to get anywhere near of the right method. So, how can I realise this? Thanks.
0
Perlin Noise Problem with Falloff I know this might be a bit of a noob question, but I can't figure out what I'm doing wrong, and the math that I have done should make this work correctly. I am trying to make a perlin noise map that is normal until a specific range, at which point it would decrease to where all the values trend towards zero, creating an island in an ocean. I am currently generating perlin "sample" values, and then dividing them by a factor which stays close to one up to a specific bound, and then increases polynomialy. The problem however, is that the noise stays stuck in the top right corner, and is darker than I would expect. Here is the mathematical function I am using graphed on Desmos where n is the boundary and x is the distance from the center of the map And here is the main body code I am using to generate the noise map using System.Collections using System.Collections.Generic using UnityEngine public class GenNoise MonoBehaviour public int width 256 public int height 256 public float scale 20f public float offsetX public float offsetY public float falloffRange 100 public float falloffPower 10 public void RenderNoiseMap() Renderer renderer GetComponent lt Renderer gt () renderer.sharedMaterial.mainTexture GenerateTexture() Texture2D GenerateTexture () Texture2D texture new Texture2D(width, height) for (int x 0 x lt width x ) for (int y 0 y lt height y ) Color color GenerateColor(x, y) texture.SetPixel(x, y, color) texture.Apply() return texture Color GenerateColor(int x, int y) float xCoord ((float)x width scale) offsetX float yCoord ((float)y height scale) offsetY float falloffFactor FalloffFactor(x, y, width, height) float sample Mathf.PerlinNoise(xCoord, yCoord) sample sample falloffFactor return new Color(sample, sample, sample) float FalloffFactor(int x, int y, int width, int height) float falloffFactor 1 float centerX (float)width 2 float centerY (float)height 2 float distanceFromCenter Mathf.Sqrt(Mathf.Pow(2, ((float)x centerX)) Mathf.Pow(2, ((float)y centerY))) falloffFactor Mathf.Pow(2, (Mathf.Pow(falloffPower, (distanceFromCenter falloffRange)) 1)) return falloffFactor And Here is the code that I am using to generate the image in the editor using UnityEngine using UnityEditor CustomEditor(typeof(GenNoise)) public class NewBehaviourScript Editor public override void OnInspectorGUI() DrawDefaultInspector() GenNoise script (GenNoise)target if (GUILayout.Button("Generate")) script.RenderNoiseMap() Here is a picture of the result
0
Can I run my own loading script during the Unity splash screen? Can I load data in the background while the Unity splash screen is up? If so, how? I am trying to run code during the splash screen, not just load assets. I have not been able to find any information on this in Google or the Unity Documentation.
0
Keeping instantiated grid in the centre of the screen? everyone, I'm making a mobile game and I need help. In the game, I instantiate a grid of dots as seen in the first attached file below. My problem is the grid is not in the centre of the screen I could just position my main camera so the grid is in the centre the only problem with this approach being that the grid changes in size depending on your level as shown in attachment 2 here's my spawn code for (int x 0 x lt gridX x ) for (int y 0 y lt gridY y ) SpawnDelay Random.Range(0.2f, 0.5f) yield return new WaitForSeconds(SpawnDelay) Instantiate(Dot, transform.position, transform.rotation) NumberOfdots transform.position new Vector2(transform.position.x distanceBetween, transform.position.y) if (y MutpleNum ByMutpleNum) transform.position new Vector2(GridoffsetX 2, transform.position.y GridoffsetY) Is there anyway I can have the grid centre regardless of its size Thanks, David
0
Unity How to realize a modal message box? I'm developing a simple "modal" MessageBox. This is the code inside Message Box panel public void Show(string title , string message, bool showYesButton, bool showNoButton, bool showCancelButton) this.gameObject.SetActive (true) Title.text title Message.text message btnYes.SetActive ( showYesButton) btnNo.SetActive ( showNoButton) btnCancel.SetActive ( showCancelButton) And here how I call it outside MyMessageBoxScript script MyMsgBoxGameObject.GetComponent lt MyMessageBoxScript gt () script.Show("Hey..","Are you sure you want to overwrite this save ?",true,true,false) Ok.. the problem is that I can't do a "modal" window, like in .NET version, returning what user pressed. Something like buttonPressed script.Show("Hey. ", "Are you sure...") So, searching with Google someone use this Way script.Show(CallBackFunction "Hey..","Are you sure you want to overwrite this save ?",true,true,false) and void CallBackFunction () ... But I can't understand how it works How to pass CallBackFunction as parameter and how to execute (after clicking yes,no or cancel) ? Thanks
0
Looping world for a top down space shooter? I am trying to understand how to make a seamless looping world for my top down space shooter. First thing I tried was using multiple cameras, and teleporting the player when he reaches the edge, but it is not working well, and I don't like that I have to use 4 cameras. I wanted to test making the objects in the world teleport around the player, but I will have problems with the fact that each object is a different size, and teleporting them around will for sure create problems with moving objects. (Big obstacles could be teleported away and not collide with, for example, bullets until the bullet gets teleported too but inside the big obstacle) Are there other ways to accomplish this? Screen of the game (everything is still a placeholder) https i.stack.imgur.com 8FWCE.png
0
Attach movement to each list object How would i move every sphere that gets spawned every 2 seconds ? Basically i want every sphere to follow the previous spawned sphere or even all N 1 spheres should follow the first spawned sphere along a predefined path and they should keep rolling as a train of spheres. I am lost when i try to imprint movement to each sphere. using System.Collections using System.Collections.Generic using UnityEngine public class Spawner MonoBehaviour public GameObject prefabs public List lt GameObject gt listBalls new List lt GameObject gt () private GameObject x public int timer 0 private float movementSpeed 5f void Start() createBall() void Update() if (Time.time timer gt 0.8f) createBall() timer 2 listBalls listBalls.Count 1 .transform.position new Vector3(0, 0, movementSpeed Time.deltaTime) void createBall() x prefabs Random.Range(0, prefabs.Length) Instantiate(x, x.transform.position, Quaternion.identity) listBalls.Add(x) void moveBall(GameObject x, GameObject y) x.transform.position y.transform.position new Vector3(0,0, 1) Loop added but movement staggered void Update() if (Time.time timer gt 0.8f) createBall() timer 2 foreach (GameObject item in listBalls) item.transform.position new Vector3(0, 0, movementSpeed Time.deltaTime)
0
Move object towards the center of coordinating system I would like to move a object towards Vector2(0, 0), but every time I use this script, the object always goes down, instead of going towards the center of the coordinate system. void Update() Object rotation if (!Input.GetMouseButtonDown(0)) angle speed Time.deltaTime var offset new Vector2(Mathf.Sin( angle), Mathf.Cos( angle)) radius transform.position centre offset else Moving object towards center rb.transform.position Vector2.MoveTowards(transform.position, Vector2.zero, speed Time.deltaTime)
0
How to instantiate seamless scrolling tiles I'm trying to create in Unity an quot Endless Runner quot game, where the player remains stationary on the 0 of the axes while the tiles underneath him scroll with a fixed speed on the Z Axis. The script attached spawns 5 tiles at the start while already scrolling at the speed set in the GameManager and then keeps on spawning tiles based on a timer. The issue I'm facing is the following The tiles that are spawned with the timer are too much distant from the starting set of tiles. How can I calculate the correct distance between the set of the already scrolling tiles and those the script start to spawn after 5 seconds in order to have seamless scrolling? I'm attaching the script with what I've written so far in the hope that someone knows how to proceed, or perhaps knows a different method. Thanks! public class TileManager MonoBehaviour SerializeField private Transform player SerializeField private GameObject tilesArray SerializeField private int tilesToSpawn 5 SerializeField private float zPosSpawn 0f SerializeField private float tileLength 20f public List lt GameObject gt tilesList private float spawnRate private float timeSinceLastSpawned void Start() scrollingSpeed is 5 spawnRate GameManager.Instance.scrollingObjectsSpeed 1 StartSpawnLogic() void Update() timeSinceLastSpawned Time.deltaTime SpawnTimer() DestroyAfterSpawn() private void StartSpawnLogic() for (int i 0 i lt tilesToSpawn i ) if (i 0) SpawnTiles(0) else SpawnTiles(Random.Range(0, tilesArray.Length)) SPAWN FUNCTION private void SpawnTiles(int tileIndex) On Instantiation a list is filled to later dispose of the tiles after they reached a certain point tilesList.Add((GameObject)Instantiate(tilesArray tileIndex , transform.forward zPosSpawn, Quaternion.identity)) zPosSpawn tileLength TIMER private void SpawnTimer() if (timeSinceLastSpawned gt spawnRate) timeSinceLastSpawned 0 SpawnTiles(Random.Range(1, tilesArray.Length)) void RemoveObjFromList(GameObject tile) Destroy(tile) tilesList.Remove(tile) private void DestroyAfterSpawn() for (int i 0 i lt tilesList.Count i ) if (tilesList i .transform.position.z lt 20f) RemoveObjFromList(tilesList i )
0
Unity IAP through Google Play is forgotten after a day without internet connection I am trying to make a NonConsumable IAP purchase persist without internet connection. I have implemented the IAP system from Unity 5.6 through Google Play for a NonConsumable item and it is working. From a previous question I learned how to avoid using Unity's PlayerPrefs to remember purchases in favor of checking the receipt from the Unity storeController that initializes with Unity's API code below. public void OnInitialized (IStoreController controller, IExtensionProvider extensions) this.controller controller this.extensions extensions What I have observed is that the OnInitialized will run without internet connection as long as it has recently been initialized. This seems to be cached somewhere within Android because clearing the cache on my app will not force the purchase to be forgotten. The problem is after about half a day without internet connection the controller cannot initialize. Therefore I cannot check the item receipt in the controller with the code below. Product product storeController.products.WithID(productId) if (product ! null amp amp product.hasReceipt) Owned Non Consumables and Subscriptions should always have receipts. So here the Non Consumable product has already been bought. itemBought true What strategy or method should I use to persist a NonConsumable purchase during times without internet connection as it is recommended to not use Playerprefs on numerous guides.
0
How to create high quality and fast portal effect? EDIT So I've gotten the portal visual effect working with no performance hit, and I've got the physics set up of objects with rigidbodies moving through portals seamlessly, and objects with character controllers moving through it seamlessly. The only thing I'm trying to figure out now is blending two camera views to get the proper first person transition effect. Any ideas on how I'd blend those two? I'm thinking something using a depth only shader, or the normalized viewport rect. My main problem is calculating that in real time, and with angles. So I've been working on creating a portal effect in Unity3D. Obviously I've taken Valve's Portal as a great influence to programming this. Currently I'm simply using a camera's rendertexture to get the graphical effect across, and then some code to do the rest. The problem is at 2048x2048 it looks as high quality as Portal's, but causes heavy FPS loss. To solve this I'd either have to lower the texture quality or the number of times I update the texture. Valve has accomplished a high quality portal effect without causing high frame rate loss. How can I do the same? Does anybody have any good ideas for rendering to a high resolution texture without causing frame loss? I'm considering making my own code for rendering to textures rather then using Unity's built in system, it's doable but would definitely be a hassle. So any thoughts, ideas, or suggestions are highly appreciated.
0
Is it possible to get object rotation in a shader for dynamically batched objects? All the batched objects have the same rotation. To simulate the effect of directional light I need to determine the object sides actual (world) directions. Normally I would use unity ObjectToWorld amp unity ObjectToWorld for that, which is not possible when the objects are batched. Is it possible to pass the object rotation to the shader in one action (since it's the same for all of them) without breaking the batching? This is a simplified shader example (here I use colors instead of light shadow effect and only 2 sides instead of 4) Shader quot Test UnlitTest quot Properties MainTex ( quot Texture quot , 2D) quot white quot TopColor ( quot TopColor quot , Color) (1, 0, 0, 1) BottomColor ( quot BottomColor quot , Color) (0, 0, 1, 1) SubShader Tags quot RenderType quot quot Opaque quot ZTest Off ZWrite Off Lighting Off Cull Off Fog Mode Off Pass CGPROGRAM pragma vertex vert pragma fragment frag include quot UnityCG.cginc quot sampler2D MainTex float4 MainTex ST float4 MainTex TexelSize fixed4 TopColor, BottomColor struct vertData float4 vertex POSITION float2 uv TEXCOORD0 struct fragData float2 uv TEXCOORD0 float2 uvW TEXCOORD1 float4 vertex SV POSITION fragData vert (vertData v) fragData f f.vertex UnityObjectToClipPos(v.vertex) f.uv TRANSFORM TEX(v.uv, MainTex) f.uvW mul(unity ObjectToWorld, f.uv) return f fixed isTransparentPixel(fixed2 uv) return step(tex2D( MainTex, uv).a, 0.0) fixed isEdgePixel(fixed2 uv) uv mul(unity WorldToObject, uv) back to object space return isTransparentPixel(uv) fixed4 frag (fragData f) SV Target fixed isTransparent isTransparentPixel(f.uv) clip( isTransparent) fixed4 c tex2D( MainTex, f.uv) float2 borderSize float2(3, 3) border size in tex pixels float dy borderSize.y MainTex TexelSize.y fixed3 borderColor fixed3(0, 0, 0) float borderColorsCount 0 float2 uvW f.uvW UV in the world space Top edge fixed isEdge isEdgePixel(uvW float2(0, dy)) borderColor isEdge TopColor.rgb borderColorsCount isEdge Bottom edge isEdge isEdgePixel(uvW float2(0, dy)) borderColor isEdge BottomColor.rgb borderColorsCount isEdge fixed noBorderColor step(length(borderColor), 0) fixed hasBorderColor 1 noBorderColor c.rgb c.rgb noBorderColor hasBorderColor borderColor max(borderColorsCount, 1) return c ENDCG It gets a semi transparent image as a texture. The image is completely transparent at the edges and contains an opaque shape in the center. The shader colors the top edges of the non transparent shape in red and the bottom ones in yellow. It uses unity WorldToObject amp unity ObjectToWorld to check the edges facing directions in the world space.
0
Have a method accept generic methods for a in game console I'm making a console, like in Half Life so that the devs can add their commands. I'm making this in Unity's C . I have a problem when dealing with the commands. When you want to add a commands, you create a class Command and add it through a method to the Console List of Commands. The code of the class Command is the following one public class Command lt summary gt The string by which this command will be called lt summary gt public string commandKey lt summary gt The information of this command that the help option will show lt summary gt public string helpInfo public delegate string stringVoid() public delegate string stringString(string consoleInput) public delegate void voidCmd() public delegate void voidString(string consoleInput) public stringVoid stringVoid public stringString stringString public voidCmd voidCmd public voidString voidString public Command(string commandInput, string helpTooltip) commandKey commandInput helpInfo helpTooltip region Add Command Methods public Command addVoidCommand(voidCmd voidCommand) voidCmd voidCommand return this public Command addStringVoid(stringVoid stringVoidCmd) stringVoid stringVoidCmd return this public Command addStringString(stringString stringStringCmd) stringString stringStringCmd return this public Command addVoidString(voidString voidStringCmd) voidString voidStringCmd return this endregion As you can see users can add four types of delegates methods Void methods with no parameters. String methods with no parameters. Void methods with a string parameter. String method with a string parameter. This makes the class very heavy, and makes the users have to navigate through a lot of options to add a class. I want to have some way to add methods without having to go through so many options, and, from my side, taking out the need of searching through so many options when a command is called from console. You can find the whole script project here. In conclusion, I want to have a way that the user simply write way I want it to work new Command("commandName", "this is an example" ExampleCommand) new Command("commandString", "this is another example" ExampleString) void ExampleCommand() string ExamplesString(string ble) return ble "bla" way it currently works new Command("commandName", "this is an example").addVoidCommand(ExampleCommand) new Command("commandString", "this is another example").addStringString(ExampleString) To simplify everything. Is any way I can achieve this with delegates, Unity Actions or something else? Thank you very much.
0
Why when using Mathf Lerp the speed is not changing according to Time.deltatime? using System.Collections using System.Collections.Generic using UnityEngine public class DetectCollision MonoBehaviour public Transform player public Transform target public bool turnOnOffPlayerAnimator false float timeElapsed 0 float lerpDuration 3 float startValue 1 float endValue 0 float valueToLerp 0 private Animator playerAnimator private bool entered false private bool prevFacing false private Rigidbody rigidbody private bool stopped false Start is called before the first frame update void Start() rigidbody player.GetComponent lt Rigidbody gt () playerAnimator player.GetComponent lt Animator gt () if (turnOnOffPlayerAnimator) playerAnimator.enabled false Update is called once per frame void Update() var currFacing IsFacing(target) if (currFacing ! prevFacing) here you switched from facing to not facing or vise verca. timeElapsed 0 prevFacing currFacing var distance Vector3.Distance(player.position, target.position) if (IsFacing(target)) if (entered amp amp distance gt 30) if (timeElapsed lt lerpDuration) valueToLerp Mathf.Lerp(startValue, endValue, timeElapsed lerpDuration) playerAnimator.SetFloat( quot Forward quot , valueToLerp) timeElapsed Time.deltaTime playerAnimator.SetFloat( quot Forward quot , valueToLerp) valueToLerp 0 else if (valueToLerp lt 0.9f) if (timeElapsed lt lerpDuration) valueToLerp Mathf.Lerp(endValue, startValue, timeElapsed lerpDuration) playerAnimator.SetFloat( quot Forward quot , valueToLerp) timeElapsed Time.deltaTime playerAnimator.SetFloat( quot Forward quot , valueToLerp) Mathf.Lerp(valueToLerp, 0, Time.deltaTime 0.0001f) if(turnOnOffPlayerAnimator) playerAnimator.enabled false else playerAnimator.enabled true private void OnTriggerEnter(Collider other) entered true Debug.Log( quot Entered ! quot ) private void OnTriggerExit(Collider other) entered false Debug.Log( quot Exited ! quot ) private bool IsFacing(Transform target) Vector3 forward player.TransformDirection(Vector3.forward) Vector3 toTarget target.position player.position return Vector3.Dot(forward, toTarget) gt 0 I tried first 0.1f but it didn't change the lerp speed. I want that if the player is pressing the W key and moving the player forward and then stop pressing the key W it will smooth slow will lerp to 0. and it does but I also wanted to control the lerp speed. I want that when the player is starting moving backward direction if the player leave the W key the player should stop slowly to 0. This should be the line Mathf.Lerp(valueToLerp, 0, Time.deltaTime 0.0001f) but the Time.deltaTime does not seems to affect the lerp at all. the lerp is working fine I just wanted to control the lerping speed too.
0
Why are there weird texture artifacts in baked light which don't appear with realtime light? This is the comparison of the same scene, realtime light vs baked light. What's am I wrong ? EDIT In particular, also texture are low quality (see image 2). Why ?
0
Planar reflections not showing when baked reflection probes enabled I have a reflection probe that is baked that is set to capture static environment objects like buildings terrain etc. I also have a planar reflection probe that is following the player camera which is only set to capture the player. I am trying to have both of these displaying on a surface. When I have the baked reflection probe turned on the planar reflection will not show. Are they mutually exclusive? I am using Unity 2020.1.6f1 with HDRP.
0
How to prevent Rigidbodies with restricted movement from clipping My player is a rigidbody cube with a box collider that can push other quot NPC quot rigidbody cubes that also have a box collider. These NPC cubes have restricted movement either in horizontal or vertical direction. If the player pushes a cube that can only move horizontally into a cube that can only move vertically, the cubes start clipping. I recorded the whole situation in this video. Note that the NPC cube on the left has frozen X position, while the one on the right has frozen Z position. I know that one way of preventing this would be to increase the mass of the NPC cubes, but that would only resolve the problem proportionally to the increased mass (the higher the mass, the lower the clipping), and at some point my player is not strong enough to move the NPC cubes anymore. How can I solve this?
0
How to make a rigidbody come to rest faster I'm trying to move around a 3D rigidbody in Unity 2018.1.0f2 Personal. I am using a C script with the basic vector3 and velocity stuff from a YouTube video using System.Collections using System.Collections.Generic using UnityEngine public class Player MonoBehaviour SerializeField private Rigidbody playerBody private Vector3 inputVector private float xMovement private float zMovement SerializeField private float playerSpeed private float maxSpeed Use this for initialization void Start () playerBody GetComponent lt Rigidbody gt () playerSpeed 1 Update is called once per frame void Update () xMovement Input.GetAxisRaw("Horizontal") playerSpeed zMovement Input.GetAxisRaw("Vertical") playerSpeed inputVector new Vector3(xMovement, playerBody.velocity.y, zMovement) playerBody.velocity inputVector It works great with a cube I put it on, except for this if I move the rigidbody and then stop, it takes a long time for it rotate from go only one of the edges or corners just touching the ground (screenshot of what I mean, another screenshot) to resting flat. How can I make it fall back to stability faster?
0
Unity 5 Occlusion culling at runtime I am creating a game in Unity where the game is rendered while playing. The game is made in a voxel style, and has thousands upon thousands of objects rendered while playing. Of course, this causes a huge amount of lag. Therefor I need to use occlusion culling, to make sure only the objects needed are rendered. For occlusion culling, you need to bake the area, but I'm planning on creating a huge world. So, any tips on how I could do this?
0
Handle two different touch gestures at same time without overlapping I'm trying to create a Character touch controls for 2d platform. In my script Im using one horizontal swipe and hold touch gesture and one vertical swipe gesture without hold.Both are different methods called in void Update (). And here is my script void Update () HorizontalSwipe() VerticalSwipe () void HorizontalSwipe() foreach (Touch FingerTouchx in Input.touches) if(FingerTouchx.fingerId lt 1) FINGERID if(FingerTouchx.position.x lt Screen.width 2) if(FingerTouchx.phase TouchPhase.Began) FingerInitialPositionx FingerTouchx.position.x else if(FingerTouchx.phase TouchPhase.Moved) FingerMovedPositionx FingerTouchx.position.x if(FingerMovedPositionx gt FingerInitialPositionx) charcter.transform.Translate(Vector2.right speed Time.deltaTime) else if(FingerMovedPositionx lt FingerInitialPositionx) charcter.transform.Translate( Vector2.right speed Time.deltaTime) else if(FingerTouchx.phase TouchPhase.Ended) FingerInitialPositionx 0f FingerMovedPositionx 0f else FingerMovedPositionx FingerTouchx.position.x if(FingerMovedPositionx gt FingerInitialPositionx) charcter.transform.Translate(Vector2.right speed Time.deltaTime) else if(FingerMovedPositionx lt FingerInitialPositionx) charcter.transform.Translate( Vector2.right speed Time.deltaTime) void VerticalSwipe() foreach (Touch FingerTouchy in Input.touches) if(FingerTouchy.fingerId lt 1) FINGERID if(FingerTouchy.position.y gt Screen.width 2) if(FingerTouchy.phase TouchPhase.Began) FingerInitialPositiony FingerTouchy.position.y if(FingerTouchy.phase TouchPhase.Moved) FingerMovedPositiony FingerTouchy.position.y if(FingerTouchy.phase TouchPhase.Ended) if(FingerMovedPositiony gt FingerInitialPositiony) charcter.transform.Translate(Vector2.up speed Time.deltaTime) if(FingerMovedPositiony lt FingerInitialPositiony) charcter.transform.Translate( Vector2.up speed Time.deltaTime) FingerInitialPositiony 0f FingerMovedPositiony 0f else Problem 1 When i swipe and hold horizontally the character moves fine but when i take my finger back it triggers the vertical swipe method. 2 When i try to swipe only vertically the horizontal swipe is also triggered. 3 The two swipe gestures are overlapping and triggered at same time on a Single touch. Solution(Guess) Dividing the touch screen equally half and forcing horizontal touch gestures strictly on left side of touch screen and vertical touch gestures on right side. But I'm beginner(You can see my coding style) and would like to know how to do it programatically. Im still learning.
0
On screen enemy indicating arrow I am working on indicating on screen arrow to point towards the enemy. I have a environment which consist of a player and three enemy placed at different position on the environment.I need an arrow indicating the enemy,so that the player can move towards the enemy in the environment. How can I do this?Can anybody please help me out. I have got a script on searching. public Texture2D icon The icon. Preferably an arrow pointing upwards. public float iconSize 50f HideInInspector public GUIStyle gooey GUIStyle to make the box around the icon invisible. Public so that everything has the default stats. Vector2 indRange float scaleRes Screen.width 500 The width of the screen divided by 500. Will make the GUI automatically scale with varying resolutions. Camera cam bool visible false Whether or not the object is visible in the camera. void Start () visible GetComponent lt SpriteRenderer gt ().isVisible cam Camera.main Don't use Camera.main in a looping method, its very slow, as Camera.main actually does a GameObject.Find for an object tagged with MainCamera. indRange.x Screen.width (Screen.width 6) indRange.y Screen.height (Screen.height 7) indRange 2f gooey.normal.textColor new Vector4 (0, 0, 0, 0) Makes the box around the icon invisible. visible false void OnGUI () if (visible) Vector3 dir transform.position cam.transform.position dir Vector3.Normalize (dir) dir.y 1f Vector2 indPos new Vector2 (indRange.x dir.x, indRange.y dir.y) indPos new Vector2 ((Screen.width 2) indPos.x, (Screen.height 2) indPos.y) Vector3 pdir transform.position cam.ScreenToWorldPoint(new Vector3(indPos.x, indPos.y, transform.position.z)) pdir Vector3.Normalize(pdir) float angle Mathf.Atan2(pdir.x, pdir.y) Mathf.Rad2Deg GUIUtility.RotateAroundPivot(angle, indPos) Rotates the GUI. Only rotates GUI drawn after the rotate is called, not before. GUI.Box (new Rect (indPos.x, indPos.y, scaleRes iconSize, scaleRes iconSize), icon,gooey) GUIUtility.RotateAroundPivot(0, indPos) Rotates GUI back to the default so that GUI drawn after is not rotated. void OnBecameInvisible() visible false Turns off the indicator if object is onscreen. void OnBecameVisible() visible true The problem is start when I play the scene the arrow is seen at the start but its get invisible soon
0
Unity blur on one camera effects the other as well I'm trying to fake a DOF effect for Sprites by using 2 cameras, one for the sharp objects, one for the blurred ones. I have set up the layers like Blur and Sharp accordingly. So I have these 2 cameras, and I use Unity's Blur (optimized) script to blur things, and I have this script on only one camera, the one that is responsible for the blurred render. I have the cameras like Cam 1 Clear flags Don't clear (this is the main, sharp cam) Culling mask sharp layer has no blur effect (or any other post proc effect). Cam 2 Clear flags don't clear (this is the blur cam) culling mask blur Has Blur (optimized). Now, if this blur cam is on the back, meaning its depth is LESS than the main cam's depth, I have a sharp player ground and a blurry background. However, I need a blurry foreground too that should be on top of the player ground. The issue starts when I set the blur camera's depth higher than the main cam's. In this case, everything gets blurred, no matter that the main cam has no blur effect on it. Question is, how to set this up so only the desired layers get the blur?
0
Initial setting of camera and ppu to match playing table My goal is to implement another board game as close as possible as I would play it on a table to not much think about how to arrange elements. The used space on table is in the dimensions of around 1x2m and most of my assets are scans of game cards with a touch of Photoshop (for personal use only). My question is regarding the camera, pixel on import of asset and converting to units. There are no physics in the game involved and it is 2D. For now it will be tailored to my own mobile but I would like to know if one way is preferred if I wanted to later change resolution or is just better best practice. From my understanding it would result both in the same outcomes but there might be some hidden trouble or side effects. Should I (convert for myself to get a feel for dimensions) take 1 unit as 10cm gt scene of 10x20 units would represent my table or rather have a 1x2 unit scene (since most take one unit as one meter) Assuming my scanned card has something like 2000x1000 pixel (and is 10x5cm big on a real table), does it make more sense to have it imported as 2000 20000 under pixel per unit or downscale the image first before importing it with a lesser value? I don't really care currently about build asset size.
0
How to destroy object after animation I've made an object and when the player has pick it up, rise it up and stop it out of screen. But because you can see the shadow of that object, I will destroy it after the animation has played. But how can I do this whit Unity and C ? Just destroy is just like this Destroy(gameobject) and start an animation like this private Animator anim global variable anim GetComponent lt Animator gt () in start() methode anim.SetTrigger("Picked") in other methode
0
Make Unity Text Area to act like a logger I'm trying to create a text area in Unity using UI.Text that contains multi line text which should act like a log view, i.e the text area Vertical Overflow is set to Truncate and a new line of text is added to the text property every now and then but instead of the text being eventually cut of at the bottom when the text area is full I want the text to 'scroll' up so that the newest added line is always the last displayed at the bottom of the text area, e.g. Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 ... When Line 7 is logged Line 1 goes out of the text area at the top, when Line 8 is logged, Line 2 goes out, etc. Can this be done with UI.Text?
0
Will reseting a scene instead of reloading it improve performance? I made a 2D infinite runner. My game was approved for iOS and now pending release. However, on Android, performance is a nightmare. So I'm tweaking to optimize performance. As it stands now, there is game scene and game over scene. On game over scene, there is "Play Again" button that reloads the game scene. Now, if instead of having separate scene, if i handle the play again in same scene, will it be better than reloading the scene? What i could do is, have initial speed, position etc stored in array for example and when play again is clicked, set all gameobjects to the initial values. Will the performance be better with this? since gameobjects are now not getting destroyed and reloaded?
0
Are we supposed to be creating player prefab? This may seem like a dumb question, but I want a single player object for the entirety of my game. However when I load multiple levels obviously I need to reload the player so I would create a player prefab and instantiate him. However, it seems counterintuitive as prefabs are for objects you want to create multiple instances of easily, correct? Also, I need values to be carried over accross levels for my player object therefore I guess I would need a static global singleton to store the player objects. Hence the dilemna and confusion! Can anyone help me out here?
0
How can I limit the y rotation of a cinemachine POV camera based on the player's direction? I'm using Unity (2019.4.11.f1, HDRP). My goal is to create a first person POV camera. To this purpose, I tied a Cinemachine (2.7.3) Virtual Camera to the head of a third person player character (one from the Basic Locomotion demo of this asset). The Body of the camera is set to 'Hard Lock to Target', Aim to 'POV', and Recenter Target to 'Follow Target Forward'. This works fine. The camera has a Horizontal Axis Value Range ( to ), that limits the rotation of the camera, but I cannot figure out how to tie this to the rotation of the Follow component (the head of the avatar). When I walk my character around, the camera can only rotate within the set Value Range angle that has it's 0 point in one absolute direction (let's say north), independent of the player's orientation. It seems to use World Orientation, but I don't know and wasn't able to find out where to change that. Does anyone know how I can change this behaviour?
0
Navigate UI with Dpad from Xbox controller on Mac Unity ? So, according to some documentation I found, the Xbox controller on Mac does not return Dpad presses as vertical horizontal axes As you can see, the Dpad is only recognized as buttons 5, 6, 7, and 8, and not as horizontal vertical axes. For my character's movement, I just created code that returns 1 or 1 for axis depending on the button pressed. It works perfectly fine. But then I found another problem UI navigation. I can't navigate my menus with the Dpad on Mac because the the EventSystem is expecting navigation via horizontal vertical axes, which the Dpad is not providing. Is there any way I can turn these Dpad button presses into real horizontal vertical axes in Unity's Input system? Or is there something else I can do to make UI navigation happen on a Mac, with the Dpad?
0
Transform.position is being changed, but character is not moving back to it when told I'm trying to make a respawn point for my car to jump back to if it presses a button. I can see, using the Print() lines, that all the variables are correct and the methods are being triggered when expected. But the car doesn't go back to the spawnpoint like I want it to. The velocity part seems to take effect and work ok, but the rotation and position part does nothing. I tried several different variations of this code (ie. GetComponent lt gt and setting a public player variable (even though I am already in the player with this script)). Like I said I tried making a public Player and setting the transform p and r on that. I also tried GetComponentByParent lt Transform gt and setting like that. I've tried a few other variations of that too. And I get the same results. Here is the bit of code I think is relevant, if you actually need to see more please let me know. public void OnTriggerExit(Collider other) if (other.gameObject.tag "RespawnTrack") print("respawn point added upon Trigger Exit") recordedTransformAtRespawnTrack transform recordedVelocityAtRespawnTrack rb.velocity 0.25f print("rotation was X,Y,Z " recordedTransformAtRespawnTrack.rotation.x " , " recordedTransformAtRespawnTrack.rotation.y " , " recordedTransformAtRespawnTrack.rotation.z) print("position was X,Y,Z " recordedTransformAtRespawnTrack.position.x " , " recordedTransformAtRespawnTrack.position.y " , " recordedTransformAtRespawnTrack.position.z) public void CheckToRespawnCar() if (isRacing) if (CrossPlatformInputManager.GetButtonDown("Jump")) print("RESPAWN TRIGGERED BY PRESSING BUTTON") transform.position recordedTransformAtRespawnTrack.position transform.rotation recordedTransformAtRespawnTrack.rotation rb.velocity recordedVelocityAtRespawnTrack
0
On changing a voxel, don't recombine everything again, only modify the changed parts? I'm working on a voxel based game, where destructible structures are made out of cubes. (Some of them has 3000 voxels) I solved the framerate issues by combining them, but after making it able to handle multiple materials, calling the method causes a framerate drop. And it's annoying during runtime, because currently it recombines the whole structure when a voxel is changed (changed material, destroyed voxel, etc). One plan of mine is to decomposite the structures into smaller chunks, and only recombine the affected chunks instead of the whole structure. This increases drawcalls, but decreases framerate drops. By finding a good chunk size and chunk "making" heuristic, it would work I think. My other plan is to modify the combined mesh based on the affected voxels. For example when a voxel is destroyed, find its vertices in the combined mesh, and remove them. Or change those faces' material, etc. But I don't know how to do this. The bottleneck of my mesh combining algorithm is this private static Mesh CombineMeshes(MeshFilter meshFilters, List lt Material gt materials) Each material will have a mesh for it. var subMeshes new List lt Mesh gt () foreach (var material in materials) Make a combiner for each (sub)mesh that is mapped to the right material. var combiners new List lt CombineInstance gt () foreach (var meshFilter in meshFilters) The filter doesn't know what materials are involved, get the renderer. var renderer meshFilter.GetComponent lt MeshRenderer gt () lt (Easy optimization is possible here, give it a try!) Let's see if their materials are the one we want right now. var sharedMaterials renderer.sharedMaterials for (int i 0 i lt sharedMaterials.Length i ) var sharedMaterial sharedMaterials i if (sharedMaterial ! material sharedMaterial null) continue This submesh is the material we're looking for right now. CombineInstance ci new CombineInstance() ci.mesh meshFilter.sharedMesh ci.subMeshIndex 0 With zero it works with "i", every voxel in the structure will have every damagelayer. ci.transform meshFilter.transform.localToWorldMatrix combiners.Add(ci) Flatten into a single mesh. var mesh new Mesh() mesh.indexFormat UnityEngine.Rendering.IndexFormat.UInt32 mesh.CombineMeshes(combiners.ToArray(), true) subMeshes.Add(mesh) foreach (var meshFilter in meshFilters) meshFilter.GetComponent lt MeshRenderer gt ().enabled false The final mesh combine all the material specific meshes as independent submeshes. var finalCombiners new List lt CombineInstance gt () foreach (var mesh in subMeshes) CombineInstance ci new CombineInstance() ci.mesh mesh ci.subMeshIndex 0 ci.transform Matrix4x4.identity finalCombiners.Add(ci) var finalMesh new Mesh() finalMesh.indexFormat UnityEngine.Rendering.IndexFormat.UInt32 finalMesh.CombineMeshes(finalCombiners.ToArray(), false) return finalMesh Could you recommend something? Thanks!
0
Update dependent values of Serializable C classes on Inspector I have some data types' properties that depend on the input given into other attributes, but I haven't found in the Unity's API an elegant way to update them automagically on the Inspector. As an example, let's say I have a struct that has a divider value. Since I want to save division computations, I also have on the class a multiplicative inverse value that depends on the divider's, so I'd rather multiply instead of dividing. Example Code Snippet Serializable public struct SomeNumbers SerializeField private float divider private float multiplicativeInverse When the divider is set, the multiplicative inverse is also set. public float Divider get return divider set divider value multiplicativeInverse (1f divider) public float MultiplicativeInverse get return multiplicativeInverse private set multiplicativeInverse value Constructor. public SomeNumbers(float divider) this() Divider divider public class ExampleScript MonoBehaviour public float value public SomeNumbers numbers void Update() float result (value numbers.MultiplicativeInverse) Instead of (value numbers.divider)... Debug.Log("Result " result.ToString()) What I'd like, is that each time I change the divider's field, the value under the hood (this case the multiplicative inverse) also gets changed, as if I used the Divider's setter. Since the idea is to have an independent data type, the approach of using OnValidate on a class that contains this struct would not be applicable, since that would be a hard case. I could also set the Divider's setter on each class at Start Awake do that for me, but that would be prone to be forgotten. I know about Property Drawers , but I am not sure if that would be the right approach. I hope the question was clear enough, if not make me know so I correct it. Thanks in advance.
0
Need an option to send camera output as video or frames in Unity3d 2017 Tools I've used in Unity 5.x are breaking my 2017 scene... and I do not see a way to output video or frames from Cinemachine (although I am trying to understand all of its features). What is the best way in a mandatory C Unity 2017 workflow to capture camera output within Unity not a screen grab? No postprocessing needed... just frames! In the past I have used Renderator Pro and VR Rocks, neither of which seem at the moment to support 2017 using deprecated code. SOLUTION ROCK VR Does indeed work with Unity 2017... although not exactly the way I have modified it for 5.x.... but going back to stock import of resources and rebuilding works well.
0
How to check if grounded with rigidbody Does anyone have a better way to make an object with a rigidbody check for ground and then jump, right now I wrote a script where a raycast is cast downwards and it checks for distance but then I discovered that a player can still jump when close to the ground and when I decrease the distance amount on raycast then the jumping works a few times (5 or 6) and then stops working, so I had to increase the distance a bit and add a delay so the player can't jump for some time after a jump. But I think there might be a better way of doing it. So does anyone have suggestions on how can I improve my script or what other method I can use to make a character with a rigidbody to check if grounded and jump?
0
Controlling noise density I'm trying to fake terrain blending by using an opacity mask on my road mesh to reveal the grass underneath. I'm currently multiplying some Perlin noise by a Rectangle node displaying my texture at 80 width which is giving me the following Obviously this doesn't look great for reasons that should be apparent. The blotches are unnaturally spaced and they abruptly end with a sharp line at the end of the texture. What I would like to do is generate noise that looks more along the lines of this Is there a way to apply some sort of gradient to my noise to achieve this? I know I can just use the texture itself but I would like to be able to adjust properties like the extent of the noise during runtime.
0
Import blender camera with key frames to unity? I am wondering if I can take a camera tracked camera from blender and import it into unity. Is there any way to do this? Please let me know! Thanks in advance.
0
Unity order issue with TilemapRenderer.Render I'm using unity, with 2D Tilemaps (I'm doing something like an RPG) I want to have a Tile which should be rendered with a random sprite. When I use a tile like a tree that is bigger than the tile size and RandomTile, the draw order seems to get confused. Even if the sort order on the Tilemap Renderer is set appropriately, some of the tiles are drawing on top of the other tiles with no consistent pattern. After stepping through with the Frame Debugger, it looks like all tiles with the same sprite are drawn at the same Draw Dynamic event under TilemapRenderer.Render. I'm using the following script using System using System.Collections using System.Collections.Generic if UNITY EDITOR using UnityEditor endif using UnityEngine namespace UnityEngine.Tilemaps Serializable public class RandomTile Tile SerializeField public Sprite m Sprites public override void GetTileData(Vector3Int location, ITilemap tileMap, ref TileData tileData) base.GetTileData(location, tileMap, ref tileData) if ((m Sprites ! null) amp amp (m Sprites.Length gt 0)) long hash location.x hash (hash 0xabcd1234) (hash lt lt 15) hash (hash 0x0987efab) (hash gt gt 11) hash location.y hash (hash 0x46ac12fd) (hash lt lt 7) hash (hash 0xbe9730af) (hash lt lt 11) Random.InitState((int)hash) tileData.sprite m Sprites (int) (m Sprites.Length Random.value) if UNITY EDITOR MenuItem("Assets Create Random Tile") public static void CreateRandomTile() string path EditorUtility.SaveFilePanelInProject("Save Random Tile", "New Random Tile", "asset", "Save Random Tile", "Assets") if (path "") return AssetDatabase.CreateAsset(ScriptableObject.CreateInstance lt RandomTile gt (), path) endif if UNITY EDITOR CustomEditor(typeof(RandomTile)) public class RandomTileEditor Editor private RandomTile tile get return (target as RandomTile) public override void OnInspectorGUI() EditorGUI.BeginChangeCheck() int count EditorGUILayout.DelayedIntField("Number of Sprites", tile.m Sprites ! null ? tile.m Sprites.Length 0) if (count lt 0) count 0 if (tile.m Sprites null tile.m Sprites.Length ! count) Array.Resize lt Sprite gt (ref tile.m Sprites, count) if (count 0) return EditorGUILayout.LabelField("Place random sprites.") EditorGUILayout.Space() for (int i 0 i lt count i ) tile.m Sprites i (Sprite) EditorGUILayout.ObjectField("Sprite " (i 1), tile.m Sprites i , typeof(Sprite), false, null) if (EditorGUI.EndChangeCheck()) EditorUtility.SetDirty(tile) endif Is there any way to fix it?
0
Having the same camera in all scenes I have 100 scenes, each scene has a camera, but I want only the camera from scene 1 to exist in each scene that I appear in. I use the function DontDestroyOnLoad() to make the camera exist in each scene but I always find my self with another camera that I don't want. Any ideas? thank you in advance.
0
Visual Studio not recognizing Unity's new Input system I'm attempting to learn Unity's new input system, but when I try to add using UnityEngine.InputSystem to my code it gets a red squiggly line under it. It doesn't cause any compiler errors, but it's very annoying. How do I get Visual Studio to recognize this so Intellisense will work again?
0
How can I turn off the sound from another scene? I attached music file to my first scene and thanks to following javascipt code, sound continues without stopping in other scenes. public static var object SingletonMusic null function Awake() if( object null ) object this DontDestroyOnLoad(this) else if( this ! object ) Destroy( gameObject ) My problem is that I want to turn off the sound from the button in the another scene (setting scene) so that I added a new button to my setting scene and attached the following javascript code to the button that I have created. Javascript code var objects AudioSource SingletonMusic.object.GetComponent(AudioSource) if( objects.isPlaying ) objects.Pause() else objects.Play() However, it gives following errors If I start the game from Setting scene I get this error If I start the game from first scene and then, go to Setting scene I get this error
0
How to manage ammo when firing and reloading I have this script and I need to fix one thing which is count correctly the number of bullets I have. public GameObject ebullet public Transform Bullet position, target public int ammo 200 public int ammo Hold 600 public bool reload false public bool readyToShoot Update is called once per frame void Update() if (ammo 0) ammo Hold ammo Hold 200 ammo 200 if (reload true amp amp ammo Hold gt 0) ammo Hold ammo Hold ammo reload false if (readyToShoot true) Quaternion rotation Quaternion.LookRotation(target.position transform.position) transform.rotation Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime 5.0f) GameObject bullets Instantiate(ebullet) as GameObject bullets.transform.position Bullet position.transform.position 1 Rigidbody rb bullets.GetComponent lt Rigidbody gt () rb.velocity transform.forward 100 Destroy(bullets, 2f) ammo else print("Don't Shoot") end update
0
How can I load multiple scenes in background? I want to queue the loading of multiple scenes in background and show all of them at the same time when all complete their loading. The only idea I have by reading the docs is to root all objects in every scene I want to load this way in a single GameObject that is disabled by default and when all my LoadSceneAsync finishes its work, I can them activate each scene root GameObject. Without doing that, I have all related scenes being loaded and being showed in the screen at different times and this is just not acceptable. I'm creating this question because I believe there must be a better way to accomplish that rather than rooting all the scene into a single game object.
0
.blend scenes are not showing texture in Unity I am new to Unity and Blender. I am getting a problem when importing .blend files into Unity in Unity scenes the textures created in Blender are not showing. But there are no problems with color. How can I fix this problem?
0
How to draw a NavMesh Path to a destination without traversing the path in Unity3d? I have a set of pre determined destinations. When the user chooses any one of those destinations, the path to the destination should be drawn, similiar to google maps. I am trying to do this in unity, but not able to figure out just how.
0
gpu rotate a texture2d or rendertexture How does one gpu rotate a Texture2D or RenderTexture using Unity c ? Or, is that possible? I think it might be something like this... I'm also trying to understand how gpu scale seems to work here? Internal unility that renders the source texture into the RTT the scaling method itself. static void gpu scale(Texture2D src, int width, int height, FilterMode fmode FilterMode.Trilinear) We need the source texture in VRAM because we render with it src.filterMode fmode src.Apply(true) Using RTT for best quality and performance. Thanks, Unity 5 RenderTexture rtt new RenderTexture(width, height, 32) Set the RTT in order to render to it Graphics.SetRenderTarget(rtt) Setup 2D matrix in range 0..1, so nobody needs to care about sized GL.LoadPixelMatrix(0, 1, 1, 0) Then clear amp draw the texture to fill the entire RTT. GL.Clear(true, true, new Color(0, 0, 0, 0)) Graphics.DrawTexture(new Rect(0, 0, 1, 1), src) Edit The input image is rotated 90 degrees ccw to fit in the left part (replacing the beige with pink dots) of this texture (no alpha is needed). If you want some numbers, it's a rect from 0,0 to new Vector2(794, 1024)
0
CS0118 framerate is a field but a type was expected I'm making a mobile game in Unity and I'm trying to write a script that will set the game to either 30 or 60 frames per second based on a public bool, but I am getting error CS0118 on line 12 with fps.framerate is a 'field' but a 'type' was expected. I am pretty new to Unity so I need help with this? using System.Collections using System.Collections.Generic using UnityEngine public class fps MonoBehaviour public fps framerate Use this for initialization void Start () framerate GameObject.Find("gameSettings").GetComponent lt framerate gt () lt error CS0118 if (framerate true) Application.targetFrameRate 60 else Application.targetFrameRate 30
0
Is it possible to import UV maps in Unity3D without manually importing the associated texture? When i import an object from Maya with a defined UV map i have to manually import the texture (image) and assign it to the material. Is there a way to keep the materials texture reference from Maya when importing into Unity?
0
Develop a Wii U game without official dev kit I was looking for unity for Wii U game development. But it seems that I need the approval of Nintendo to have the software (and special hardware) (ref https wiiu developers.nintendo.com). Is there a way to have the software and to replace the hard with an emulator ? I just want to make a game for fun, I can't afford the official SDK (Rumors says it about 5000) If it is possible, I would love to have some ressources (I couldn't find anything...) Thanks )
0
Bad quality of the sprite in Unity I need to import a few sprites (background platform and sky) into my game scene but it seems that their quality after importing into Unity is too bad (they are blurred). The original resolution of this two images is big enough (2048 X 400 for background) and they are looking very nice in standard Windows image viewer. Here are the settings for these two textures maxSize 2048 Format truecolor TextureType Sprite(2d) nGUI FilterMode point I am using Unity2D 4.5 Target resolution of my project is 1280 800. Can anyone help me to solve these problem? As you can see the grass on foreground looks very bloory (1 picture) Texture settings (2 picture) Original image (3 picture)
0
Move car at same speed I want to move car on each game play run with same speed. At present I was getting each time different velocity. I want to fix that. Here is game play area on which I was moving car At present I was moving car in infinite motion without any kind of control. When it collide with wall, it will its direction based on collision calculation. Here is my source code that I was using to move car void Start () direction new Vector2 (Random.Range ( 1f, 1f), Random.Range ( 1f, 1f)) void FixedUpdate () float angle Mathf.Atan2 (direction.y, direction.x) Mathf.Rad2Deg float targetRot Mathf.LerpAngle (myRigidbody.rotation, (angle 90f), 0.1f) myRigidbody.MoveRotation (targetRot) myRigidbody.velocity direction speed myRigidbody.MovePosition (myRigidbody.position direction Time.deltaTime speed) Debug.Log("vel mag " myRigidbody.velocity.magnitude) void OnCollisionEnter2D (Collision2D other) ContactPoint2D contact contact other.contacts 0 direction 2 (Vector3.Dot(direction, Vector3.Normalize(contact.normal))) Vector3.Normalize(contact.normal) direction Following formula v' 2 (v . n) n v direction 1 Dont know why I had to multiply by 1 but it's inversed otherwisae Vector2 reflectedVelocity Vector2.Reflect(direction, contact.normal) direction reflectedVelocity At present on each run of car, I was getting different velocity that I have checked via debug statement. So my target is to move car with same speed always.
0
How to change transform.position code to Rigidbody.AddForce? 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 That's how i do my movement, but i need to change it to Rigidbody.AddForce 'cause the way that i use right now makes my character doesn't collide with objects perfectly. Note What i mean with "perfectly" is, if you walk to the corner of walls, you can pass through it and that's the thing that i want to prevent.
0
Stuttering movement when approaching boundary I'm trying to limit my movement in the y axis by checking if the position will be within the boundaries after the Translate. If it is, only then do I translate the Player. public class Player MonoBehaviour private float speed 5.0f private float bottomY 4.37f void Start () transform.position new Vector3(0, 4, 0) void Update () Movement() void Movement () vertical movement Vector3 yTranslateVector Vector3.up Input.GetAxis("Vertical") speed Time.deltaTime float newYPos (transform.position yTranslateVector).y if (newYPos gt bottomY amp amp newYPos lt 0) transform.Translate(yTranslateVector) horizontal movement Vector3 xTranslateVector Vector3.right Input.GetAxis("Horizontal") speed Time.deltaTime transform.Translate(xTranslateVector) However, when I do this, the Player kind of pauses when approaching the boundary and then stutters forward towards the absolute limit upon releasing the key. I tried putting the Movement function in the Update and FixedUpdate method, but neither made any difference. Can anyone give me any insight into this?
0
Canvas not visible in my GearVR Project with Vuforia (Unity) I created a simple AR project with vuforia and my Samsung GearVR, like described here https developer.vuforia.com library articles Solution Integrating Gear VR and the AR VR Sample in Unity 5 3 and above . This works fine so far. Now I want to add some canvas elements, I don't want them to move, just fixed canvas elements. I tried to place my canvas on different positions in the scene Root Child of CameraRig Child of LeftCamera Child of TrackableParent Child of an ImageTarget in TrackableParent But for all of these cases the canvas is not visible. I know, this question is really specific, but maybe someone with knowledge in this specific thing can help me. This is my Canvas
0
Which size do I need to use in Blender to import to Unity I want to create a cube with different textures in Blender. But if I import the model to Unity 2017 the cube has not the same size as a cube with scale x,y and z 1 from Unity's default components. Which size do I need for my cube in Blender so it has the same size as a default cube in Unity?
0
Unity Tilemap one way collisions How can we get one way collisions using Tilemaps in Unity? There doesn't seem to be much online regarding this topic yet. From this link https answers.unity.com questions 1471156 how to make one way platforms using a tilemap.html, I got that we should use a Tilemap Collider 2D for collisions and not use a Composite Collider 2D. Finally, we need a Platform Effector 2D with One Way enabled. However, the resulting tiles all behave like normal tiles in that collisions occur along all edges. Here's what the inspector looks like for the tile map in question. The scene setup looks like this It looks like the tiles in the scene all have collision edges all the way around. What needs to be done to allow for one way platforms? Thanks! EDIT Here is the setup of the character Here is a view of what it looks like in game When jumping, the character unfortunately collides with the block above and is unable to pass through.