#💻┃code-beginner

1 messages · Page 60 of 1

sullen wraith
#

On trigger enter is the child

swift crag
#

Is the scene view set to "local" and "pivot" here?

sullen wraith
#

@swift crag yes

swift crag
#

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.

sullen wraith
#

@swift crag RigidD on the children

swift crag
#

try one thing: log trans.name in the RegisterLaser method

sullen wraith
swift crag
#

I just want to make sure you're, indeed, getting two different transforms

sullen wraith
#

@swift crag

#

i do

grand birch
#

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.

marsh glade
distant mesa
#

with newtonsoft.json, are you supposed to put "using newtonsoft.json" stuff at the top of ur script?

grand birch
swift crag
#

It lets you write JsonConverter instead of Newtonsoft.JSON.JsonConverter

distant mesa
#

yea that doesnt work

swift crag
#

ah, it's Newtonsoft.Json. Not all-caps.

swift crag
distant mesa
#

in the package?

swift crag
# distant mesa 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;
distant mesa
#

ah

#

yeah

#

that doesnt work

#

but its in the project

slender nymph
#

are you using asmdefs?

marsh glade
swift crag
# distant mesa

You may need to restart your code editor and regenerate the external project files, since you've added a new assembly to the project.

distant mesa
#

reimport?

swift crag
#

no. close your code editor, then go to preferences -> external tools and click "Regenerate project files"

#

then reopen your code editor

distant mesa
#

ahhh

swift crag
distant mesa
#

yess

#

found it

swift crag
#

I would also check that the package actually shows up in the package manager window.

marsh glade
#

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.

sullen wraith
#

@swift crag Made a reference to the children in the inspector and printed this at parent start. It looks correct now right?

swift crag
#

Yes, that looks right.

#

I presume you're just trying to get a list of all the children?

distant mesa
#

it worked

swift crag
#

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.

swift crag
#

and the second one points in the +Y direction -- up

sullen wraith
#

@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.

swift crag
#

Yep, that's very reasonable.

sullen wraith
#

thanks for the help btw 😄

swift crag
#

Was the trigger message used to detect when a laser hit the first box?

sullen wraith
#

yes sir

magic condor
#

Uhm this wont go away

#

I hope this isnt the wrong place to put it

swift crag
#

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")

sullen wraith
#

@swift crag This is my child script. Ignore the red line i am removing the transform since i dont need it any more

marsh glade
#

Callbacks and delegates

swift crag
#

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

sullen wraith
#

later 🙂

#

I am triggering it manually at the moment

solemn anvil
#

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;
    }
}
wintry quarry
#

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?

swift crag
#

It's not just an image -- it's supposed to be bumpy

#

words are failing me right now

#

uhh, terrain!

wintry quarry
#

ok well - the answer is clear, there is no attempt to do any UV mapping in this code.

swift crag
#

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?

wintry quarry
#

the rect tool is throwing me off too

swift crag
#

yeah

queen adder
#

what does this thing look like?

#

what am i supposed to be searching

#

oh wrong channel

frozen dagger
#

Guys, I’m wondering how to add animated objects in pause UI cuz time.scale = 0

solemn anvil
obtuse oar
#

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;
    }
}
wintry quarry
#

that will simply anchor it stationarily in place

obtuse oar
#

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"

wintry quarry
solemn anvil
spiral niche
#

Does anyone know how to fix this?
"failed to create coreclr, hresult: 0x80004005"

obtuse oar
wintry quarry
solemn anvil
#

soo what should I do

wintry quarry
solemn anvil
# wintry quarry 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;
}
tame mist
#

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

wintry quarry
#

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

obtuse oar
#

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;
    }
}

wintry quarry
#

also did you make the mouse Rigidbody kinematic?

queen adder
#

Hi

obtuse oar
#

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);
    }
}
wintry quarry
#

OnMouseDown

obtuse oar
#

oh it was not kinematic, though i changed that

queen adder
#

