#💻┃code-beginner
1 messages · Page 60 of 1
@swift crag yes
Ah
Is there a rigidbody on the parent object?
If so, collision messages will go to it when a child collider touches something.
wait, but then the name would be wrong.
That doesn't mesh.
@swift crag RigidD on the children
try one thing: log trans.name in the RegisterLaser method
I just want to make sure you're, indeed, getting two different transforms
Yeah, the numbers on the enemy objects basically act as inputs for the math equation you're trying to solve. EX: shooting with a '2' and a '7' should produce a '2' and a '7' on the bottom of the screen where the X and Y on the screen are respectively, and then the player will either progress if the Z on bottom of the screen is a '9' (2 + 7 = 9) or recieve damage if the Z is any other number. The callback that @marsh glade mentioned makes sense, but I'm not quite sure how to implement that.
I assume you have a script that spawns these enemies somewhere ?
with newtonsoft.json, are you supposed to put "using newtonsoft.json" stuff at the top of ur script?
Yes, this is it https://hastebin.com/share/ayasoyigot.csharp.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yes. That lets you omit the namespace.
It lets you write JsonConverter instead of Newtonsoft.JSON.JsonConverter
yea that doesnt work
ah, it's Newtonsoft.Json. Not all-caps.
Hm, I'm not sure what else would cause this. Can you share the scripts?
in the package?
I'm not sure what "in the package" would be. I'm talking about adding this to the top of your script:
using Newtonsoft.Json;
are you using asmdefs?
Okay, so let's say you have two classes : A and B. If B has a callback "OnDestroyed", then A can say "I want to know when B is Destroyed, and when this happens, I want a specific method to be called, so I will subscribe to B.OnDestroyed"
You may need to restart your code editor and regenerate the external project files, since you've added a new assembly to the project.
reimport?
no. close your code editor, then go to preferences -> external tools and click "Regenerate project files"
then reopen your code editor
ahhh
I would also check that the package actually shows up in the package manager window.
In this case, you can add a variable "public Action<int> OnDestroyed;" in your enemy_script class, this is your callback. To invoke this callback, you need to use the function "OnDestroyed?.Invoke(math_number);" in the part of your script where your object is destroyed.
Now, to listen to a callback, you need to subscribe to it. For example, in your enemy_spawner class, whenever you spawn an enemy_script, you can say "enemy_script.OnDestroyed += MyMethod;", where "MyMethod" is a method located within the enemy_spawner class which accepts a single parameter of type int and returns void, so something like this "private void MyMethod(int math_number) { // Do stuff here }"
However, another issue here is that your class which spawns enemies is separate from the one which contains the answer. You might need to add a reference so that the two can communicate, for example, in enemy_spawner. That way, whenever an enemy_script is destroyed, MyMethod is called with the math_number of the enemy_script that was just destroyed. With a reference to math_generator here, you can pass that value to your math_generator.
@swift crag Made a reference to the children in the inspector and printed this at parent start. It looks correct now right?
Yes, that looks right.
I presume you're just trying to get a list of all the children?
it worked
If so, I wouldn't use physics at all. I'd just have the parent use GetComponentsInChildren to find all of the child components.
I should've asked about that sooner :p
I am unsure what was your problem was, though. I wonder if the rigidbodies weren't "ready" yet?
I have not seen that before.
the first child's "up" direction points in the +X direction -- to the right
and the second one points in the +Y direction -- up
@swift crag I am just trying to map out the children rotations so that if something goes in the first box it should come out on the other side with the correct rotation. Since i dont know what orientation the parent will be i need to know where the transform.up is on every child object.
Yep, that's very reasonable.
thanks for the help btw 😄
Was the trigger message used to detect when a laser hit the first box?
yes sir
Did you happen to have a field named transform in the child script?
I know you have one named name, since the name ("A" / "B") didn't match the name of the game object ("Link Child" / "Link Child 2")
@swift crag This is my child script. Ignore the red line i am removing the transform since i dont need it any more
Callbacks and delegates
huh, ain't got any other ideas.
Were the triggers happening on the very first frame of the game, or were they running later?
The method doesn't care what collider hit it, so they could be getting activated instantly
Hello. I have europe map texture and I want to make mesh from it but the problem is that the map is not rendering completely. Code
public class TerrainGenerator : MonoBehaviour
{
public Texture2D europeMap;
public float heightMultiplier = 10f;
public Material terrainMaterial;
void Start()
{
GenerateTerrain();
}
void GenerateTerrain()
{
int width = europeMap.width;
int height = europeMap.height;
GameObject terrain = new GameObject("EuropeTerrain");
MeshFilter meshFilter = terrain.AddComponent<MeshFilter>();
MeshRenderer meshRenderer = terrain.AddComponent<MeshRenderer>();
Mesh mesh = new Mesh();
Vector3[] vertices = new Vector3[width * height];
int[] triangles = new int[(width - 1) * (height - 1) * 6];
int triangleIndex = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Color pixelColor = europeMap.GetPixel(x, y);
float heightValue = pixelColor.r * heightMultiplier;
vertices[y * width + x] = new Vector3(x, heightValue, y);
if (x < width - 1 && y < height - 1)
{
int topLeft = y * width + x;
int topRight = y * width + x + 1;
int bottomLeft = (y + 1) * width + x;
int bottomRight = (y + 1) * width + x + 1;
triangles[triangleIndex] = topLeft;
triangles[triangleIndex + 1] = bottomLeft;
triangles[triangleIndex + 2] = topRight;
triangles[triangleIndex + 3] = topRight;
triangles[triangleIndex + 4] = bottomLeft;
triangles[triangleIndex + 5] = bottomRight;
triangleIndex += 6;
}
}
}
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
meshFilter.mesh = mesh;
meshRenderer.material = terrainMaterial;
terrain.transform.position = Vector3.zero;
}
}
You're not setting UVs on your mesh
UVs are how textures are mapped to 3D meshes
I'm kinda curious why you're making a custom mesh here anyway if it's just a flat plane
why not use the built in Quad mesh?
It's not just an image -- it's supposed to be bumpy
words are failing me right now
uhh, terrain!
ok well - the answer is clear, there is no attempt to do any UV mapping in this code.
yeah, that's going to need a fix
ah, there is indeed elevation here
Is the problem that the mesh isn't filling out that entire square?
the rect tool is throwing me off too
yeah
what does this thing look like?
what am i supposed to be searching
oh wrong channel
Guys, I’m wondering how to add animated objects in pause UI cuz time.scale = 0
yep, it should make mesh from this
I am trying to get a box to follow the mouse when the user clicks and drags on it, on the BoxController script I just have the OnMouseDrag() method to call the Move() method in the LevelController and then a OnMouseUp() method to call the Release() method in the LevelController. The issue is that everything appears to be recognized the way I want it to, as in the inspector values are changing correctly, but the boxes don't move.
Shown is my LevelController, I'm wondering if there is something I missed here that is causing the boxes to not move. Sorry this is my first time using a spring joint.
public class LevelController : MonoBehaviour {
public SpringJoint2D springJoint;
private Vector3 worldMousePos;
public void Move(Rigidbody2D obj) {
if (!springJoint.connectedBody) {
Debug.Log("Moving " + obj);
springJoint.connectedBody = obj;
}
worldMousePos = Camera.main.WorldToScreenPoint(Input.mousePosition);
springJoint.connectedAnchor = worldMousePos;
}
public void Release() {
Debug.Log("Released!");
springJoint.connectedBody = null;
}
}
It looks like you're just attaching your object to a world space position and not another Rigidbody
that will simply anchor it stationarily in place
hm, after messing around with it i think my initial approach is just incorrect for my goal
i did try swapping things around because i noticed that the connected body in the official unity tutorial seemed to be the "anchor"
A typical approach is to create an invisible kinematic Rigidbody which you move around with the mouse (in FixedUpdate via rb.MovePosition) and attach the object to that with a joint.
I don't need texture rn, I meant that the mesh does not render the entire map, only part of it
Does anyone know how to fix this?
"failed to create coreclr, hresult: 0x80004005"
is there an easier way to do this? this feels like it's not correct Fixed it
public class LevelController : MonoBehaviour {
public Rigidbody2D mousePoint;
private void Start() {
mousePoint = this.GetComponentInParent<Rigidbody2D>();
}
yeah that's because of your UVs
soo what should I do
fix the UVs
still nothing changes
void GenerateTerrain()
{
int width = europeMap.width;
int height = europeMap.height;
GameObject terrain = new GameObject("EuropeTerrain");
MeshFilter meshFilter = terrain.AddComponent<MeshFilter>();
MeshRenderer meshRenderer = terrain.AddComponent<MeshRenderer>();
Mesh mesh = new Mesh();
Vector3[] vertices = new Vector3[width * height];
Vector2[] uv = new Vector2[width * height];
int[] triangles = new int[(width - 1) * (height - 1) * 6];
int triangleIndex = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Color pixelColor = europeMap.GetPixel(x, y);
float heightValue = pixelColor.r * heightMultiplier;
vertices[y * width + x] = new Vector3(x, heightValue, y);
uv[y * width + x] = new Vector2((float)x / (width - 1), (float)y / (height - 1));
if (x < width - 1 && y < height - 1)
{
int topLeft = y * width + x;
int topRight = y * width + x + 1;
int bottomLeft = (y + 1) * width + x;
int bottomRight = (y + 1) * width + x + 1;
triangles[triangleIndex] = topLeft;
triangles[triangleIndex + 1] = bottomLeft;
triangles[triangleIndex + 2] = topRight;
triangles[triangleIndex + 3] = topRight;
triangles[triangleIndex + 4] = bottomLeft;
triangles[triangleIndex + 5] = bottomRight;
triangleIndex += 6;
}
}
}
mesh.vertices = vertices;
mesh.uv = uv;
mesh.triangles = triangles;
mesh.RecalculateNormals();
meshFilter.mesh = mesh;
meshRenderer.material = terrainMaterial;
terrain.transform.position = Vector3.zero;
}
hello, I'm working on a game where there will be a bunch of cars using the same material but I want to be able to make slight changes to the albedo color and metallic on the material and only effect one car instead of all of them.
the current approach I'm using is giving me problems though.
I get "UnassignedReferenceException: The variable oldCarMaterial of CarStats has not been assigned."
but when I look at the script in the inspector it gets the correct reference of the material on the Mesh Renderer.
here is the code I'm using:
private void Start()
{
oldCarMaterial = meshRendererCar.sharedMaterial;
}
public void RandomizeCarColor()
{
Color customColor = new Color(0.4f, 0.9f, 0.7f, 1.0f);
oldCarMaterial.SetColor("_Color", customColor);
}
oldCarMaterial.SetColor("_Color", customColor);
is where the exception is coming from
show the full stack trace of the error
it's possible RandomizeCarColor is running before Start
btw since you're modifying the sharedMaterial you will modify the color of all the cars at once
So i got it to move the boxes but now they seem to just fly off the screen and the moving of the rigibody that is following the mouse is super delayed, it takes a few seconds to stop changing almost like it's slowly following the mouse instead of just equalling its position...
public class LevelController : MonoBehaviour {
public Rigidbody2D mousePoint;
private void FixedUpdate() {
mousePoint.MovePosition(Camera.main.WorldToScreenPoint(Input.mousePosition));
}
public void Move(SpringJoint2D springJoint) {
if (!springJoint.connectedBody) {
Debug.Log("Moving " + springJoint);
springJoint.connectedBody = mousePoint;
}
}
public void Release(SpringJoint2D springJoint) {
Debug.Log("Released!");
springJoint.connectedBody = null;
}
}
how and where are Move and Release getting called?
also did you make the mouse Rigidbody kinematic?
Hi
through the controller on the boxes i want to be dragged:
public class BoxController : MonoBehaviour {
public LevelController levelController;
private SpringJoint2D springJoint;
private void Start() {
this.springJoint = this.GetComponentInParent<SpringJoint2D>();
}
private void OnMouseDrag() {
levelController.Move(this.springJoint);
}
private void OnMouseUp() {
levelController.Release(this.springJoint);
}
}
you're calling Move every time the mouse moves. You should just call it at the beginning
OnMouseDown
oh it was not kinematic, though i changed that
Honestly don’t know how to code
is there any support for displaying a key prompt as a key? for instance, rather than press the 'e' key to interract it'd show an actual e key
what does "an actual e key" mean? An Image?
yes
You'd need to build that yourself
gotcha, ty
the issues shown in a clip:
do the boxes continuously move? or are they moving to a specific position?
your mouse point object is in timbuktu
and it's because of this:
mousePoint.MovePosition(Camera.main.WorldToScreenPoint(Input.mousePosition));
you use WorldToScreenPoint when you wanted ScreenToWorldPoint
here is the full stack trace
right so you're spawwning a car
and calling a function on it
You know Start won't run until a frame later right?
You should be using Awake for initialization like that
oh alright, I'll try that and see how it goes
lol, whoops
I tried this but now the position isnt updating at all
mousePoint.MovePosition(Camera.main.ScreenToWorldPoint(Input.mousePosition));
Are you using a perspective camera or orthographic?
whatever is default upon creating a scene, idk what that is sorry
you can always just look
perspective
That's your problem
perspective camera with Camera.main.ScreenToWorldPoint(Input.mousePosition) will just return the same thing as Camera.main.transform.position
use Plane.Raycast instead
or switch to an orthographic camera
worlds strangest issue goes to this block of code
the function IsLookingDown is a boolean function that works completely fine (hopefully), shown by the debug statement outside of the input if statement. However, whenever I press Q to go down the if statement, the debug log inside the if statement always reports it as true. also the force is never applied as a result of this weird issue
Your if statement is checking if you're NOT looking down
yeah, its meant to only add force when isLookingDown is false
ok so what's the issue exactly then?
it's saying "throwing: false" but there's no force being added?
everything works, just needs a lot of smoothing and such, but now they orbit when let go...
Debug.Log("throwing: " + playcam.IsLookingDown()); inside the input if statement always results in being true, looking down or not, despite Debug.Log(playcam.IsLookingDown()); outside the input if statement being completely fine
that means the joint is not releasing
do you have Collapse turned on in your console?
BTW you really should be using ForceMode.Impulse or ForceMode.VelocityChange for this.
collapse is turned on so its easier to see yeah
that makes it impossible to tell what's going on then though
because you can't tell in what order things are being printed
hence why the one inside the input statement has that "throwing" bit
also there's no guarantee that the IsLookingDown() function doesn't have side effects
I would just get rid of the one outside the if and turn off collapse
IsLookingDown() is just
that's not a good way to check that
return Vector3.Angle(transform.forward, Vector3.down) < 90;``` will do it more reliably
euler angles are a shitshow
why not?
because of this^
(-45, 0, 0) is equivalent to (315, 0, 0) which is also equivalent to (0, 90, 45)
so just reading the x part won't tell you all that much useful
I was able to fix this by setting the .isKinematic bool to true when releasing, is this the proper way to do so? it appears that before starting the scene they are connected to this joint which makes no sense to me (ss of scene view not in play) idk if this is an issue or not tbh.
I just want them to be moved when dragging then stop completely when let go, currently they just preserve momentum but they're not orbiting lol, how can i just get them to stop?
you have the joint there so the joint is active
there is no way to disable a joint
you can only destroy the joint or attach it to a world position or to an object
You can also just set the velocity to Vector3.zero instead of making it kinematic
the objects will maintain their velocity when you release otherwise
this seems to be always reporting false, also replaced the 90 with down - lookingDownLeniancy which is 30
are you ever actually looking down that far?
(within 30 degrees of straight down)?
also which object is this script attached to?
It'd probably be better to check if the dot product of transform.forward and Vector3.down is greater than some threshold percent like 0.9f
its not 30 away from 90 its 30 in total
I don't understand what that means
this code is checking how far away from straight down you're looking
if it's 90 it will return true whenever you are looking even slightly down
past directly horizontal
down is 45, its the maximum angle you can look down in this game instead of 90
if it's 30 it will return true only if you're looking within 30 degrees of straight down
well don't use 30 then because that's lower than the max (and therefore impossible)
use 90 to start with
and tune it from there
lookingDownLeniancy exists so you dont have to be looking exactly down for it to return true, so its a range of 30 to 45 where it counts as 'looking down'
and I'm telling you you should be using 90 - 30 then
aka 60
not 30
30 is impossible
return Vector3.Angle(transform.forward, Vector3.down) < (90 - lookingDownLeniancy);
this code works differently
please listen
what 'direction' is Vector3.Angle(transform.forward, Vector3.down) facing?
I don't understand what the question means
it's calculating an angle between two different directions
- the direction you're looking
and - straight down
Have you tried this code?
can someone help me? Why vscode doesn't autocomplete code. I tried unchecking omnisharp use modern net as suggested in https://github.com/dotnet/vscode-csharp/issues/5228 but it didnt work
Environment data dotnet --info output: mk@mk:~$ dotnet --info .NET SDK (反映任何 global.json): Version: 6.0.300 Commit: 8473146e7d 运行时环境: OS Name: ubuntu OS Version: 20.04 OS Platform: Linux RID: ubunt...
Follow the whole VSCode guide in
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
this vid shows an older project of mine that has a super bulky, and imo stupid, implementation of the functionality i want compared to what i currently have with the spring joint, i'm trying to configure the values in the spring join to more closely match the first part of the clip but so far i cant really get it to have the same feel, the spring joint tends to orbit the mouse too much when moving quickly. Am I approaching this problem wrong by trying to use spring joint? I was told back when i was here for advice on the implementation in the first part of the clip about half a year ago that i should try using spring joint instead for an easier implementation.
it really depends what you're trying to do
why are you using SpringJoint in the first place?
Hey, not sure if it's the right channel to ask, but I've been struggling for the past two hours on the following problem
i could simply teleport the boxes to the mouse position but i am using spring joint so that they instead smoothly go over to the position
You could also use MoveTowards or SmoothDamp
I'm trying to implement a crosshair in my vr application using google cardboard, therefore I had to load an image in front of the camera in order to see the crosshair, however it goes "inside" objects rendered on the scene
my question is how can I force rendering? I didn't manage to change the shaders and i've been stuck for a while now
Already did, but it didn't work for me
Remove the Visual Studio Code Editor package in Unity, they both use the Visual Studio Editor package
Does VS Code say anything about an SDK being needed?
The extension and package is up to date though.
could you elaborate or should I do some self-study on this first?
The documentation pages describe how they work and have examples
MoveTowards moves at a steady rate towards a destination
SmoothDamp behaves like a spring
it was the fault of unity limits. I had to add
mesh.indexFormat = IndexFormat.UInt32; and it works
that ended up working and i stopped using .sharedMaterial so that i could change the materials individually.
but i'm trying to figure out how to save the changes to the instanced materials so that when i load the game back up the cars have the same colors they spawned in with. is it possible to save this changed material for each car? or for each car should I save the random values I generated for the color change and then when the game loads up change the color in Awake?
no you wouldn't save the material
you need a saved game system
you'd just save the colors
you could also use a seed value to generate the same sequence of random colors assuming you always have the same number of cars etc
Can anyone see what I have wrong here? In the inspector I have dragged in two empty GOs as the teleport locations:
private void InputManager_OnDismountAction(object sender, System.EventArgs e)
{
foreach (var tpLocation in _teleportPlayerLocations)
{
float distanceFromTeleportLocationToJetski = Vector3.Distance(tpLocation.position, transform.position);
if (distanceFromTeleportLocationToJetski <= TELEPORT_DISTANCE_BUFFER) // buffer is set to 20f.
{
Debug.Log("Dismount pressed");
}
else
{
Debug.Log("Can't dismount, not on shore! Distance away: " + distanceFromTeleportLocationToJetski);
}
}
}
I'm trying to specifically go to the second log/position. It's weird because when I go to the first GO, it works, just not this second one, even though I'm within distance.
print out TELEPORT_DISTANCE_BUFFER
also InputManager_OnDismountAction(object sender, System.EventArgs e) the EventArgs pattern is not recommended for Unity
since you're not using any parameters here you can just use System.Action as the delegate type and have no parameters.
If you do need parameters you can make a custom delegate type or simply an Action<T, T1> etc style delegate
Thanks, PB. Just realized, I had a magic number written in there as 20f earlier, then realized that was way too large, and set up the buffer variable, at 10f. My oversight, but thank you.
Thanks, I will change. Why is it not recommended for Unity though?
creating instances of System.EventArgs generates garbage since it's a heap allocated class
this leads to GC hiccups
(same reason it's generally encouraged to avoid frequent allocations/garbage collection in general)
Ah didnt realize that's creating instances, thank you.
As an additional question, I've updated to using Action. I have an input manager script where i am doing:
public event Action OnInteractAction;
private void OnEnable()
{
_input.Player.Interact.performed += Interact_performed;
}
// unsubbing in OnDisable()
private void Interact_performed(InputAction.CallbackContext context)
{
OnInteractAction?.Invoke();
}
Then in my PlayerController.cs class I sub to them in Start():
InputManager.Instance.OnInteractAction += InputManager_OnInteractAction;
Should I be subbing and unsubbing as well in OnEnable() and OnDisable() in my PlayerController.cs class? I was thinking there might be some race conditions if I did that.
At the very least should I be doing OnDisable() to unsub in PlayerController.cs?
you should always unsub in OnDisable to match every subscription in OnEnable yes
Ok even though I'm subbing in Start() within the classes that use the Input Manager set up.
I don't think I could OnEnable() across them all due to race conditions. Maybe I'm wrong.
If subbing in Start then unsub in OnDestroy
note when unsubbing you'll want to do this:
var im = InputManager.Instance;
if (im != null) im.OnInteractAction -= InputManager_OnInteractAction;```
this will prevent MissingReferenceException when the scene is being unloaded
Cool, thanks.
How can I make a button make infinite scenes?
What is an infinite scene and what does a button have to do with it?
I am making a 3D animation and modeling application, there is also an application of that when you create a new project, a .proj file appears.
SceneManager has a method called CreateScene that creates a new scene at runtime, which can have any name you want https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.CreateScene.html
doesn't sounds like infinite scenes to me. Sounds like one thing.
Look at the photos
huh how's it related to infinite scene?
I think there's a language barrier. Maybe try using Google translate to convey your thoughts...
Nothing infinite here. Do you mean how to show a file selector?
I suspect they actually mean just creating a new scene/project. As in, each time you press [new] it does so ... hence infinite.
It's like I was going to create a Minecraft world but in unity within the game
or maybe make virtual folders in the unity build
sounds more like you need to learn about saving data / files instead of scenes
More or less so
start serializing some data in a file , go from there
json is easy to start with
well
does anyone know why this wouldn't shoot a Ray?
I tried debugging
but it says it's unreachable
Your IDE looks suspiciously underhighlighted, are you getting error highlighting and autocomplete?
I take that as a no then. The configuration steps are here !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
and yes, if you put a log after a return statement, how can it be reached? You just returned, you exited the function
Fix the debug as vertx said, and put a debug before the tag check too. You want to know how far it gets
I'll try that. Thanks.
yup configured IDE would def show you dark gray for code underneath return statement
If you still have not configured your IDE, that's the first thing you should do
did you read the steps at all?
I read em all
update is like the last step
so what about the Unity Workload in VS Installer
The workload, the settings in Unity's External Tools preferences
assuming you actually did all the steps, whats left is try regen project files or check the solution explorer if the solution needs rebuild
set to Unity
What is this referring to
Is there any way to make animated objects play when time.scale = 0?
I’m asking for second time
New to reading data from json files, experimenting with this tutorial in the first screenshot. I can't tell why my code (second screenshot) is throwing a nullreference error on the for loop.
I want to make pause menu like here, but the only way to pause game what I know is making time scale = 0
Have them use unscaled time
How?
Is it an option in animation/animation controller or where? Or I need to script it
ur list is null
Not enough info here but either the array or the wrapper object itself is null
Likely the json data isn't correct for that object
Yes it's an option on the animator or the state machine
Don't remember which
Ok I’ll check, thank you so much!
I suspect its because the array inside the list class isnt declared as an instance, but the tutorial code didnt do that, and it worked for them
not sure where mine differs
I told you why
Your json is incorrect likely
I had a json syntax error before and fixed it. What about the json file would be incorrect?
The shape of the data
It doesn't match the object
Yep the name is wrong
It's not called "weapon" in your class
It's called "lazerWeapon"
Of course it has to match
All the field names must match
How else would it know which data to put where?
thats the point of mapping an object 😛
granted with something like json.net you can create custom names and map them accordingly but thats another story
my brain is closer to our ape ancestors than most please bear with me
but due to this revelation, I must now restructure how my data flows
which i've been doing all day
fun
I have two weapon types, more like categories: Lazer and Physical. Lazer weapons just use a ray to fire, so there are a bunch of different numbers that go into making them unique from each other. Physical weapons spawn a projectile, such as a grenade launcher, rocket launcher, etc. Their only differing stat is reload time, the other stats are on the object they spawn.
I'm trying to group the stats of the two different weapon types into one location, which i can stream from in a weapon_pickup_manager, which can forward the data to the singular player_weapon script that handles the weapon behavior
Seems I'll need two different json files for each weapon type
despite my best efforts to put them in one place
your namings is very confusing not for nothin
Could rename them Raycast and Projectile weapons
but regardless, outcome is the same
weapon_pickup_manager has stats?
anyway you can totally put them in one file, don't see the problem
using System.Collections.Generic;
using Unity.VisualScripting.FullSerializer;
using UnityEditor;
using UnityEngine;
public class Weapon_Pickup_Manager : MonoBehaviour
{
[SerializeField] TextAsset weaponData;
Lazer_Weapon_List lazerWeaponList = new Lazer_Weapon_List();
[System.Serializable]
public class Lazer_Weapon
{
public string name;
public string type;
public int shotDamage;
public int shotPierceMax;
public int numberOfBulletsPerShotMax;
public float shotDistance;
public float shotReloadTime;
public float burstShotSpeed;
public float coneOfFire;
}
[System.Serializable]
public class Lazer_Weapon_List
{
public Lazer_Weapon[] lazerWeapon;
}
private void Start()
{
lazerWeaponList = JsonUtility.FromJson<Lazer_Weapon_List>(weaponData.text);
for(int i = 0; i < lazerWeaponList.lazerWeapon.Length; i++)
{
print(lazerWeaponList.lazerWeapon[i].name);
}
}
public void GivePlayerLazerWeapon(Player_Weapon_Manager player, Weapon_Name weapon)
{
switch (weapon)
{
case Weapon_Name.Pistol:
break;
}
}
public void GivePlayerPhysicalWeapon(Player_Weapon_Manager player, Weapon_Name weapon)
{
switch(weapon)
{
case Weapon_Name.Grenade_Launcher:
//player.SetPhysicalWeapon()
break;
}
}
}
//Defines whether each weapon is a lazer or physical weapon
public enum Weapon_Type { Lazer, Physical}
//Defines what weapon is picked up from a weapon_pickup
public enum Weapon_Name { Pistol, Rifle, Burst_Rifle, SMG, Shotgun, Grenade_Launcher, Bazooka, Ray_Gun}```
not finished yet obviously
thats what the tutorial did
i just blindly followed along
I do as the crystal guides
bad tutorial
very
should start at least naming things that match lol
This is cursed. Why is there a class that says lazer weapon list, then it holds an array and that's its only purpose?
THE TUTORIAL
Blame the tutorial
i give up, i will sleep and resume this dumbassery tomorrow
Thanks for the help
Tutorials should give you a sense more of what exists and what is possible, this wont be too fun to scale up later
start small, serialize one object
work your way to arrays
nested objects are tricky
and name things properly lol
names are the most difficult part
public class Wepons
{
public List<Lazors> LazorWeps { get; set; }
public List<Projectile> ProjectileWeps { get; set; }
}
```idk
as long as it matches the json lol use w/e
You dont need to short form for names, but you could take a look at the Microsoft convention on how to name things. Using underscores in the middle of names is like a python style thing or I think enums in java
Not really c# convention though
Ive only seen underscores used in C# for const and local variables that start with "m_" (though I personally dislike the latter convention, a lot of Unitys internal scripts will use it alot, and it just looks ugly but I get its purpose)
my const usually start with c_ 🥵
That m_ convention is mainly just old c++ stuff, so makes sense its old internal unity code
those are members not locals
Ah are those terms different? I thought they meant local to the class, as in they cannot be accessed outside of the class they were declared in
so i'm trying to make a holdable system and i can't find a way to disable myRB (which is a rigidbody)
if (Input.GetKey(holdButton) | Input.GetButton("A")) {
myRB.enabled = false;
transform.SetParent(holdingGameObject.transform, false);
} else {
myRB.enabled = true;
transform.SetParent(null);
}
in c# local means inside a method
Ah I see, thanks for the clarification
AFAIK, you cant directly toggle a rigidbody with .enabled, you could try freezing all the constraints instead and .Sleep() it, or enable .isKinematic so its not affected by physics
you'll want to make it kinematic, sleep will only work if it doesnt get hit by anything and does not move. Moving the transform will wake it up
Oh, interesting
you can also switch layer/ set ignore collisions
Hey everyone, I'm running into a bit of a brain ache right now, I was hoping someone could point me to the right direction, basically, I want to generate a terrain procedurally, by creating the tile meshes through code and placing them with perlin noise for height variations, my issue is I need my tile to get a distinct value based on it's surrounding tiles heights so it can be curved accordingly, I have a function that is highly inefficient and that doesn't work in cases where the height of the terrain varies to much, my question is, based on the surrounding tiles, how can I get a distinct value to work with to identify which configuration my tile should have? here are some images to demonstrate what I have so far, thank you in advance :
do you know about marching cubes?
a type of voxel right?
I also should have pointed out that the curve of the tiles are configured via an animationCurve which gives me more controle over the slope
no, its an algorithm
it builds the mesh from premade pieces based on an index assigned to each voxel
its efficient because it does lookup by that index with direct array access
oh, I wasn't aware of that, I'll look it up thank you! can I still use it if I want controle over curves, like this ? :
also, how efficient would that be if I want tiles with high resolution, let's say 64x64?
Thank you anyway I'll look it up, I think sebastian lague has a video on it. have a great day!
Can I set multiple ints to 0 ? like "heat, power, cornFlakes, flem=0;"
heat = power = cornFlakes = flem=0;
You legend, TYVM (:
Sorry if this is a simple question. The world is measured in meters and I’m trying to move my plane in m/s where the player can adjust their speed 0-10 to speed up or slow down how might I do this
In many different ways. What do you have so far?
Currently I’ve just getting the position of the plane and moving it by 1 so say we’re moving forward by 1 meter per second but I don’t think that makes sense or is correct since my plane will move so slowly
Share some code.
Instead of 1 you want to use some variable that changes value depending on what speed you want to have.
Currently I have float speed = 1.0f // move 1 meter per second? if (Input.GetKey(KeyCode.UpArrow)){ transform.position += Vector3.forward * speed * Time.deltaTime; }
Great. So you just need to assign a different(changing) value to speed
Ah ok so that’s correct? Think it’s gonna be quite slow though for the plane
You can assign whatever value you want🤷♂️
can I suggest using transform.Translate(Vector3.forward * speed * Time.deltaTime); it's much better than just doing position += something.
and yes, 1m/s is quite slow... for reference it's 3.6km/h or ~2.2mph, which is about your average walking speed
Alright thank you both!
Why?
transform.position += transform.forward * Time.deltaTime * speed;
transform.Translate(Vector3.forward * Time.deltaTime * speed);
these will be equivalent
I don't find one that much nicer to use than the other.
They're both the same, unless the transform rotates
the important difference is that your code doesn't care about the rotation of your transform
it'll always move in the +Z direction, no matter how the transform is rotated
using transform.forward instead of Vector3.forward fixes this
as does using the transform.Translate method
I just think it's important to explain the reason when you give advice to beginners.
I wouldn't say it's "much better", yes
Moves the transform in the direction and distance of translation.
If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes. (the x, y and z axes shown when selecting the object inside the Scene View.) If relativeTo is Space.World the movement is applied relative to the world coordinate system.
transform.Translate interprets its argument as a local direction, rather than a world direction
hence the difference
transform.position += Vector3.forward; // always goes in the world's forward direction
transform.Translate(Vector3.forward); // always goes in *your* forward direction
transform.position += transform.forward; // always goes in *your* forward direction
and then there's the funny fourth wrong option
transform.Translate(transform.forward); // ???
I mean, explain why "it's much better"
transform.position += transform.forward;```
I don't think I've used anything but this one
still not too sure if I should bother converting a lot of projectile logic over to rbs
lose out on a lot of positional functions I use otherwise
it might not be that much better as a single occurrence, or in the given example, more... a syntax, (practically non-existent) performance difference and personal experience in moving things in games, there tends to be parenting, unparenting, etc. happening and using translate makes the movement stay more consistent
This is nearly word salad.
transform.Translate defaults to local space. That's about it.
If you have a local-space vector, then it makes sense to use it
the alternative being transform.position += transform.TransformVector(vec);
transform.Translate(vec); is easier to understand in that situation
Also translate has a parameter you can pass in to make it be world space instead of you'd rather do that
Oh I see that was brought up already
Sorry I just woke up I should scroll more
I would say that because of that parameter alone, translate is better than adding to position directly, since it lets you more rapidly switch between modes if you need to refactor something or for debugging purposes, but thats a pretty niche situation. Under the hood it's all addition anyways, so there's no performance benefit or anything
does anyone know how could i specify the long of the vibration?
cause what exacly does that method rn? how many dime it spends vibrating?
specifiy it how ?
put your own nmbers
Vibrate does not take any parameters so I guess the duration is down to the device itself
yeah, the duration i think
i cant pass it any value...
and i don't know how to choose the duration length...
you cannot
(sry not code i' did not find specific channel) we are a team of developper and beginner on unity, we want to collaborate with github. The original project load the textures but when we dl it, its this redish texture that appears, we have no clue... 🙂 thx
so... how could i make it bigger or smaller?
like the length the vibration plays
what about 'can not' do you not understand?
yeah, i understand it, but imagine i want the phone to vibrate for 5 secs...
how could i do that?
is it possible?
NO!!!!!!!!!!!!
Is impossible to do that in unity? hmm... is the first time that unity put me a limit on something hehe <:
Pretty sure phones don't let you do extended rumbles though
Just little vibrations
I mean you can do, at least on Android by calling the OS directly but that is well outside of this scope
Do a coroutine that calls it multiple times until the time limit has ended
ohh, thanks, i'll look for it hehe
Hey everyone, I am having a problem with my player movement in my game and I just can’t figure it out. My game has a top down Isometric camera. For my movement, I want to control the direction of the movement via W, A, S, D while controlling the rotation via Mouse. So the player rotates where I move the mouse without changing the direction the players moves. This has been a pain to implement. My Blend tree has 8 way animations that are controlled by the parameters velocity.x and velocity.z. The problem is I have no idea how to implement the rotation. Because right now if I for example press w to walk up, but look to the left. The forward animation is being played since the velocity is set to forward. But instead the player should move to the top while the right strafe animation is playing since I am looking to the left. I have no idea how to implement the rotation into my animation controller while still using velocity too. Any help would be appreciated:)
PS: As an example of what the final movement should look like you can look at the game soulstone survivors.
The animation you play should depend on the local direction of movement.
Vector3 worldMove = Vector3.forward;
Vector3 localMove = transform.InverseTransformDirection(worldMove);
You mean instead of velocity?
ah, I should say velocity
since you care about not only the direction, but also how fast you're going
Vector3 worldMove = Vector3.forward;
Vector3 localMove = transform.InverseTransformVector(worldMove);
Suppose the player is facing to the right
localMove will wind up being a vector that points to the left
because the player is moving in the world forward direction and facing the world right direction
Hey guys. What is another good way to rotate around something other than using this method, that is working for me but it is also rotating the transform rotation of the object it self, and I dont want that. cs transform.RotateAround(_player.transform.position, Vector3.forward , 30 * Time.deltaTime); Tried so many other things and nothing seems to work sadly. Imagine I have 2 objects.. 2 circle 2d and I want one to orbit the other without rotating itself
so, from the player's perspective, their movement is in the left direction
I don't understand your problem. Are you saying that you don't want the child object to care about how its parent is rotated?
Oh
I see.
You want the child to move without changing the direction it's facing.
So just so I understand correctly, I should base my parameters based on localMove and not solely on velocity?
Yes. Your problem is that the player's velocity is in world-space.
So it's the direction + speed you're moving in the world
You need a velocity in local-space
which will be the direction + speed you're moving from your point of view
Thanks for the help I will try this once I am home, can I contact you in case I run into problems?:)
Will do thank you!
No
I have 2 separated objects, they are not child of each other or something like that
1 is the player the other is the boss. and everytime the player goes nearby the boss or far away I set that the boss will react accordinly and it works.. but I also want to add another movement for the boss.. not only going close or further from the player but also rotate around the player
One option would be to just calculate a new position and go to it directly.
Vector3 position = transform.position;
Vector3 parentPosition = transform.parent.position;
Vector3 offset = position - parentPosition;
Quaternion rot = Quaternion.AngleAxis(30 * Time.deltaTime * speed, Vector3.forward);
Vector3 newOffset = rot * offset;
transform.position = parentPosition + newOffset;
It works, but it is also rotating the boss rotation transform
Ah. That should not be happening.
but it is using cs transform.RotateAround(_player.transform.position, Vector3.forward , 30 * Time.deltaTime);
or maybe I am misunderstanding.
and if I try to fix the transoform.localrotation as quaternery,.iodentity it stops working
yes the boss rotation should be fixed and the object boss should go around the player
Could anyone help out with Pool Manager related questions?
ask your question.
private void BossMovement() {
float dist = Vector3.Distance(_player.transform.position, transform.position);
Vector3 MoveDirection = (_player.transform.position - transform.position).normalized;
Vector3 MoveDirection2 = (_player.transform.position + transform.position).normalized;
if (dist < 20)
{
_rb.velocity = MoveDirection2 * _speed;
//transform.RotateAround(_player.transform.position, Vector3.forward , 30 * Time.deltaTime);
} else if(dist > 35){
_rb.velocity = MoveDirection * _speed;
}
}```
here's an idea: make an empty object orbit the player
then make the boss move towards that empty object
that is what I have now and works.. but if I add the line that is commented it rotates around but also rotate around itself
You're trying to modify the transform of an object that also has a rigidbody on it.
That will cause problems.
This would avoid that!
The boss would just try to move on top of that empty object.
This is my current loop:
Player spawns (Has stock pool of 1 item)
Player breaks into pieces. (pool is cleared, and reutrned to 1 default)
Im having issue geting my playerid attaching to all the seperate pooled objects that belong to me. Is it best to serve the ID from the PoolManager as a global variable?
will try that thank you
alternatively, just have the boss calculate which direction would make them orbit around the player.
This would be a good place to use Vector3.Cross, actually
A: vector pointing at the player
B: vector pointing into the screen
Result: vector that makes you orbit counter-clockwise around the player
i don't understand how an object pool is relevant here
There is going to be lots of people doing this
all shattering, collecting fragments
dropping their collected fragments
Player spawns (Has stock pool of 1 item)
Player breaks into pieces. (pool is cleared, and reutrned to 1 default)
This does not make sense to me. Is this just a collection of fragments that the player is holding?
Object pooling is used to avoid creating and destroying lots of objects by reusing them
So if the player has collected... lets say 3000 fragments, its going to be a big drop. I assume you would collect them in each players pool because you can just reuse them for the drops to save instancing new objects
I would just have one big object pool for fragments.
When the player breaks, it spawns a bunch of fragments
It would ask the object pool to give it these fragments
and then the fragments are collected, they'd go back into the object pool
If you need to attach any data to the fragments, do it at this point.
also, I would consider grouping these fragments together :p
ye i have them under 1 parent prefab
Yeh it looks fun eh?
5 skulls will turn into a larger skull instead of dropping as 5 small skulls
so you don't get a huge pile of objects
Hopefully i can pull it off, ur a legend thanks for your input
Even if you want to have lots of physics objects everywhere, 3000 sounds like a ~lot~
similar approach in games like vampire survivors etc, xp gems get grouped at some point
Is it the rigid body collisions that cost alot of performance? I can wack them on a seperate layer as a sort of "entity?"?
That would be expensive, yes.
it would also probably be unstable
with objects clipping into each other and going flying
I'd make fragments of size 1, 5, 20, 100, 500, something like that
Voxel size?
value -- whatever you're counting here
ah true
so a 500 fragment would give you 500...fragment points, or whatever
to decide what to spawn, pick the largest possible fragment until you're down to 0
Yeh and just make that piece bigger
maybe add some randomness too
or something
so there's a chance to pick a smaller one anyway
bigger/different colour is usually a good approach for visual clarity that it's worth more
I was going to add gravitational pull so you dont need to walk close
Yeh i like the idea
is this possible like rigging the arm of that charcter within the border using mouse input?
you could use visual effects to make it look like the big fragments are shattering into many small pieces as they fly towards you
might make it more fun
This looks like an inverse kinematics problem.
You scale up in size the more you eat, I was going to make it once you got to a certain scale, little blocks only "chip" blocks of you off and can pick them up
figuring out how to rotate the joints so that the gripper is at the desired point
While you slowly roam around the map like a mamoth
I forget if unity has that built in for 2D arms.
#🏃┃animation channel might be a shout
but its possible? do you have any recommendation if its possible?
This looks relevant.
Keeping the arm inside the border is the easy part. You'd just clamp the mouse position.
Probably like this
Thanks ill look on it
Vector3 targetPos = // get a desired position somehow
Vector3 delta = targetPos - armHolder.transform.position;
delta = Vector3.ClampMagnitude(delta, 100);
targetPos = armHolder.transform.position + delta;
this would limit the arm to reaching 100 meters
might want a smaller number :p
oooohhhh okay!!! thanksss
its not
there's very little difference in 2d/ 3d dev..
thus why it looks hard because im struggling with 3d xD
So the first block of fragments the players get go into "the" pool now.
Players are shifted into the player pool to reuse their objects for respawning.
Is that what you mean?
The cube fractures, the assigned fracturedobject is activated(leaving fractures in the world), and then a new deactivated fracture propagates in the pool for the respawned player to drop again.
Hmm.. ok interesting. i will check this out. the way you said to do worked great for me.. create an empty object that will make all the movement and its a separate object not parent not child from the boss and the boss just follow it..
but maybe with this .cross would work without the need of doing the empty object
will need to try
leap/charge + txt (holding down right click)
hi can anybody help me ou with NavMesh Components ?
i need help with NavMesh Components i have it set up on my enemy but it does not work im going to send video of the problem now.
Hi I am having a really hard time fixing a bug in my code fr a 3D FPS shooter and was wondering if anyone is free to help out?
Nav Mesh Agent on Enemy and NavMesh Surface on your floor?
yes
Ok then ill wait for the video
what are we supposed to look at
whats supposed to happen
btw shouldnt use rigidbody on navmesh agent unless its like locked on constraints
also you have a script error you should fix
the enemy should chase the player when the player is in sight range and attack the player when in attack range
well we're gonna have to look at the script
also like I said if that error is part of this script then it can cause weird issues too
it is not part of the script
heres the code
Hi everyone, I am new to Unity and would really appreciate some help with my code. I am having an issue where, when I run my code, even if the player starts on the ground it is teleported up to a height of 2.8 every time I move at all. This is resulting in my grounded code not working and so I can't implement any forms of ground checks for anything in the future. Any help would be much appreciated as I have been working from youtube tutorials from many different people and have been stiching parts together.
It might help if you posted your !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Tried to understand how to put it into the code.. but it is not working cs _rb.velocity = Vector3.Cross(_player.transform.position ,transform.position) * _speed;surely something is wrong.
you're crossing two positions. that doesn't really make sense
collapse the other debugs
you want to cross two directions
you have another error @stable portal
ahh ok not positions..
The first direction should be the vector pointing towards the player.
The second direction should be pointing into or out of the screen
Got it will test now
The second direction will decide whether it's clockwise or counterclockwise
Also, make sure to normalize the result
otherwise the enemy will move faster when they're further away!
When i try to raycast to the left and to the right of my character(currently the raycastdirection is Vector3.right and Vector3.left) the raycast turns with the object but it should the direction shouldnt move when the character rotates how can i achieve this?
I have only those 2
you should still fix
can someone help me. when i launch unity on my laptopwith github it wont load . it will give me a error report screen
Ask about this in #💻┃unity-talk . This isn't a code problem.
also show us what this error is.
ok
hey, could you give me an example on how I would calculate the velocity x and zz with localmove?
once you get localMove, just read its x and z values
sent it in the channel
transform.InverseTransformVector gives you a local-space vector that matches the provided world-space vector
So, as an example
transform.localPosition = transform.parent.InverseTransformPosition(transform.position);
This does nothing
It turns its world position into a local position from its parent's POV, then sets its local position to that.
transform.position = transform.parent.TransformPosition(transform.localPosition);
same deal
(in fact, I'm pretty sure this is roughly how Unity decides what the world position of a parented transform is!)
(Inverse)TransformPosition is used for a position. The result depends on your transform's own position
(Inverse)TransformVector is used for a vector. Your own position doesn't matter.
Done like that and it is working. Thank you my friend. ```cs
float dist = Vector3.Distance(_player.transform.position, transform.position);
Vector3 MoveDirection = (_player.transform.position - transform.position).normalized;
if (dist < 30)
{
_rb.velocity = Vector3.Cross(Vector3.forward, MoveDirection).normalized * _speed;
} else if(dist > 35){
_rb.velocity = MoveDirection * _speed;
}
}```
and (Inverse)TransformDirection is used for a direction. Your scale doesn't matter.
nice 👍
!logs Assets\CiroContinisio\ToonShader\Shader\Editor\ToonShaderGUI.cs(70,54): error CS1061: 'MaterialEditor' does not contain a definition for 'PopupShaderProperty' and no accessible extension method 'PopupShaderProperty' accepting a first argument of type 'MaterialEditor' could be found (are you missing a using directive or an assembly reference?)
Hi
I have a problem
Assets\CiroContinisio\ToonShader\Shader\Editor\ToonShaderGUI.cs(70,54): error CS1061: 'MaterialEditor' does not contain a definition for 'PopupShaderProperty' and no accessible extension method 'PopupShaderProperty' accepting a first argument of type 'MaterialEditor' could be found (are you missing a using directive or an assembly reference?)
_shadingStyle = (ShadingStyle)materialEditor.PopupShaderProperty(FindProperty("_SHADING_STYLE", properties), new GUIContent("Material"), options);
this is the line of code that is making the problem
Hey, guys! I have a question. When I am opening Pause Menu game object on my game and go to my options scene and then I want to get back to my pause menu I don't see my pause menu screen there opened like I had it. I know that everytime another scene loads everything included the previous scene were destroyed. So, what I want to know is how to use DontDestroyOnLoad() I have never used that before and I don't know what to do?
is it your code?
nope
it's an assest
better to contact the creater, the error says there is no PopupShaderProperty method in class MaterialEditor
ok
Perhaps the asset is designed for URP/HDRP, and you're using the built-in render pipeline
the problem is not whether you use DDOL , instead when you return the game option scene from game play and reload the game play scene (idk how you call it btw) and there is no memory on game play scene before you load the option scene, and game play scene cant restore the state.
// Use localMove to directly set velocity parameters
float targetVelocityX = localMove.x * targetSpeed;
float targetVelocityZ = localMove.z * targetSpeed;
// Smoothly adjust current velocities to target velocities
velocityX = Mathf.MoveTowards(velocityX, targetVelocityX, Time.deltaTime * SpeedChangeRate);
velocityZ = Mathf.MoveTowards(velocityZ, targetVelocityZ, Time.deltaTime * SpeedChangeRate);
if (_hasAnimator)
{
_animator.SetFloat("velocity.x", velocityX);
_animator.SetFloat("velocity.z", velocityZ);
}
This works like it is intended too except that for example my forward run is at x= 0 and z= 10 (10 is my movespeed) but the max Z velocity I get when pressing W is 7. The rotation works though tank you
private void Move()
{
// Set target speed based on move speed, sprint speed, and if sprint is pressed
float targetSpeed = _input.sprint ? SprintSpeed : MoveSpeed;
// A simplistic acceleration and deceleration designed to be easy to remove, replace, or iterate upon
// Note: Vector2's == operator uses approximation so is not floating point error-prone and is cheaper than magnitude
// If there is no input, set the target speed to 0
if (_input.move == Vector2.zero) targetSpeed = 0.0f;
// Calculate the move direction based on input
Vector3 moveDirection = new Vector3(_input.move.x, 0.0f, _input.move.y);
// Correct input direction based on camera's 45° rotation on the Y-axis
moveDirection = Quaternion.Euler(45, 45, 0) * moveDirection;
// Normalize the corrected input direction
moveDirection.Normalize();
//Vector3 worldMove = transform.TransformVector(moveDirection);
Vector3 localMove = transform.InverseTransformVector(moveDirection);
// Use localMove to directly set velocity parameters
float targetVelocityX = localMove.x * targetSpeed;
float targetVelocityZ = localMove.z * targetSpeed;
// Smoothly adjust current velocities to target velocities
velocityX = Mathf.MoveTowards(velocityX, targetVelocityX, Time.deltaTime * SpeedChangeRate);
velocityZ = Mathf.MoveTowards(velocityZ, targetVelocityZ, Time.deltaTime * SpeedChangeRate);
// Update animator if using character
if (_hasAnimator)
{
_animator.SetFloat(_animIDSpeed, Mathf.Max(Mathf.Abs(_input.move.x), Mathf.Abs(_input.move.y)) * targetSpeed);
_animator.SetFloat(_animIDMotionSpeed, Mathf.Max(Mathf.Abs(_input.move.x), Mathf.Abs(_input.move.y)));
_animator.SetFloat("velocity.x", velocityX);
_animator.SetFloat("velocity.z", velocityZ);
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
thx
Hey guys, I am brand new to using unity and I am stuck trying to get a scene change with a trigger on a box collider 2d. I'll include a screenshot of my script and my object settings. Whenever i try to walk into an object it is acting like a rigid body and I am not sure why. I attached the object's script and my player controller's isWalkable script
do you mean it acts like an obstacle?
a rigidbody is just something that can be moved around by physics
yeah, i Think it is getting caught by my isWalkable logic
which should be looking at the layer "SolidObjects"
You'll want to do two things, I think
One: Only look for objects on the appropriate layers
Two: Ignore triggers
I'm actually a bit unsure on the second point -- the Physics2D.queriesHitTriggers documentation says it's for raycasts
I don't do very much 2D
but maybe that's just badly worded
I see that you're passing solidObjectsLayer to the overlap method
What is that?
should specify which layer the isMovable looks at
the SceneChange object is not in that layer so I'm not sure why its getting caught by that
hey unrelated to your issue but look at what IDE is suggesting 🙂
Perhaps it's not! You should check what you're actually hitting.
Try logging the collider you're finding
Well, i got it to not collide by changing the layer from default to creating a new one, but it still is not triggering.
I just chaged it to other.CompareTag("Player");
did you try what they suggested ? with logging what you hit
I'll see if i can figure out how to do that haha
well. other is what you hit
the code editor gives you a bunch of stuff when you do other.
I thought other was the player in this instance
thats why you debug
so you are certain
eg
Debug.Log(other.name);
Outside of the Tag but inside the trigger
Trigger Enter is good log but not very useful 😉
That's fine. You could combine the two logs if you want though
Debug.Log($"Trigger entered by {other.name}");
Hmm, even with that in there, nothing prints to the debug log, it is like this is not even executing.
oh wait you wanna log the Physics overlap not this
if ur having problem with iswalkable
Well even when i comment that out, it still doesnt work, i thought that might have been the cause.
what does isWalkable do again?
for movement right
isWalkable basically is checking if a tile is in the SolidObject layer, if it is dont allow to walk
Hey, guys! I have an error where it says Stack Overflow Exception: The requested operation caused a stack overflow. Can you guys explain to me first of all how to handle that error and secondly why that's happening when I am using DontDestroyOnLoad() on my other method where I want to load another scene?
Here is the code:
https://paste.mod.gg/xflekmslyaxp/0
A tool for sharing your source code with the world!
use Collider2D[] results and print out what you hit
but if trigger is causing issue and is not in solidObjectslayer , it shouldn't be a problem
is good to double check anyway what it is you're hitting, its an array so you just make for/foreach loop to print results of each col
Show the code.
You went infinite somewhere. Show code
@polar acorn @summer stump Here!
I feel like such a novice 🙁 I'll attempt to get that logged lol
I want to make a system that generates things over 18 tiles. If the generator wants to generate something one tile higher than 18, how can i say him that its 1 and not 19?
modulo operation
What is the point of having DontDestroyOnLoad be a function that calls DontDestroyOnLoad?
Looks like you call it twice for the pause menu too. I need to do something, but I can look more soon
DontDestroyOnLoad calls DontDestroyOnLoad which calls DontDestroyOnLoad which calls DontDestroyOnLoad which calls DontDestroyOnLoad which calls DontDestroyOnLoad which calls DontDestroyOnLoad
Ahhh yeah of course. It is recursive.
That is a danger of naming your function the same as a Unity function. Never really a good idea to do that
I am using it first time but I don't call it twice bro??
Yes you do
LoadOptionsScene()
And
GoBackButton()
And BOTH of those start a recursive loop infinitely long till crash
Don't name your functions the same as Unity functions
you would need to use the contactfilter2d version
i think you likely get an DDOL must be called on root gameobject warning from what you had said
No, what they got was a quantum singularity that threatens to destroy physics as we know it, thankfully the compiler caught it and closed the program
Wait, yes I am calling it but not for that purpose you say, I was thinking to make when I am pausing my game and load the other scene to don't destroy pause menu screen and when clicking back button to go back to my main scene to dont destroy it as well. So, in this case of mine the pause menu screen was destroyed twice.
this
DontDestroyOnLoad is something that you call one time to mark the object as a DDOL.
You don't call it every time a scene changes
once it's a DDOL it's a DDOL forever until you manually destroy it
Oh, ok!
anyone knows if referencing a gameobject through a script using the "findwithtag" thingy work if the object will only get instantiated mid-game?
considering I type something like
{
enemy = GameObject.FindWithTag("Enemy");
}```
Does an object with that tag exist when this object is created
Won't work if the start is called before instantiate
instantiate will return the object that newly created
so I need to put it in update?
No. Do this
#💻┃code-beginner message
Just capture the reference
i fixed it now i have no errors but its still not working
check other logs make sure you don't have 2 conflicthing logics (eg waiting / chasing)
what you need to do is
SomeType t=Instantiate(the t);
is better to use statemachine instead of bools for that reason @stable portal
So, I understood that but how actually can I handle that error, I just removed that two lines of code of my DontDestroyOnLoad() .
i dont realy know whats that
Just make the pauseMenu put ITSELF in DDOL in its awake
Don't make a function that calls itself which calls itself which calls itself which calls itself which calls itself which calls itself which calls itself which calls itself which--
[SerializeField] private ContactFilter2D contactFilter2D;
private bool CanMove(Vector3 targetPos)
{
Collider2D[] cols = new Collider2D[10]; // start with 10 results (expands itself)
var hits = Physics2D.OverlapCircle(targetPos, 12, contactFilter2D, cols);
if (hits > 0)
{
for (int i = 0; i < hits; i++)
{
Debug.Log(cols[i].name);
}
return false;
}
return true;
}```
Something like this should help you get started
i followed this tutorial https://www.youtube.com/watch?v=UjkSFoLxesw&t=287s
FULL 3D ENEMY AI in 6 MINUTES! || Unity Tutorial:
Today I made a quick tutorial about Enemy Ai in Unity, if you have any questions just write a comment, I'll try to answer as many as I can :D
Also, don't forget to subscribe and like if you enjoyed the video! :D
See you next time.
Links:
➤ NavMesh Components: https://github.com/Unity-Technologi...
for example an Enum can be used a simple state machine
In its awake? What do you mean here? Do I have to use that ddol on awake function?
If an object is going to be a DDOL you should probably just do it in Start or Awake and be done with it
There are Unity functions that are called in a certain order. Awake, Start, Update, etc.
It is only called once, and it happens right when the object is created. So it's a good place to do things to initiatalize the object
And "put in DDOL" is what is happening here. When you call DontDestroyOnLoad on an object, it gets put in an additive scene named DontDestroyOnLoad that isn't cleaned up when a scene changes. That's how it works internally
doesn't mean its good lol
Like I said , I don't see the bool staying on in inspector unless you selected wrong enemy
else if (playerInSeeRange && !playerInAttackRange)
{
ChasePlayer();
Debug.Log("Chasing");
}```
🤷♂️
thats why I said check for Debug.Log("waiting"); log
it could be happening so fast that it could be printing chasing while waiting
from the video you sent the log was printing
the enemy is WhatIsEnemy layer
screenshot the Player object
nice it works now but i have one more issue when the enemy is shooting is shoots in itself because of its collider how can i fix it?
if you dont care about enemy bullets hitting other enemies use
https://docs.unity3d.com/Manual/LayerBasedCollision.html
do like EnemyBullet doesnt hit WhatIsEnemy
or you can just do it when you instantiate bullet , put collider of it and enemy inside Physics.IgnoreCollision (requires reference to bullet collider and own collider)
ok im going to try it out
[SerializeField] private Collider myCol
void Foo(){
var enemyBullet = Instantiate(etc..
if(enemyBullet.TryGetComponent(out Collider col))
Physics.IgnoreCollision(col, myCol, true);
}```
2D - How do I quickly set the opacity of a panel in code?
reference it's image component and modify its color property
i did this and for some reason it does not work
if (!attacked)
{
Rigidbody rb = Instantiate(enemyBullet, transform.position, Quaternion.identity).GetComponent<Rigidbody>();
if(enemyBullet.TryGetComponent(out Collider coll))
{
Physics.IgnoreCollision(coll, myColl, true);
}
rb.AddForce(transform.forward * 32f, ForceMode.Impulse);
rb.AddForce(transform.up * 8f, ForceMode.Impulse);
attacked = true;
Invoke(nameof(ResetAttack), attacksDelay);
}
I get no suggestions. Usually it shows me whatever the thing has.
well you've got several things wrong there. first, you should be using GetComponent, not GetComponents. second, it is a method that you call using ()
Ah okay, thanks
becaause u write it wrong
ur not grabbing it from the instance
im not quite sure if i understand what do you mean by that could you please correct the core or explain thanks.🙏
you're calling TryGetComponent on your prefab not the object you instantiated
rb is the object you instantiated which is also what you should be calling TryGetComponent on
newbie question but how do I reference a gameobject to a prefab?
thx
you can't drag a gameObject from the scene into a prefab
I don't quite know what you mean by this.
If you mean you want to reference a game object in a scene from a prefab, then the other answers are correct: you can't reference scene objects from a prefab.
selected ObstacleSpawner
ok
see the link boxfriend posted.
How do I slowly fade in a panel and its lower attached things? I tried the following but it did not work:
while (opacity < 100) {
_settingsMenu.GetComponent<Image>().color = new Color(1f, 1f, 1f, opacity);
opacity += 0.1f;
}
I also tried with this, which also did not work:
while (opacity < 100) {
_settingsMenu.GetComponent<Image>().color = new Color(opacity, opacity, opacity);
opacity += 0.1f;
}
loops run to completion. so either you need to put this in a coroutine with a yield inside of the loop, or remove the loop and repeat this code in Update.
also Color uses values from 0 to 1 not 0 to 255
also opaicty (alpha) in a Color struct is from 0 to 1
so an alpha of 100 is the same as an alpha of 1
Ah okay, thanks
you also shouldn't be using 0.1f as a magic number like that you should use the amount you want to increase per second then multiply it by deltaTime
unless you don't care that different framerates will cause it to fade in/out at different rates
hmmm update() isnt called on the frame gameObject.SetActive(true); is called?
public void Tip(string to)
{
Update();
gameObject.SetActive(true);
text.text = to;
}```had to do this on a tooltip code since it pops on where it was last placed first before going to where it should be
it very likely depends on what point in the frame you set the object as active
but you do know you can use OnEnable to set things up for when it is enabled, right?
i call tip when mouse entered something that should have toooltip
I'm still confused after reading the docs. I don't understand. I'm getting
are you still trying to drag a scene object into a prefab? beacuse as has already been pointed out you cannot
otherwise you are trying to drag an object that doesn't have the component you are tryign to reference
yes, but I want to know a solution to it because I keep getting
You probably need to assign the obstacleSpawner variable of the DestroyOutOfBounds script in the inspector.```
Mouse events are called before Update. so this code runs immediately before update does
did you even bother reading the link i sent to you?
yes i did
I don't know what you mean exactly, do you mean that I should do opacity += 0.1f * DeltaTime?
then what did you try besides trying to drag the scene object into the prefab?
Because I just used 0.1f as a test value
this is pretty relevant thanks
I tried to use GetComponent to access the variable
no. firstly because DeltaTime is not a thing. second, that would cause it to increase opacity by 0.1 per second. use the number you want to increase per second not your magic number
well obviously GetComponent is not going to work unless you have a reference to the object the component is attached to already
LookAt makes the object's forward direction (blue arrow) point toward the object. you probably just need to get the direction from this object to the one you want to "look" at and assign it to Player.transform.up
huh
well that's certainly not a helpful response
(spriteRenderer.sortingOrder <= 0 ? ReferenceHolder.Instance.tileMap : ReferenceHolder.Instance.tileMap1)?.SetTile(transform.position.SnapToInt(), null);
```can `?.` work here?
do not use ?. with objects that inherit from UnityEngine.Object
just gonna get rid of this 🥹
that is precisely why you should not use ?. with unityengine.objects
Ok so I put now this:
IEnumerator ChangeOpacityOverTimeIn() // This makes it run as it is intended to, fading it in.
{
while (opacity < 1)
{
_settingsMenu.GetComponent<Image>().color = new Color(1f, 1f, 1f, opacity);
opacity += fadeinTime * Time.deltaTime;
yield return null; // Yielding to the next frame
}
}
ChangeOpacityOverTimeIn();
```The "fadeinTime" I set in the inspect box to "2" but it still pops in instantly
null conditional (?.) and other null related operators do a pure null check. they do not use the overridden == operator on UnityEngine.Object to check for unity's fake null when an object has been destroyed. they have no way to access that overridden operator so when you use them on a destroyed object you still run into missingreferenceexceptions because those objects aren't actually null
well for one you're not starting the coroutine correctly
How do I start it correctly?
by using StartCoroutine
Ok now it broke. It pops in instantly, then when I close it it closes instantly, then when I open it again, the closing button appears but the panel does not
share the full class using a bin site 👇 !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
the code you've shown should make it fade in and out in 0.5 seconds (assuming that fadeinTime and fadeoutTime are both 2)
if it somehow isn't working, then some other code is affecting it, or those variables i just referred to are set way higher than you think they are
great! then either some other code is affecting it, or it is actually taking a whole half of a second
or you're looking at the wrong object
does the OverlapBoxAll size height and width or is it half of height and half of width?
Ok I changed the while (opacity < 1) line to while (opacity < 255) and now the panel appears again, though again it appears instantly.
it's like you haven't even been listening
Apologies but I have some mental disabilities, so that might be why
Is there a way to have 1 object parent and 1 object child, where both have colliders, and the script that I have on the parent will say that when other.comparetag("bullet") happens, it will do some logic. BUT the prob is that when the bullet enter the child circle collider and not the parent collider that is also a circle and its inside the child collider, it also counts and I want just to count when it hits the parent.
tried like 5 dif ways to achieve that but seems that I cant separate one for the other. Is there a way to do this?
ignore layer or ignore collision?
what do you mean? can you explain better?
exlude the child layer from collision messages with incoming bullet
oh ok, will look into it, thank you
https://docs.unity3d.com/Manual/LayerBasedCollision.html
this one if you want to completely ignore each other and not do it every function call
I managed to fix it.
https://hatebin.com/bunouungzl
This also changes the opacity of its children, and it works with my current project.
Hey!
I have this idea to get some Realtime data from NodeRED into my unity project. I've researched and I came across Websockets and REST API's.
Which one would be best? or are there any other, better, solutions?
I work with a HoloLens so performance is important to consider too.
whats NodeRED
Its something my collegues work with, i think network/server stuff that holds data
personally dont know much of it
Ah so the issue was that child object of the panel weren't being affected. You should maybe mention important details like that next time
but basically from a web page
if you need more like realtime messages websockets make more sense
"Node-RED is a programming tool for wiring together hardware devices, APIs and online services in new and interesting ways."
yeah like once per few seconds
thats a very generic statement
but if it has to be faster, websockets would be the go-to?
they have diff use case
Are you frequently transferring data?
Websocket is good for keeping a connection open and transfer data frequent
WebSockets are a bit more efficient for continuous data than HTTP.
That wasn't the issue even. The issue was that the panel did not fade in and out correctly. The issue was the order of how things were done.
its very efficent
ooo great ty!
whats the proper thread to use for Unity Editor crashing help?
what kind of crash
!bug
🪲 To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
📝 If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click ‘Report a problem on this page’!
💡If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
ollow by a crash report popup
could probably be an infinite loop in your code
it's not a bug. it's def me
nah, I just enabled windows firewall for... reasons.. now unity wont open.
if I disable it it will.
can't you allow Unity through firewall settings?
tried the stuff I found online, that got me to ALMOPST get unity loaded, but it still crashed after that popup
yes, and I did, and that seem to MOSTLY work.. but obviously, not completely
Ahh . . .
could be Visual Studio also
used this: https://docs.unity3d.com/Packages/com.unity.live-capture@2.0/manual/setup-network.html as my guide.
created a rule to allow that also, alas I CANNOT create a rule for the DLL mentioned in that popup.. only .exes
(also that dll shows up in the projects' libraray folder, and I got a zillion projects)
good thinking, alas, I did check those, and I do see a stack trace in there, but not sure how to use that info to set the right rule..
I even tried a to create a rule to allow ALL connections from 127.0.0.1, figuring that gonna cover everything originating on my own system- alas, didn't help
private void ApplyChangesToMaterial(Material material)
{
material.SetColor("_Color", colorToApply);
}
private void ApplyMaterialPropertyBlock()
{
thisRenderer.GetPropertyBlock(propBlock);
propBlock.SetColor("_Color", colorToApply);
thisRenderer.SetPropertyBlock(propBlock);
}```
How can I refactor these methods together so that as I expand this I don't have to maintain two separate method trees of duplicate code, specifically the:
material.SetColor("_Color", colorToApply);
propBlock.SetColor("_Color", colorToApply);
these two lines 
the ideal result would be something like a third method that does the assignment and can have either the material or material block passed into it?
I think my problem is that materials and material property blocks have technically nothing in common? like I cant cast from one to the other or whatever?
you can can overload a function, meaning you can create two versions of it, one that takes a property block and one that takes a material. not sure if that is what you need tho
Yeah moreso my problem I am trying to avoid is having to maintain two duplicate codebases as I expand this class
one for material property blocks, one for materials, both identical otherwise
afraid there is no way around that.. it simply requires different code to change the color for a material and a propertyblock. However with the overloaded function you shouldn't need to ever write that code again...just call that function when you want to chaNGE THE COLOR, AND PASS IN WHAT YA HAVE.
oops caps,
I might have to settle for that
Thanks, Ill try that out for now then
So did my earlier suggestion wind up working?
(the goal is to preview different colors in the editor, but to also get SRP batching at runtime)
giving each renderer its own material in the editor is confusing, but using material property blocks breaks SRP batching
BoxCast
hey guys, already tried all the things that people here told me to try, but none works. I have this situation. 1 object boss with 4 child minions. Minions they have a collider each, and boss also has a collider. Inside the boss script I have the method OnTriggerEnter2d. But if do like that as below ```cs
private void OnTriggerEnter2D(Collider2D other) {
if (other.CompareTag("Bullet")){
_currentHealth -= _bullet._playerBulletDamage;
}
}``` no matter if I hit the minions or the boss is the same. And I cant find a way to differentiate and say NO i want the hit to count only when hits the boss. Boss and minions are using dif tags.
Where do u get the id of the bool from?
you can use Animator.StringToHash for that
or if you don't want to do that and don't mind using a string in that call just use its name
I am using this script to zoom using Alt+Scroll Wheel. But there seems to be an issue. Once I zoom & reach at a point where I cannot zoom-in further, I am not able to zoom-out. But If I zoom-in normally then I can zoom-out
using UnityEngine;
public class CameraController : MonoBehaviour
{
private float zoomSpeed = 5f;
public GameObject cameraFramePrefab;
[HideInInspector] public GameObject CameraFrame;
void Awake()
{
CameraFrame = Instantiate(cameraFramePrefab, new Vector3(0f, 0f, 0f), Quaternion.identity);
}
void Update()
{
Vector3 lookAtPosition = CameraFrame.transform.position;
// Dolly: Alt + Scroll Wheel
if (Input.GetKey(KeyCode.LeftAlt) && Input.GetAxis("Mouse ScrollWheel") != 0f)
{
float scrollWheel = Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
Vector3 dollyDirection = lookAtPosition - this.transform.position;
if (dollyDirection.magnitude > 5f)
this.transform.position += dollyDirection.normalized * scrollWheel;
}
}
}```
are you sure you setup Mouse ScrollWheel correct?
why not Input.mouseScrollDelta
how do I do that, I directly started coding
wait, I'll try this, never heard this one before
how can i make a loop that runs alongside with Update? E.g a variable that goes up by one every frame and stops once it gets to a certain number
use an if statement inside of update. if variable is less than threshold add 1
would this work maybe ?
IEnumerator Foo()
{
var frames = 0;
while(frames < 3000)
{
frames++;
yield return new WaitForEndOfFrame();
}
yield return null;
}```
void Update()
{
Vector3 lookAtPosition = CameraFrame.transform.position;
float scrollWheel = Input.mouseScrollDelta.y * zoomSpeed;
Vector3 dollyDirection = lookAtPosition - transform.position;
if (dollyDirection.magnitude > 5f || scrollWheel < 0f)
{
transform.position += dollyDirection.normalized * scrollWheel;
}
}```
So I updated the script as per your advice. And now I am able to zoom-out. But one issue that's happening now is, if i rapidly scroll then my camera is going beyond the bounds I set & then zoom-out doesn't work
which is the bounds ?
I don't want my camera to go nearer than 5f from the LookAtPosition
My canvas doesn't seem to be responding to the player input. I'm able to adjust the values just fine in the inspector, but the sliders and buttons don't seem to be responding in the game window
This forum post https://forum.unity.com/threads/sliders-wont-slide.283570/ suggested it had something to do with file hierarchy, and changing that is indeed how I got it working in a separate scene, but I still don't fully understand what was different about that separate setup and I'd rather know the underlying issue rather than just trial and error-ing it again
just use distance check
oh I see the magnitude
my if condition is wrong? I have checked the magnitude
check the number make sure its correct
its prob not
that if statement is sus tho
Why is the int jumping up to 5 even though the texts are null?: foreach (TMP_Text e in InputFields) { if (HaveChildren != 5) { if (e.text != null) { HaveChildren++; } else { HaveChildren = 0; } } }
is there a better way to do this? on sprint() i just put the playerspeed to 5 and on unsprint i just put it to 2
yeah just have one method you subscribe to both events and change it based on the context passed in
although you probably wanted started and canceled rather than performed and canceled if you just want to start when the button is first pressed down and end when it is released (performed can act the same way if you don't have anything interactions or whatever on your action)
how you know is null
I'm trying to check if the text is empty.
so use !string.IsNullOrEmpty(e.text)
yeah, I did, it's correct. Not able to solve the issue
thank you
you havent specified which direction is scrolling and which one is the limit
The int still jumps up to 5
even though the texts are null
So my scrolling is towards the lookAtPosition, which i am calculating, first line of Update() & I don't want my camera to zoom through it, so I added a rough 5f value
show the full context
{
public TMPro.TMP_Text[] InputFields;
public int HaveChildren;
bool Checked;
public GameObject button;
void Update()
{
foreach (TMP_Text e in InputFields)
{
if (HaveChildren != 5)
{
if (!string.IsNullOrEmpty(e.text))
{
HaveChildren++;
}
else
{
HaveChildren = 0;
}
}
}
if (HaveChildren != 5)
{
button.GetComponent<CanvasGroup>().alpha = 0.03f;
button.GetComponent<CanvasGroup>().interactable = false;
}
if (HaveChildren == 5 && !Checked)
{
Check();
Checked = true;
}
}
public void Check()
{
button.GetComponent<CanvasGroup>().alpha = 1;
button.GetComponent<CanvasGroup>().interactable = true;
}
}```
Hey!
How do I set an animation float for a blend tree using the animated object (animal) and the followable (player) distance?
I want that if the animal is near the player, it should be around 0, and if the player is far away, it should be 1, which would indicate the animal running. I tried doing some math with magnitudes and vectors but I didnt figure it out.
Thanks!
you never reset HaveChildren to 0. so if there is even one non-null object in there, after 5 frames it will be 5 and it will always be 5 after that
So how should i go by doing this?
its probabnly scrollWheel < 0 being true
You need to get the distance between the two objects and then use lerp to map the distance between two values 0 and MaxSpeed.
how should I fix it then?
why do you want that there
a better solution would prob be clamp
I removed it. But then my zoom-out stops all-together.
if (dollyDirection.magnitude > 5f)
actually wait, there is one point where you reset it to 0. but you should probably be checking for InNullOrWhitespace not IsNullOrEmpty
Ok
but for future reference, use the debugger or print useful information if things are not happening the way you expect. don't just expect everyone else to debug your code for you
The int somehow still jumps to 5
well what debugging have you tried?
how do i fix this the first image is my code
what have you actually done to make sure that the values you are using/checking are actually what you expect them to be?
I did transform.pos1 - transform.pos2 for distance
Use lerp?