Honestly don’t know how to code

nimble sorrel
#

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

wintry quarry
#

what does "an actual e key" mean? An Image?

nimble sorrel
#

yes

wintry quarry
#

You'd need to build that yourself

nimble sorrel
#

gotcha, ty

nimble sorrel
#

do the boxes continuously move? or are they moving to a specific position?

wintry quarry
#

and it's because of this:
mousePoint.MovePosition(Camera.main.WorldToScreenPoint(Input.mousePosition));

#

you use WorldToScreenPoint when you wanted ScreenToWorldPoint

tame mist
wintry quarry
#

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

tame mist
obtuse oar
wintry quarry
obtuse oar
#

whatever is default upon creating a scene, idk what that is sorry

wintry quarry
#

you can always just look

obtuse oar
#

perspective

wintry quarry
#

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

final trellis
#

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

wintry quarry
final trellis
#

yeah, its meant to only add force when isLookingDown is false

wintry quarry
#

ok so what's the issue exactly then?

#

it's saying "throwing: false" but there's no force being added?

obtuse oar
final trellis
#

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

wintry quarry
wintry quarry
wintry quarry
final trellis
wintry quarry
#

because you can't tell in what order things are being printed

final trellis
#

hence why the one inside the input statement has that "throwing" bit

wintry quarry
#

also there's no guarantee that the IsLookingDown() function doesn't have side effects

wintry quarry
final trellis
#

IsLookingDown() is just

wintry quarry
#

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

final trellis
wintry quarry
#

(-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

obtuse oar
# wintry quarry that means the joint is not releasing

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?

wintry quarry
#

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

final trellis
wintry quarry
#

are you ever actually looking down that far?

#

(within 30 degrees of straight down)?

#

also which object is this script attached to?

polar acorn
#

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

wintry quarry
#

checking the angle is identical to this^

#

just easier to understand

final trellis
wintry quarry
#

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

final trellis
#

down is 45, its the maximum angle you can look down in this game instead of 90

wintry quarry
#

if it's 30 it will return true only if you're looking within 30 degrees of straight down

wintry quarry
#

use 90 to start with

#

and tune it from there

final trellis
#

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'

wintry quarry
#

aka 60

#

not 30

#

30 is impossible

final trellis
#

how

#

i was doing 30 perfectly fine with the old eulerangle code

wintry quarry
wintry quarry
#

please listen

final trellis
#

what 'direction' is Vector3.Angle(transform.forward, Vector3.down) facing?

wintry quarry
#

it's calculating an angle between two different directions

#
  • the direction you're looking
    and
  • straight down
hollow axle
wintry quarry
eternal falconBOT
obtuse oar
#

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.

wintry quarry
#

why are you using SpringJoint in the first place?

rotund portal
#

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

obtuse oar
#

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

wintry quarry
rotund portal
#

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

hollow axle
summer stump
#

Does VS Code say anything about an SDK being needed?

The extension and package is up to date though.

obtuse oar
swift crag
#

The documentation pages describe how they work and have examples

#

MoveTowards moves at a steady rate towards a destination

#

SmoothDamp behaves like a spring

solemn anvil
tame mist
# wintry quarry You should be using Awake for initialization like that

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?

wintry quarry
#

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

quasi rose
#

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.

wintry quarry
#

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

quasi rose
quasi rose
wintry quarry
#

this leads to GC hiccups

#

(same reason it's generally encouraged to avoid frequent allocations/garbage collection in general)

quasi rose
quasi rose
# wintry quarry creating instances of System.EventArgs generates garbage since it's a heap alloc...

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?

wintry quarry
quasi rose
#

I don't think I could OnEnable() across them all due to race conditions. Maybe I'm wrong.

wintry quarry
#

If subbing in Start then unsub in OnDestroy

quasi rose
#

Ah ok

#

That's what i was trying to determine, how to unsub properly then. Thanks!

wintry quarry
#

this will prevent MissingReferenceException when the scene is being unloaded

quasi rose
#

Cool, thanks.

supple wasp
#

How can I make a button make infinite scenes?

frosty hound
#

What is an infinite scene and what does a button have to do with it?

supple wasp
#

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.

slender sinew
wintry quarry
supple wasp
rich adder
#

huh how's it related to infinite scene?

teal viper
#

I think there's a language barrier. Maybe try using Google translate to convey your thoughts...

wintry quarry
frosty hound
#

I suspect they actually mean just creating a new scene/project. As in, each time you press [new] it does so ... hence infinite.

rich adder
supple wasp
#

It's like I was going to create a Minecraft world but in unity within the game

rich adder
#

or maybe make virtual folders in the unity build

#

sounds more like you need to learn about saving data / files instead of scenes

rich adder
#

json is easy to start with

marble sapphire
#

well

#

does anyone know why this wouldn't shoot a Ray?

#

I tried debugging

#

but it says it's unreachable

north kiln
#

Your IDE looks suspiciously underhighlighted, are you getting error highlighting and autocomplete?

marble sapphire
#

well, I tried re-downloading

#

it doesn't seem to change anything much

north kiln
#

I take that as a no then. The configuration steps are here !ide

eternal falconBOT
north kiln
#

and yes, if you put a log after a return statement, how can it be reached? You just returned, you exited the function

summer stump
#

Fix the debug as vertx said, and put a debug before the tag check too. You want to know how far it gets

marble sapphire
#

I'll try that. Thanks.

rich adder
#

yup configured IDE would def show you dark gray for code underneath return statement

marble sapphire
#

OK Now it's kinda going crazy

#

Whup My mistake. I made the Ray linger for 100f

north kiln
#

If you still have not configured your IDE, that's the first thing you should do

marble sapphire
#

well

#

I *did * update the VS

#

but the highlighting didn't change.

rich adder
#

did you read the steps at all?

marble sapphire
#

I read em all

rich adder
#

update is like the last step

marble sapphire
#

yeah

#

but I already installed it manually

#

the proper way

#

2 times

rich adder
#

so what about the Unity Workload in VS Installer

north kiln
#

The workload, the settings in Unity's External Tools preferences

marble sapphire
#

yea

#

already set to unity

rich adder
#

assuming you actually did all the steps, whats left is try regen project files or check the solution explorer if the solution needs rebuild

north kiln
#

set to Unity
What is this referring to UnityChanThink

frozen dagger
#

Is there any way to make animated objects play when time.scale = 0?

#

I’m asking for second time

queen adder
#

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.

frozen dagger
wintry quarry
frozen dagger
#

Is it an option in animation/animation controller or where? Or I need to script it

rich adder
wintry quarry
#

Likely the json data isn't correct for that object

wintry quarry
#

Don't remember which

frozen dagger
#

Ok I’ll check, thank you so much!UnityChanBye

queen adder
#

not sure where mine differs

wintry quarry
#

Your json is incorrect likely

queen adder
#

I had a json syntax error before and fixed it. What about the json file would be incorrect?

wintry quarry
#

The shape of the data

queen adder
wintry quarry
#

It doesn't match the object

wintry quarry
#

It's not called "weapon" in your class

#

It's called "lazerWeapon"

queen adder
#

now that part they never said had to match

#

nice

wintry quarry
#

Of course it has to match

#

All the field names must match

#

How else would it know which data to put where?

rich adder
#

granted with something like json.net you can create custom names and map them accordingly but thats another story

queen adder
rich adder
#

all ur doing is matching names

#

1:1

queen adder
#

but due to this revelation, I must now restructure how my data flows

#

which i've been doing all day

#

fun

rich adder
#

the rest look fine, all ur changing is the main object

#

weapon

queen adder
#

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

rich adder
#

your namings is very confusing not for nothin

queen adder
#

Could rename them Raycast and Projectile weapons

#

but regardless, outcome is the same

rich adder
#

weapon_pickup_manager has stats?

#

anyway you can totally put them in one file, don't see the problem

queen adder
#
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

rich adder
#

I wouldn't nest regular objects in a MonoBehaviour

#

messy

queen adder
#

thats what the tutorial did

#

i just blindly followed along

#

I do as the crystal guides

rich adder
queen adder
#

very

rich adder
eternal needle
#

This is cursed. Why is there a class that says lazer weapon list, then it holds an array and that's its only purpose?

queen adder
#

Blame the tutorial

#

i give up, i will sleep and resume this dumbassery tomorrow

#

Thanks for the help

eternal needle
#

Tutorials should give you a sense more of what exists and what is possible, this wont be too fun to scale up later

queen adder
#

figures

#

First time utilizing json files though, hopefully more success tomorrow

rich adder
#

start small, serialize one object

#

work your way to arrays

#

nested objects are tricky

#

and name things properly lol

queen adder
#

names are the most difficult part

rich adder
#
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

eternal needle
#

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

rich adder
#

yes drop that habit lol

#

ugly af

fierce shuttle
#

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)

rich adder
#

my const usually start with c_ 🥵

eternal needle
fierce shuttle
halcyon steppe
#

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);
            }
rich bluff
fierce shuttle
fierce shuttle
eternal needle
#

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

fierce shuttle
#

Oh, interesting

rich bluff
#

you can also switch layer/ set ignore collisions

candid eagle
#

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 :

rich bluff
candid eagle
#

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

rich bluff
#

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

candid eagle
#

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!

mighty moat
#

Can I set multiple ints to 0 ? like "heat, power, cornFlakes, flem=0;"

rich bluff
#

heat = power = cornFlakes = flem=0;

mighty moat
#

You legend, TYVM (:

idle sleet
#

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

teal viper
idle sleet
teal viper
idle sleet
teal viper
idle sleet
teal viper
#

You can assign whatever value you want🤷‍♂️

valid leaf
#

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

idle sleet
#

Alright thank you both!

swift crag
#
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.

valid leaf
swift crag
#

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

teal viper
swift crag
#

I wouldn't say it's "much better", yes

valid leaf
#

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.

swift crag
#

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); // ???
teal viper
timber tide
#
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

valid leaf
# teal viper I mean, explain why "it's much better"

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

swift crag
#

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

polar acorn
#

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

dry tendon
#

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?

rich adder
#

put your own nmbers

languid spire
#

Vibrate does not take any parameters so I guess the duration is down to the device itself

dry tendon
#

and i don't know how to choose the duration length...

languid spire
#

you cannot

timber hatch
#

(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

dry tendon
#

like the length the vibration plays

languid spire
#

what about 'can not' do you not understand?

dry tendon
#

yeah, i understand it, but imagine i want the phone to vibrate for 5 secs...

dry tendon
#

is it possible?

languid spire
#

NO!!!!!!!!!!!!

dry tendon
wintry quarry
#

Pretty sure phones don't let you do extended rumbles though

#

Just little vibrations

languid spire
#

I mean you can do, at least on Android by calling the OS directly but that is well outside of this scope

hexed terrace
#

Do a coroutine that calls it multiple times until the time limit has ended

dry tendon
grizzled mountain
#

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.

swift crag
#

The animation you play should depend on the local direction of movement.

#
Vector3 worldMove = Vector3.forward;
Vector3 localMove = transform.InverseTransformDirection(worldMove);
grizzled mountain
swift crag
#

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

solemn fractal
#

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

swift crag
#

so, from the player's perspective, their movement is in the left direction

swift crag
#

Oh

#

I see.

#

You want the child to move without changing the direction it's facing.

grizzled mountain
swift crag
#

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

grizzled mountain
#

Thanks for the help I will try this once I am home, can I contact you in case I run into problems?:)

swift crag
#

just ask here again

#

you can ping me

grizzled mountain
#

Will do thank you!

solemn fractal
#

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

swift crag
# swift crag You want the child to move without changing the direction it's facing.

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;
solemn fractal
#

It works, but it is also rotating the boss rotation transform

swift crag
solemn fractal
#

but it is using cs transform.RotateAround(_player.transform.position, Vector3.forward , 30 * Time.deltaTime);

swift crag
solemn fractal
#

and if I try to fix the transoform.localrotation as quaternery,.iodentity it stops working

swift crag
#

So the boss is orbiting the player.

#

And you want the boss to not get rotated.

solemn fractal
#

yes the boss rotation should be fixed and the object boss should go around the player

tepid cobalt
swift crag
solemn fractal
#
    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; 
        }

    }```
swift crag
#

then make the boss move towards that empty object

solemn fractal
#

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

swift crag
#

You're trying to modify the transform of an object that also has a rigidbody on it.

#

That will cause problems.

swift crag
#

The boss would just try to move on top of that empty object.

tepid cobalt
# swift crag ask your question.

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?

solemn fractal
swift crag
#

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

swift crag
tepid cobalt
#

There is going to be lots of people doing this

#

all shattering, collecting fragments

#

dropping their collected fragments

swift crag
#

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

tepid cobalt
#

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

swift crag
#

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

swift crag
#

also, I would consider grouping these fragments together :p

tepid cobalt
#

ye i have them under 1 parent prefab

swift crag
#

I am reminder of UT3's Greed gamemode

#

you collect skulls from killed players

tepid cobalt
#

Yeh it looks fun eh?

swift crag
#

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

tepid cobalt
#

Hopefully i can pull it off, ur a legend thanks for your input

swift crag
#

Even if you want to have lots of physics objects everywhere, 3000 sounds like a ~lot~

pseudo sable
#

similar approach in games like vampire survivors etc, xp gems get grouped at some point

tepid cobalt
swift crag
#

That would be expensive, yes.

#

it would also probably be unstable

#

with objects clipping into each other and going flying

tepid cobalt
#

Ive had it up to about 1200 so far wit RTX

#

then it burns

swift crag
#

I'd make fragments of size 1, 5, 20, 100, 500, something like that

tepid cobalt
#

Voxel size?

swift crag
#

value -- whatever you're counting here

tepid cobalt
#

ah true

swift crag
#

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

tepid cobalt
#

Yeh and just make that piece bigger

swift crag
#

maybe add some randomness too

tepid cobalt
#

or something

swift crag
#

so there's a chance to pick a smaller one anyway

pseudo sable
#

bigger/different colour is usually a good approach for visual clarity that it's worth more

tepid cobalt
#

I was going to add gravitational pull so you dont need to walk close

gusty gyro
#

is this possible like rigging the arm of that charcter within the border using mouse input?

swift crag
#

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

swift crag
tepid cobalt
swift crag
#

figuring out how to rotate the joints so that the gripper is at the desired point

tepid cobalt
#

While you slowly roam around the map like a mamoth

swift crag
#

I forget if unity has that built in for 2D arms.

pseudo sable
gusty gyro
swift crag
#

This looks relevant.

#

Keeping the arm inside the border is the easy part. You'd just clamp the mouse position.

#

Probably like this

gusty gyro
#

Thanks ill look on it

tepid cobalt
#

why does 2d dev look harder than 3d

#

or am i just simple

swift crag
# gusty gyro 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

gusty gyro
#

oooohhhh okay!!! thanksss

sand glen
hexed terrace
tepid cobalt
#

thus why it looks hard because im struggling with 3d xD

tepid cobalt
#

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.

solemn fractal
solemn fractal
#

will need to try

tepid cobalt
stable portal
#

hi can anybody help me ou with NavMesh Components ?

stable portal
#

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.

charred fossil
#

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?

silk night
silk night
#

Ok then ill wait for the video

rich adder
#

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

stable portal
rich adder
#

also like I said if that error is part of this script then it can cause weird issues too

stable portal
charred fossil
#

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.

languid spire
eternal falconBOT
solemn fractal
swift crag
#

you're crossing two positions. that doesn't really make sense

rich adder
swift crag
#

you want to cross two directions

rich adder
#

you have another error @stable portal

solemn fractal
swift crag
#

The first direction should be the vector pointing towards the player.
The second direction should be pointing into or out of the screen

solemn fractal
#

Got it will test now

swift crag
#

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!

merry spade
#

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?

stable portal
rich adder
feral palm
#

can someone help me. when i launch unity on my laptopwith github it wont load . it will give me a error report screen

swift crag
#

also show us what this error is.

feral palm
#

ok

grizzled mountain
swift crag
feral palm
swift crag
#

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.

solemn fractal
# swift crag

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; 
    }
}```
swift crag
#

and (Inverse)TransformDirection is used for a direction. Your scale doesn't matter.

digital latch
#

!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?)

eternal falconBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

digital latch
#

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

sage mirage
#

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?

digital latch
gaunt ice
#

better to contact the creater, the error says there is no PopupShaderProperty method in class MaterialEditor

digital latch
#

ok

swift crag
#

Perhaps the asset is designed for URP/HDRP, and you're using the built-in render pipeline

gaunt ice
grizzled mountain
# swift crag and (Inverse)TransformDirection is used for a direction. Your scale doesn't matt...

// 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

swift crag
#

what's with targetSpeed?

#

show me the entire script

grizzled mountain
# swift crag what's with `targetSpeed`?
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);
            }
gaunt ice
#

!code

eternal falconBOT
grizzled mountain
pulsar lodge
#

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

swift crag
#

do you mean it acts like an obstacle?

#

a rigidbody is just something that can be moved around by physics

pulsar lodge
#

yeah, i Think it is getting caught by my isWalkable logic

#

which should be looking at the layer "SolidObjects"

swift crag
#

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?

pulsar lodge
#

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

rich adder
swift crag
#

Try logging the collider you're finding

pulsar lodge
#

Well, i got it to not collide by changing the layer from default to creating a new one, but it still is not triggering.

pulsar lodge
rich adder
pulsar lodge
#

I'll see if i can figure out how to do that haha

rich adder
#

well. other is what you hit

#

the code editor gives you a bunch of stuff when you do other.

pulsar lodge
#

I thought other was the player in this instance

rich adder
#

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 😉

pulsar lodge
#

So like this?

#

location wise?

summer stump
# pulsar lodge

That's fine. You could combine the two logs if you want though
Debug.Log($"Trigger entered by {other.name}");

pulsar lodge
#

Hmm, even with that in there, nothing prints to the debug log, it is like this is not even executing.

rich adder
#

oh wait you wanna log the Physics overlap not this

#

if ur having problem with iswalkable

pulsar lodge
#

Well even when i comment that out, it still doesnt work, i thought that might have been the cause.

rich adder
#

for movement right

pulsar lodge
#

isWalkable basically is checking if a tile is in the SolidObject layer, if it is dont allow to walk

sage mirage
#

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

rich adder
#

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

polar acorn
sage mirage
pulsar lodge
rotund falcon
#

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?

gaunt ice
#

modulo operation

summer stump
polar acorn
summer stump
#

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

sage mirage
summer stump
#

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

rich adder
gaunt ice
#

i think you likely get an DDOL must be called on root gameobject warning from what you had said

polar acorn
sage mirage
#

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.

polar acorn
#

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

sage mirage
calm osprey
#

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");
}```
polar acorn
summer stump
gaunt ice
#

instantiate will return the object that newly created

calm osprey
#

so I need to put it in update?

summer stump
stable portal
rich adder
gaunt ice
#

what you need to do is

SomeType t=Instantiate(the t);
rich adder
#

is better to use statemachine instead of bools for that reason @stable portal

sage mirage
stable portal
summer stump
polar acorn
rich adder
# pulsar lodge I feel like such a novice 🙁 I'll attempt to get that logged lol
    [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
stable portal
# rich adder is better to use statemachine instead of bools for that reason <@532165031303970...

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...

▶ Play video
rich adder
sage mirage
polar acorn
summer stump
polar acorn
rich adder
#
  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

stable portal
#

it only waits

#

the function chase or attack just dont activate

rich adder
#

from the video you sent the log was printing

stable portal
#

only the waiting log yeah

#

so the enemy was waiting

#

oh

#

my bad them sorry

rich adder
#

oh wait no

#

myb

stable portal
#

yeah

#

only wait was printing

rich adder
#

ok yeah playerInSeeRange is false

#

Im guessing it could be a layer issue

stable portal
#

the enemy is WhatIsEnemy layer

rich adder
#

screenshot the Player object

stable portal
#

ok

rich adder
#

yup

#

layer issue

#

Your enemy is looking for WhatIsPlayer

#

your player is Default

stable portal
#

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?

rich adder
#

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)

rich adder
#
[SerializeField] private Collider myCol
void Foo(){
var enemyBullet = Instantiate(etc..
if(enemyBullet.TryGetComponent(out Collider col))
Physics.IgnoreCollision(col,  myCol, true);
}```
pliant oyster
#

2D - How do I quickly set the opacity of a panel in code?

slender nymph
#

reference it's image component and modify its color property

stable portal
#

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);

    }
pliant oyster
slender nymph
#

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 ()

pliant oyster
#

Ah okay, thanks

rich adder
#

ur not grabbing it from the instance

stable portal
#

im not quite sure if i understand what do you mean by that could you please correct the core or explain thanks.🙏

slender nymph
#

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

raw hamlet
#

newbie question but how do I reference a gameobject to a prefab?

raw hamlet
#

thx

eager elm
swift crag
raw hamlet
swift crag
#

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.

raw hamlet
#

selected ObstacleSpawner

swift crag
#

see the link boxfriend posted.

pliant oyster
#

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;
        }
slender nymph
#

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

languid spire
slender nymph
#

so an alpha of 100 is the same as an alpha of 1

pliant oyster
#

Ah okay, thanks

slender nymph
#

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

queen adder
#

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
slender nymph
#

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?

queen adder
#

i call tip when mouse entered something that should have toooltip

raw hamlet
#

I'm still confused after reading the docs. I don't understand. I'm getting

slender nymph
#

otherwise you are trying to drag an object that doesn't have the component you are tryign to reference

raw hamlet
slender nymph
slender nymph
pliant oyster
slender nymph
pliant oyster
#

Because I just used 0.1f as a test value

raw hamlet
#

I tried to use GetComponent to access the variable

slender nymph
slender nymph
feral ice
#

How do i make the green arrow point towards the middle instead of the blue arrow?

rich adder
slender nymph
#

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

feral ice
#

huh

slender nymph
#

well that's certainly not a helpful response

feral ice
#

oh

#

set the player.up to something

queen adder
#
(spriteRenderer.sortingOrder <= 0 ? ReferenceHolder.Instance.tileMap : ReferenceHolder.Instance.tileMap1)?.SetTile(transform.position.SnapToInt(), null);
```can `?.` work here?
slender nymph
#

do not use ?. with objects that inherit from UnityEngine.Object

queen adder
#

just gonna get rid of this 🥹

slender nymph
#

that is precisely why you should not use ?. with unityengine.objects

pliant oyster
#

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
slender nymph
# queen adder just gonna get rid of this 🥹

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

slender nymph
pliant oyster
#

How do I start it correctly?

slender nymph
#

by using StartCoroutine

pliant oyster
#

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

slender nymph
#

share the full class using a bin site 👇 !code

eternal falconBOT
pliant oyster
slender nymph
#

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

slender nymph
#

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

stiff stump
#

does the OverlapBoxAll size height and width or is it half of height and half of width?

pliant oyster
#

Ok I changed the while (opacity < 1) line to while (opacity < 255) and now the panel appears again, though again it appears instantly.

slender nymph
#

it's like you haven't even been listening

pliant oyster
#

Apologies but I have some mental disabilities, so that might be why

solemn fractal
#

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?

rich adder
#

ignore layer or ignore collision?

solemn fractal
#

what do you mean? can you explain better?

rich adder
solemn fractal
#

oh ok, will look into it, thank you

rich adder
pliant oyster
distant mesa
#

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.

distant mesa
#

Its something my collegues work with, i think network/server stuff that holds data

#

personally dont know much of it

slender nymph
distant mesa
#

but basically from a web page

rich adder
#

if you need more like realtime messages websockets make more sense

distant mesa
#

"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

rich adder
#

depends

distant mesa
#

but if it has to be faster, websockets would be the go-to?

rich adder
#

they have diff use case

strong wren
rich adder
#

Websocket is good for keeping a connection open and transfer data frequent

strong wren
#

WebSockets are a bit more efficient for continuous data than HTTP.

distant mesa
#

Ohhh okay

#

good to know

#

does it take up alot of performance?

pliant oyster
rich adder
distant mesa
#

ooo great ty!

sharp wyvern
#

whats the proper thread to use for Unity Editor crashing help?

rich adder
#

!bug

eternal falconBOT
#

🪲 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

sharp wyvern
#

ollow by a crash report popup

rich adder
#

could probably be an infinite loop in your code

sharp wyvern
#

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.

cosmic dagger
#

can't you allow Unity through firewall settings?

sharp wyvern
#

tried the stuff I found online, that got me to ALMOPST get unity loaded, but it still crashed after that popup

sharp wyvern
cosmic dagger
#

Ahh . . .

rich adder
#

could be Visual Studio also

sharp wyvern
sharp wyvern
rich adder
#

hmm strange, not sure why it would crash it

#

check editor logs mybe

sharp wyvern
#

(also that dll shows up in the projects' libraray folder, and I got a zillion projects)

sharp wyvern
#

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

orchid trout
#
    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 ![UnityChanThink](https://cdn.discordapp.com/emojis/885169594560544800.webp?size=128 "UnityChanThink")
#

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?

sharp wyvern
orchid trout
#

one for material property blocks, one for materials, both identical otherwise

sharp wyvern
#

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,

orchid trout
swift crag
#

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

sharp phoenix
#

BoxCast

solemn fractal
#

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.

tiny bloom
#

Where do u get the id of the bool from?

slender nymph
#

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

sturdy lintel
#

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;
        }
    }
}```
rich adder
#

why not Input.mouseScrollDelta

sturdy lintel
sturdy lintel
weary moss
#

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

slender nymph
#

use an if statement inside of update. if variable is less than threshold add 1

rich adder
sturdy lintel
# rich adder https://docs.unity3d.com/ScriptReference/Input-mouseScrollDelta.html
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
sturdy lintel
#

I don't want my camera to go nearer than 5f from the LookAtPosition

nimble sorrel
#

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

rich adder
#

oh I see the magnitude

sturdy lintel
rich adder
#

its prob not

#

that if statement is sus tho

twin bolt
#

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; } } }

crude prawn
#

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

slender nymph
#

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)

twin bolt
rich adder
sturdy lintel
rich adder
twin bolt
#

even though the texts are null

sturdy lintel
slender nymph
twin bolt
# slender nymph 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;
    }   

}```
delicate portal
#

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!

slender nymph
twin bolt
rich adder
frosty hound
sturdy lintel
rich adder
#

a better solution would prob be clamp

sturdy lintel
slender nymph
slender nymph
#

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

twin bolt
slender nymph
#

well what debugging have you tried?

rustic verge
#

how do i fix this the first image is my code

slender nymph
#

what have you actually done to make sure that the values you are using/checking are actually what you expect them to be?

delicate portal
#

Use lerp?