#💻┃code-beginner

1 messages · Page 490 of 1

lethal meadow
#

fixed it by changing the raycast origin point

nocturne kayak
#

Hey, back with the same old problem, cutting straight to the point- i'm trying to achieve a transform similar to the transform you get in the editor, but in-game

#

so far i managed to cook it up, the cube's moving on xy based on the mouse position

#

i also made some basic scripts for the handle which basically tell me if someone clicked on the axis handler or not

#

but i can't for the love of me figure out how to implement drag axis to drag cube

wet bobcat
#

Im setting up a VR-project with ambisonic sound (360 surround) and want to know...

where objects are in relation to where the player faces...

...so I can pan the sound of the objects in external software.

How can I go about to get a value that represent this, that I can convert to degrees, what solution/technique shall I use? Dont know where to look atm.

nocturne kayak
#

dot product will help you see how close to the sound source the player's looking at

#

Quick vector subtraction will tell you the distance

#

correction: dot product will tell you if the source's behind or in front of the player, 1 is directly in front, -1 is directly behind

rocky canyon
# nocturne kayak

once u click on handle you could use the mouse position + raycast and project on plane to the plane parallel to the handle and then just use the delta to move the object around

nocturne kayak
#

also, wouldn't defining a plane make it so i can move it on both x and y axis of that plane?

#

nvm,you're talking about a plane parallel to the cam?

wet bobcat
#

How can I see left or right panning placement? Can you please point me to a script or tutorial that shows this. I am installing the project on saturday.... I really want this to be a part of it.

rocky canyon
#

for a top down map style cam controller.. but ```cs
if (Input.GetMouseButtonDown(0)) {
Plane plane = new Plane(Vector3.up, Vector3.zero);

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        float entry;

        if (plane.Raycast(ray, out entry)) {
            dragStartPosition = ray.GetPoint(entry);
        }
    }```
#

im guessing its similar to that

nocturne kayak
#

but it'd involve a bit of vector maths, which i'm rusty on, unfortunately

#

basically subtract playerpos fom soundsourcepos relative to the playerpos

willow scroll
nocturne kayak
#

if the result's positive, it's on the player's left, negative means player's right

rocky canyon
#

i guess ud just use the cubes forward, right, or up and then the cubes position

wet bobcat
# willow scroll Not sure what this means, could you elaborate, please?

I have several obects in a scene that the player (with VR-headset) can interact with. When the player turns around, or move the objects, I want the objects sound sources move accordingly. So I can pan this around in a 7 speaker circular setup. I use external software for synthesis (PureData). I just want a value for each object in the scene that represents its position (in relation to the player) in something similar to degrees. Then I send this out over UDP/open sound control. Everyhing is working OK, except panning. Please tell me if I should clarify.

willow scroll
wet bobcat
nocturne kayak
willow scroll
#

How would you represent the position in degrees?
If you try to think of it as a degree distance from the direction of the camera to the player, there will be a possibility of the objects in the same "line" having the same value

nocturne kayak
#

Jeus christ this is so frustrating

#

i just want to manipulate objects ingame like you would on the editor

jolly urchin
#

What's causing this 😭

#

I'm losing my mind I can't figure it out

willow scroll
rocky canyon
willow scroll
jolly urchin
wet bobcat
rocky canyon
#

thats when you break it into pieces.. and figure out how to do the thing u dont know how to do

edgy prism
#

Hello this might be some sort of quirk of unity but in case its not I would like to understand whats causing it. Im checking positions on my grid in 2D and when I change the float in my IsPositionOccupied function to 2.5 and get to a gamestate where the code is being run Unity consistently freezes

Vector2 spawnPosition = Vector2.zero;
        bool validPosition = false;

        while (!validPosition)
        {
            spawnPosition = new Vector2(Random.Range(-3, 3) + 0.5f, Random.Range(-8, 7) + 0.5f);
            validPosition = !IsPositionOccupied(spawnPosition, 2f);
        }

        // Add position to reserved list
        reservedPositions.Add(spawnPosition);
bool IsPositionOccupied(Vector2 spawnPosition, float radius)
    {
        foreach (Vector2 reservedPos in reservedPositions)
        {
            if (Vector2.Distance(spawnPosition, reservedPos) < radius)
            {
                return true;
            }
        }

        Collider2D overlap = Physics2D.OverlapCircle(spawnPosition, radius);
        return overlap != null; // If there's a collider, the position is occupied
    }
willow scroll
willow scroll
willow scroll
steep rose
jolly urchin
steep rose
willow scroll
jolly urchin
steep rose
eternal falconBOT
steep rose
#

and also please take the time to !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

steep rose
#

instead of copying and pasting everything

jolly urchin
#

just the .cs?

willow scroll
# jolly urchin Yes.

We do not help people, who don't know what they are doing, here, since they are the guys, who cause the most troubles.
You'll probably have to either follow the tutorial better or start actually learning game development

steep rose
#

it tells you how

jolly urchin
steep rose
wet bobcat
jolly urchin
#

It's in the thing I sent

#

I put it on the paste site I usually use

slender nymph
#

that site appears to be absolute garbage for sending code. there's no line numbers or syntax highlighting

steep rose
#

ah I see, did you assign the sound variable in the inspector?

jolly urchin
#

I figured that's what the problem was, but it doesn't allow me to alter it

steep rose
#

it is expecting an AudioSource

#

are you trying to give it an AudioSource?

jolly urchin
slender nymph
#

audio files are not AudioSources. those are AudioClips

#

an AudioSource is the component that plays an AudioClip

jolly urchin
#

I have an audio source

#

It won't let me assign it to the script

slender nymph
#

what object is the AudioSource on

jolly urchin
#

LadderClimbSoundEffect is the audio source

#

I click it and drag to assign and it doesn't accept

slender nymph
#

do not assign it on the script asset, do it on the actual Ladder object in the scene

jolly urchin
#

Alright

#

Even though I've deleted that object though it won't compile

slender nymph
#

what compilation errors do you have

jolly urchin
#

Lemme try it again, one moment

willow scroll
wet bobcat
jolly urchin
slender nymph
#

this is a runtime exception, and has absolutely nothing to do with compilation. it tells you exactly what you need to do. you have an instance of the Ladder component in the scene where the sound variable has not been assigned

jolly urchin
#

How would I easily locate that instance? i've not been able to find it

slender nymph
#

you can use the search bar in the hierarchy, search t:Ladder to find all instances of the Ladder component

nocturne kayak
#

This is proving way too troublesome so i'm gonna be straighter here

#

Is there an easy way to replicate transform gizmo behavior without implementing the built-in gizmo system?

sage peak
#

Hey everyone! I dont know if this is anything to do with the code, but im facing an issue.
In my runner game for some reason after I added a road model and the obstacles, it doesnt let me jump as I want to, but if I keep pressing the arrow key it works eventually, maybe its the collider or something I dont know

#

Heres the script

#
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private CharacterController controller;
    private Vector3 direction;
    public float forwardSpeed;

    private int desiredLane = 1;
    public float laneDistance = 4;

    public float jumpForce;
    public float Gravity = -20;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        direction.z = forwardSpeed;

        if (controller.isGrounded)
        {
            // Reset vertical speed
            direction.y = 0;

            if (Input.GetKeyDown(KeyCode.UpArrow))
            {
                Jump();
            }
        }
        else
        {
            // Apply gravity when in the air
            direction.y += Gravity * Time.deltaTime;
        }

        // Lane switching logic
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            desiredLane++;
            if (desiredLane == 3)
                desiredLane = 2;
        }

        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            desiredLane--;
            if (desiredLane == -1)
                desiredLane = 0;
        }

        // Calculate target position based on lanes
        Vector3 targetPosition = transform.position.z * transform.forward + transform.position.y * transform.up;
        if (desiredLane == 0)
        {
            targetPosition += Vector3.left * laneDistance;
        }
        else if (desiredLane == 2)
        {
            targetPosition += Vector3.right * laneDistance;
        }

        // Smooth lane movement
        transform.position = Vector3.Lerp(transform.position, targetPosition, 80 * Time.fixedDeltaTime);
    }

    private void FixedUpdate()
    {
        controller.Move(direction * Time.fixedDeltaTime);
    }

    private void Jump()
    {
        direction.y = jumpForce;
    }
}```
short hazel
#

The last line of Update breaks the whole thing. You cannot directly assign to transform.position when using a CharacterController

nocturne kayak
#

than what i'm trying, i've been around for a few hours

#

hopefully this will get across what i'm trying to achieve, i managed to get a simple when mouse move cube move type of setup

#

but i'm trying to do that on the cube's local axis, and move along it when i drag one of those axis handles

rich adder
ruby python
#

'ello again all. So, I've figured out the whole rotating a skybox using a custom skybox shader. I'm struggling a little with the Maths involved in getting the directional light that I'm using as my sun to rotate in sync with the skybox though.

Here's The Code

https://hastebin.com/share/fadufedapi.csharp

And here's the 'layout' of the Skybox Material. I figured grabbing the vectors and using those to control the sun direction would be the way to go, but the sun, while rotating, barely moves and I'm not really sure what kind of multiplier I should be using (I've tried a bunch of values in increments of 10 so far).

I will say that it's late and I'm very tired, so could be something ridiculously simple and obvious. Just want to get this bit done and then go to bed. lol.

nocturne kayak
rich adder
nocturne kayak
#

this is the code in the cube right now

ruby python
#

Dangit, forgot the image. lol.

rich adder
nocturne kayak
#

Ah, yeah, i just realized

#

sorry, my brain's fried at this point

short hazel
nocturne kayak
#

i just can't figure out what feels like the simplest of things

lethal meadow
#

if someone could help with this

#

I'd appreciate it

nocturne kayak
#

which is

#

when drag blue pill

#

cube move along blue pill axis

#

it feels so stupid

rich adder
rich adder
nocturne kayak
#

it feels like it should be simple

#

but apparently it isn't

short hazel
#

It's very much not simple to replicate this as close as Unity does it

rocky canyon
#

ya, i was gonna say.. to me it feels deceptively easy

short hazel
#

You'll need planes, raycasts, vector projections in order to adjust the object's local axis being moved to the mouse

nocturne kayak
#

i'm not trying to do the fullfeatureset of gizmos

rocky canyon
#

theres assets on the store that do this.. runtime transform gizmo or w/e but they pricey for what they are

nocturne kayak
#

just move it around , and rotate it in a single axis

rocky canyon
#

i think imma give it a try later on today

#

already have a pickup and carry script + top down isometric camera controller

#

sooo thats both pieces i need.. i could combine them probably and get something working.. i'll give u a ping if i do caecpr

sage peak
#

Do I use it like this? If not then Im getting errors

rich adder
rocky canyon
#

characterController.Move(finalVector * Time.deltaTime);

nocturne kayak
#

i knew that'd take a lot of moving pieces, but still

nocturne kayak
#

but the middle term is [??????]

short hazel
#

Not sure from where you'd even begin to implement it, but it would be something like below (taken from your image). This would "track" your mouse cursor perfectly from screen space to world space:

#

Red mouse position is the resulting world position of raycasting the plane

nocturne kayak
#

so, first things first

#

i gotta dynamically create a plane when an axis is clicked

rocky canyon
#

^ thats what i was trying to get out earlier

nocturne kayak
#

and then raycast to it?

rocky canyon
#

that diagram is 🔥

nocturne kayak
#

Agreed

#

thanks for the diagram btw

#

so if i have a plane and a line on that plane

#

i can just get the closest point on plane to line

short hazel
#

Yep, building the plane requires a point and a normal. That could be the center of your object (for the point), and for the normal a few if statements could solve it:
Clicked gizmo is Z => normal is transform.up
X => same
Y => any of transform.forward or transform.right

#

Then you feed your ray from Camera:ScreenPointToRay() into thePlane.Raycast() and get the position on the plane
And for projecting there's a few options available

nocturne kayak
#

oK

#

Let me try building it so far beforehand

#

feels like i'm calling it wrong, also that

#

that is what visual studio's telling me

short hazel
#

Plane is a type, so you need to make a variable and put a new instance of it into it

Plane p = new Plane(normal, point);
rocky canyon
#

lol he explained it sooo much better than i tried to

bold saffron
polar acorn
bold saffron
#

OH SHIT I FORGOT THE BREAK

#

😭

keen dew
#

There shouldn't be a while loop there at all

bold saffron
#

oh

#

wait

#

how

polar acorn
bold saffron
#

so that it can run even if roundtype changes

polar acorn
#

So, if roundType is 1, it's going to freeze for about a second then do that one always

bold saffron
#

oh

polar acorn
#

Loops run to completion

#

Until the loop is exited, literally nothing else can happen

#

So, every frame, you're going to loop that while loop until it runs the condition for complete3, then next frame it'll do it again

bold saffron
#

thank you! I rewrote the code so the while loop isn't needed

dense pike
#

Hii could I use some advice on my game

deft grail
coral ivy
#

I was working on a project, created a terrain. I saved and closed the project. When I opened the project, all my stuff was gone and it onpened a DemoScene, I can't find where all my stuff went.

deft grail
earnest helm
#

!code

eternal falconBOT
nocturne kayak
#

Well, i don't know.

#

might be generating a plane, might not, i can't find a way to debug that

#

i tried to make it so it spawns a gizmo on that plane, just to i know it's there, but no luck on that front either

teal viper
gloomy marsh
#

when i create action unity add using System; namespace and cant use Random.Range because UnityEngine.Random and System.Random have same class name Random. is there way to fix it

nocturne kayak
wintry quarry
#

Either type UnityEngine.Random.Range every time you use it

#

Or put this at the top:

using Random = UnityEngine.Random;```
gloomy marsh
#

really?

wintry quarry
#

Really

gloomy marsh
#

alright

#

thanks

wintry quarry
# gloomy marsh really?

You understand why this is a problem right? The System namespace also has a class named Random

#

So it doesn't know if you want System.Random or UnityEngine.Random

#

The solutions I showed you above remove the ambiguity.

gloomy marsh
steep rose
#

whats not profesional about using system.random or unityengine.random?

wintry quarry
#

You could also do something like:

using UnityRandom = UnityEngine.Random;
using SystemRandom = System.Random;``` and then use ```cs
float result = UnityRandom.Range(a, b);
int anotherResult = new SystemRandom().Next();```
#

if you want to use them both for some reason

#

¯_(ツ)_/¯

gloomy marsh
steep rose
#

beginner and professional should not be in the same sentence

#

just use the functions normally like a sane person

languid spire
#

rofl, a beginner worrying about appearing unprofessional

gloomy marsh
#

i m kidding

steep rose
#

im not sure why you would need to rename and assign them differently

vestal isle
#

in unit test runner, how the heck do I reference a class in scripts folder?

#

Obviously using this suggestion won't work because the csproj is stupidly enough auto-generated.

wintry quarry
#

then you can have your test assembly reference the main code assembly

vestal isle
#

notlikethis my lord

wintry quarry
#

To make assemblies in Unity you use Assembly Definition files

#

It's really not as scary as it sounds

vestal isle
#

Thank you!

#

Gee, and now I get like 50 errors of missing references 🤔
I thought it'd be easy to set up, turns out it wasn't.

wintry quarry
# vestal isle
  1. The TMPRo ones are because you didn't reference the TextMeshPro package in your game assembly. Fix that by adding a reference to TextMeshPro
#
  1. The Drawing one - not sure - it depends what this "Drawing" class is and where it lives. Most likely the fix is adding another reference, or moving that script into the assembly if it lives outside.
#

But even though there are "50" errors it looks like really it's only two

vestal isle
#

UnityEngine.Rendering doesn't even exist in the assembly definitions

wintry quarry
vestal isle
#

Not sure why it referenced that though .. So I can just delete it

#

I should be good, just needs refactoring

#

Okay, I'm good. I was just referencing pointless things.
Thank you 😛

hollow wagon
#

Anyone has a good tutorial for a 3d character movement that has walk run jump and crouching??

steep rose
cosmic dagger
steep rose
#

most of them provide what he is asking

steep rose
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

hollow wagon
hollow wagon
steep rose
hollow wagon
steep rose
hollow wagon
steep rose
#

if not its best to follow the link i provided

hollow wagon
hollow wagon
steep rose
ivory jasper
#

how can i have a repeating texture for the background of my camera?

dusky sentinel
#

hi! The facial expressions on the triangle represent the trust level between the characters. I want to update them when the trust level goes up. Right now im testing that by increasing the trust level of each relationship when I press numbers on the keypad.

The saddest face represents trust = 0 and the happiest face represents trust = 3. There are a total of 4 facial expressions. By default, all the faces are set to the saddest face and each face is named after a pair of characters(ex) annie-edward). However, when I press the number keypad, I see the trust levels increase but the facial expression sprites don't get updated. For instance, when I press one, the relationship at index=0 should increase in trust level and the face should be changing to a less sad one. I'm not sure why these changes in sprites aren't appearing when I press the keypad.

ivory jasper
rich adder
ivory jasper
#

oh okay

nocturne kayak
#

Is anyone here particularly knoweldgable on the MetaXR toolkit?

crisp token
teal viper
#

Or add more info to your logs, so that we can understand what variable it is.

crisp token
#

the other ones were just me trying to see if im dumb

#

ive done rotation before its the first thing most people do idk why this is giving me so much issue now

#

like the prefab rotates and the transform.forward should change idgi

teal viper
#

Well, I told earlier. .forward can't be 0,0,0 so I don't know what variable it is that we see in the log.

crisp token
#

oh

teal viper
#

Don't ever debug the values alone. It's a very bad practice.

crisp token
#

what should I debug instead?

teal viper
#

Something meaningful, so that we understand the context of the log

#

For example "transform forward: {value}"

crisp token
#

so transform.forward is actually stuck at (0,0,1) (my b)

teal viper
#

Great, that's progress.

#

My guess is that the transform that you debug doesn't belong to the object that you rotate in the scene.

#

Debug the name of the object

crisp token
#

hmm, I thought the transform keyword automatically would, but let me use GetComponent to make sure and debug the object

teal viper
#

No need to use GetComponent. It would result in the same thing.

crisp token
#

object seems to be correct

teal viper
#

You can also pass the object itself as the second parameter of the Log. That would allow you to click the log message to select the object in the hierarchy.

crisp token
#

doing that now

crisp token
#

this is strange

teal viper
crisp token
#

yeah the PlayerRotation is running directly on the root

#

and in the inspector its y rotation is changing

#

maybe since its rotation is always (0, x, 0) . transform.forward will actually always return the same thing? (idts)

#

cause the blue arrow in the scene is changing

teal viper
#

I see that there's networking involved. I wonder if it is related.

crisp token
#

yeah but rn the networking stuff isnt doing anything, it could be some of the overhead

#

like Network Object for ex

teal viper
#

How are you rotating the object?

crisp token
#

i was tersting different methods of setting rotation to see if that would fix it

teal viper
crisp token
#

its updating properly

teal viper
#

So, it's something resetting the property afterwards.

crisp token
#

is it a read only variable, could i be resetting it"?

#

well i cant set .forw but ig i can reset rotation

#

ill look into it, i might have a bigger issue here. Thanks for your help

teal viper
crisp token
#

you can set transform.forward?

teal viper
#

Yes

crisp token
#

oh, ill look out for that then. Im going through my whole tick cycle rn

teal viper
#

That would rotate the object such that it faces the direction.

crisp token
#

@teal viper I fixed the error by swapping the exectution order of PlayerRotation and some other script. The playerrotation was applying the rotation after the Transform.forward. I am still a little confused, however, because I do not think that transform.forward would be resetting on its own. There may still be another error with my code

teal viper
crisp token
teal viper
#

Ah, maybe I misread.

topaz mortar
#

I'm making a 3d tower defense game, currently adding exploding missiles that need to hit multiple enemies when they explode.
I saw a Brackeys tutorial where he uses Physics.OverlapSphere to get all colliders within range.
On the docs of Physics.OverlapSphere is says consider using: Physics.OverlapSphereNonAlloc, when should I use which? Is this a good way to make exploding missiles in a TD?

teal viper
#

Transform forward does not reset on it's own. It must be either your code or potentially other components(like the networking related stuff).@crisp token

crisp token
#

ugh i hate not knowing why a fix works but it works perfectly lmao.

#

if there was some reset, its not like this would fix it anyway

#

im wondering if it has to do with the fact that there is a rigidbody on the object and I manually call the physics simulation

teal viper
teal viper
crisp token
#

Just tested it by reversing the order of execution and using Rigidbody.Rotation (which apparently is proper way) and it works fine. So yeah, that was the issue, glad we figured it out

#

thank you again @teal viper

topaz mortar
#

ah raycasts again 🙂 definitely an option

eternal needle
#

though similar to the discussion yesterday, raycasts alone dont work here either

#

the post they linked you doesnt even have a solution.. its just someone saying it doesnt work and there not being a real answer

#

!collab

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

queen adder
#

!vs

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

topaz mortar
#

Physics.OverlapSphereNonAlloc does seem a lot simpler

eternal needle
# topaz mortar they don't?

a raycast gets you information in a straight line, you arent gonna reasonably use it to get you everything in a sphere. the only use for raycast here would be checking line of sight

topaz mortar
#

but you can just fire raycasts all around not?

keen dew
#

Do you have a reason to check the line of sight? For example are there obstacles that would prevent explosion damage even if the target is inside the blast radius?

topaz mortar
#

it's an option, but I don't think it's necessary, I don't mind my explosions going through the walls

keen dew
#

Then I don't see why you wouldn't use OverlapSphere as it's literally one line and the simplest way to do it

elfin hatch
#

I'm currently trying to make a hinge-joint onto a gameobject that needs a non-kinematic rigidbody, but was concave....
So I cut the object into 6 convex pieces as child objects, each with their own piece of meshrenderer/meshcollider, and connected them together with fixed-joints.

I'm having issues though using that parent gameobject to hinge-joint onto something... the item just starts floating away.
Is this a problem because the colliders aren't on this object, and are instead child-objects? or how do i solve this

#

nvm just ignored the parent, and did it on the 1 child thats closest.
this whole joint stuff is still "wobbly" though... time to tinker

topaz mortar
keen dew
#

I don't see how firing dozens of raycasts and pruning the hits for duplicates could be faster than one overlapsphere

teal viper
#

Premature optimizations: make it more code and less performant

topaz mortar
#

I have no idea about the performance of physics, but you're probably right

eternal needle
# topaz mortar I have no idea about the performance of physics, but you're probably right

i wasnt even really referring to the performance. raycasts and overlap spheres solve entirely different problems.
raycasts cant solve the problem of finding every object in a sphere.
First issue is raycasts in 3d by default dont hit the object they start inside of. Theres workarounds to this but its not the main point
2nd issue is just math. As the sphere grows larger, you arent gonna add more raycasts to cover the range of the sphere. Refer to the image i made. Even if you say you can add more raycasts to check, i could always just make the sphere larger in the example and draw a box between the raycasts near the edge of the sphere. Even if this is an extreme case, it still shows cases where raycasts will fail

fluid lagoon
#

i cant name my parameters please help it ruind all my code and i am really stuck please help me
Image

slender nymph
#

don't crosspost. this is not a code issue. have you tried restarting the editor

fluid lagoon
#

so where should i post this and do you mean restarting unity?

slender nymph
#

you've already asked the question in the correct place #💻┃unity-talk
this is why you shouldn't post questions all across the server. and yes, typically when people refer to "the editor" they mean the Unity Editor, which is the application you use to actually edit your project

topaz mortar
#

what would I use to draw lines across my grid in 3d to show the path monsters will take
I want to draw this in code since the path is dynamic

slender nymph
#

just for debugging purposes? because you can use Gizmos for that

topaz mortar
#

no to show in the actual game

#

been searching for it for a bit, but can't find exactly what I need

teal viper
slender nymph
#

LineRenderer or you can draw the lines manually with GL.LINES

topaz mortar
#

so I add a linerenderer component on my current grid node?

slender nymph
#

what you attach the linerenderer(s) to entirely depends on your setup so we can't really answer that 🤷‍♂️

teal viper
#

Presumably it's a game wide mechanic, so you probably should implement it as a singleton or a manager. Basically, one GameObject that draws all your desired lines.

#

At least that's what I'd do probably.

topaz mortar
#

cool thx, seems to work, now just need to finetune a bit (or a lot)

tulip nimbus
#

ok why wont this work? Should i use OnColliderStay?

slender nymph
#

GetKeyDown is only true for the first frame that the key is pressed and OnTriggerStay (as well as all of the physics messages) is only ever called on FixedUpdate frames so you are likely just missing the input

topaz mortar
#

Which part is not working? If you don't see OnEnemy in the console then you have an issue with your trigger, not sure what that even is OnTriggerStay?

tulip nimbus
topaz mortar
#

yeah seems right, so do you see the OnEnemy text? there's several potential issues if you don't

tulip nimbus
#

nah i dont see anything, not a single message unfortunately

#

the tags are assigned

#

ill try to figure something out with what boxfriend said and ill see

topaz mortar
#

show us your objects in the Inspector

#

boxfriend's message only applies if you see the OnEnemy in console

slender nymph
tulip nimbus
#

i might have to check Is trigger one sec

keen dew
#

no collider

tulip nimbus
#

i just added one, compleately my bad, but it still wont work ):

keen dew
tulip nimbus
#

👍

tulip nimbus
#

ill go trough the site thank you all for your time

topaz mortar
#

Unity should hire boxfriend as a Discord helper 🙂

slender nymph
#

lol as much as getting paid for this sounds nice, i definitely don't want to be required to help people lmao

silk night
#

can confirm, went from moderating a big discord voluntarily to getting paid to do it part time, leeched all the fun out of it 😄

tulip nimbus
#

I figured it out on the website, as i was using a 2D space i had to use OnTriggerEnter2D. I didnt know that. thank you guys so much

burnt vapor
#

Especially considering how often it is used

frank pelican
#

oh shit, sorry

brittle pond
#

I'm not sure if this is a beginner question. But i'm having trouble with referencing a script. I've never used any type of help from chatting before so bare with me.

teal viper
brittle pond
# teal viper Maybe explain better what you're trying to do and what the script is depicting?

Okay. So i created a gameobject that has an exp bar (ui) which has a script attached to it to update the current xp value which changes the fill amount of the exp bar. Now i cloned that exp bar (because i need the player to be able to instantiate multiple exp bars) the issue is just, when i update the amount of exp (by the press of a button) it only updates the value on the original exp bar and not the one cloned one

#

I hope that kind of captures what i'm trying to do

#

i'm not the best at coding but i'm trying to learn

#

trying to reference to this

languid spire
# brittle pond

public class progresbar : MonoBehaviour
C# is case sensitive

brittle pond
#

Thank you

willow scroll
#

Represent the object's position relatively to the camera's direction

willow scroll
# brittle pond

The classes in C# are called with PascalCase, so YourMethodIsSupposedToLookLikeThis.
Also this.gameObject can be removed, since the GameObject.GetComponent method can be used without the GameObject reference because of your MonoBehaviour already deriving from it

stuck void
eternal falconBOT
stuck void
#

i don't understand I'm new to the server my friend

teal viper
#

Do you not see the bot message above?

topaz mortar
#

Is it bad to first do transform.Translate(newPosition) and then after that clamp the x, y, z values and set transform.position = clampedPosition?
Or would it be better to just set the transform.position to the clamped values? Not sure if .Translate does anything special

#

Why would you even use transform.Translate? why not just transform.position = newposition?

ivory bobcat
# stuck void i don't understand I'm new to the server my friend

To share large code blocks (more than a few lines of code), click one of the code sharing services. Copy your code from your script and paste it into the site. Press the save button on the site. There will be a save button usually at the top right or left. The URL should have changed now. Copy the changed URL and paste it here.

teal viper
#

Translate moves the object by the movement vector that you pass into it. Setting position sets the object position to the specified position.

topaz mortar
#
{
    if (relativeTo == Space.World)
    {
        position += translation;
    }
    else
    {
        position += TransformDirection(translation);
    }
}```
Seems pretty similar?
So it's just transform.position += amountToMove then? Not sure why there's a function for this? Am I missing something?
teal viper
#

Yes, it is.

#

+= is not the same as =

topaz mortar
#

why is there a function for that? why don't ppl just += instead?

teal viper
topaz mortar
#

cool thx 🙂

teal viper
ivory bobcat
topaz mortar
#

so back to my original question
is it ok to set the position, clamp it and then set it again?
or would it be (noticably) better to only set the position once? so calculate the new position first, clamp it and then just set it once

teal viper
ivory bobcat
burnt vapor
#

We're talking about a mere nanosecond difference here for setting a value

ivory bobcat
#

Unless you've got physics sync with the Transform enabled or something.

topaz mortar
#

yeah mostly asking so I get a better understanding of how things work 🙂

languid spire
topaz mortar
stuck void
#

@stuck void Ok can someone help me fix my player because the player turns when i pick up an item and i open the window here's the code and a visualization of the problem

https://paste.ofcode.org/34UznaDnnfXsYeFpRjRtUec FirstPerLook script
https://paste.ofcode.org/ZKpHqRzxhgRYCLUTFPvegP FirstPersonAdvancedMove script
https://paste.ofcode.org/CNPmVMJK9TMNVA8Dsq3n3i Inventory Manager script
https://paste.ofcode.org/9EG83EaWVdBRAx6M2AvQYq Item Pickup script
https://paste.ofcode.org/zT2WF47ketFvzzgnxAWXbM Item script
https://paste.ofcode.org/z293kmJqnnbNFbFnYgj9CA Radio manager script

burnt vapor
#

If you stumble upon needing to improve your performance this would be one of the last things you improve on

burnt vapor
topaz mortar
#

well I'm just prototyping atm, but still better to learn things the right way not?

burnt vapor
#

Also, six files of code is not something anybody is going to debug

burnt vapor
#

I tell you to keep it simple and worry about optimization later.

teal viper
ivory bobcat
topaz mortar
#
    {

        Vector3 newPosition = transform.position;

        if (Input.GetKey("w") || Input.GetKey("z") || Input.GetKey(KeyCode.UpArrow) || Input.mousePosition.y >= Screen.height - panBorder)
        {
            //transform.Translate(Vector3.forward * panSpeed * Time.deltaTime, Space.World);
            newPosition += Vector3.forward * panSpeed * Time.deltaTime;
        }
        else if (Input.GetKey("s") || Input.GetKey(KeyCode.DownArrow) || Input.mousePosition.y <= panBorder)
        {
            //transform.Translate(Vector3.back * panSpeed * Time.deltaTime, Space.World);
            newPosition += Vector3.back * panSpeed * Time.deltaTime;
        }

        if (Input.GetKey("d") || Input.GetKey(KeyCode.RightArrow) || Input.mousePosition.x >= Screen.width - panBorder)
        {
            //transform.Translate(Vector3.right * panSpeed * Time.deltaTime, Space.World);
            newPosition += Vector3.right * panSpeed * Time.deltaTime;
        }
        else if (Input.GetKey("a") || Input.GetKey("q") || Input.GetKey(KeyCode.LeftArrow) || Input.mousePosition.x <= panBorder)
        {
            //transform.Translate(Vector3.left * panSpeed * Time.deltaTime, Space.World);
            newPosition += Vector3.left * panSpeed * Time.deltaTime;
        }

        if (Input.mouseScrollDelta.y != 0)
        {
            //transform.Translate(Vector3.down * Input.mouseScrollDelta.y * scrollSpeed * Time.deltaTime, Space.World);
            newPosition += Vector3.down * Input.mouseScrollDelta.y * scrollSpeed * Time.deltaTime;
        }

        newPosition.y = Mathf.Clamp(newPosition.y, 3, 15);
        newPosition.x = Mathf.Clamp(newPosition.x, 1, 18);
        newPosition.z = Mathf.Clamp(newPosition.z, -2, 7);

        transform.position = newPosition;
    }```
simple enough not? sure it took a few minutes, mostly just asking here, but at least now I understand what is happening 🙂
burnt vapor
languid spire
eternal falconBOT
burnt vapor
#

Like, you currently have a bunch of if statements that are long because you check for input

#

I'd put that separately

topaz mortar
#

what happened to keeping it simple? 😦

burnt vapor
#

Either by having the method return what to add to newPosition, or even by returning the Vector3/direction as an enum

burnt vapor
teal viper
burnt vapor
#

Sure, putting it all in your update method is simple, but this turns unreadable quick

willow scroll
topaz mortar
#

well I don't know how to do it so lol

burnt vapor
#

Considering there are two different logical steps in the code, you could separate the two

willow scroll
topaz mortar
#

this structure makes a lot of sense to me, not sure why it's not good

burnt vapor
#

I already explained

willow scroll
#

Because it looks bad

ivory bobcat
burnt vapor
#

Regardless, it should be clear that keys return a direction

willow scroll
#

You may create a list, which contains the keys

#

Well, it would be a readonly Dictionary<enum, List<KeyCode>>

topaz mortar
#

not sure if you're trolling me or not lol

willow scroll
#

Why would I?

#

Although, in your case, there is an additional condition, so Func<bool> is required

#

But, honestly, using the new input system is the best variant here

burnt vapor
#

I don't think I would put in a dictionary myself

#

The if-statements are long and complex

topaz mortar
#

lol I literally have no idea what you're talking about so I'm just gonna leave it like this

willow scroll
#

Well, do you know what a dictionary is in C#?

topaz mortar
#

yes

burnt vapor
#

I would just separate it from the newPosition and into a new method that returns the Vector3 direction

burnt vapor
#

So what's the issue?

#

You asked for improvements, I'm not sure how else I could explain

topaz mortar
#

I think it's overcomplicated and makes it less readable tbh

burnt vapor
#

Then I see no point in discussing it

topaz mortar
#

agree 🙂

burnt vapor
#

You'll see why this matters once your project grows, probably

#

I didn't understand how to keep things simple until I made a massive project

willow scroll
#

Yeah, just keep your code filthy 🙂

burnt vapor
#

This mostly only matters if your script grows into different parts which makes it unclear when the next thing happens. In your case it's two parts, which is still readable to an extend

steep rose
#

A ton of if statements is not preferable either way

topaz mortar
night valve
#

Dictionary :p

steep rose
#

Do exactly what sashok said lmao

topaz mortar
#

lol

#

at least now I know what sashok was saying 🤣

burnt vapor
#

A dictionary will just be unreadable in this case

#

Getting rid of the if-statements only make sense if they are not this complex

#

Alternatively use a switch statement

burnt vapor
#

This is the splitting I am talking about

#

Two different groups of input, and then other logic

topaz mortar
#

must be lagging from the complex if statements

burnt vapor
#

You got your priorities wrong if you still think a few if statements are going to lag your game

#

Especially the ones you shared

#

I don't see lag, I just see a camera that isn't smooth

willow scroll
#

This is how I would implement it. Make sure the names are changed, since they are bad.

private readonly Dictionary<Vector2, (List<KeyCode> keys, Func<bool> condition)> 
    _directionKeys = new() { ... };

private Vector2 GetDirection()
{
    Vector2 direction = default;

    for (int i = 0; i < _directionKeys.Count; i++)
    {
        var directionKey = _directionKeys[i];
        var directionValue = _directionKeys[i].value;
      
        if (directionValue.keys.Any(k => Input.GetKey(k)) || directionValue.condition)
        {
            direction += directionKey.key;
            
            if (i % 2 == 0)
                i++;
        }
    }
    return direction;
}
topaz mortar
topaz mortar
willow scroll
#

The line looks like it's moving because of how rough the camera movement is

topaz mortar
#

ok so this definitely does not do what I want it to do:
transform.position = Vector3.SmoothDamp(transform.position, newPosition, ref velocity, 0.1f);.

#

camera movement becomes extremely slow and zooming is jittery

burnt vapor
topaz mortar
#

and if I lower the 0.1f it's back to rough movement

summer hound
#

If i have, say a Cube, with a NavMeshAgent and a Rigidbody and SphereCollider, and i want the cube to move to a specific point, and "jump up on a chair", to sit on the chair, im using a "sittingPoint2 on the chair. But, when my cube comes to the chair and i call the change for my "sittingPoints" transform, the cube ain't lifting from the ground. How come?

private void RotateTowards(Transform workPoint)
{
    Rigidbody rb = GetComponent<Rigidbody>();

    if (rb != null)
    {
        Vector3 newPosition = new Vector3(workPoint.position.x, transform.position.y, workPoint.position.z);
        rb.MovePosition(newPosition);
    }

}

burnt vapor
#

Is it? You can use logging for example

#

Secondly, log the value of workPoint.position.z when rb.MovePosition is called and verify it changes

summer hound
#

Ooooh, so i have to make the change in the rb.MovePosition... Got it, ill try!

#

I mean, having it called 🙂

ivory bobcat
summer hound
#

Got it to work now @ivory bobcat and @burnt vapor , thanks!

wanton canyon
#

Hello, trying to find a tutorial on how to program a creature that is swimming in the water but everything coming up is about the player swimming. Can someone point me in the right direction for how to have, say, a shark patrol the waters?

hexed terrace
#

what you want to do is look for two separate tutorials.
1- swimming -> the player swimming tutorials will give you the swimming bit.
2- "shark" patrol -> find tutorials about general AI/ NPC patrolling

You are unlikely to find a tutorial about swimming sharks patrolling

wanton canyon
#

Yeah it doesn't have to be that specific, Im just confused on how to make the model "float" in the water while patrolling

burnt vapor
#

Perhaps it's just adjusting based on how close the camera is, idk

topaz mortar
#

I think it's a camera issue, it's breaking my hexes as well

#

I know there's a pixel perfect camera for 2d projects, but that won't work for 3d will it?

steep rose
#

whatever type is totally up to you

topaz mortar
#

I think I'll just switch to an orthographic camera, makes more sense for my game anyway

#

I tried SMAA but didn't help

steep rose
#

try TAA if unity has it

topaz mortar
steep rose
steep rose
#

i dont know what would be causing that

topaz mortar
topaz mortar
#

ah yeah it shows pretty clearly

#

ok, so I made my camera Size scrollable and now the jitter on the tiles is gone somehow 🤯
the red line is still flickering though

#

ok it seems to be only at certain camera positions, not everywhere

steep rose
#

if that solution works, i believe you are good

#

you can turn the quality setting up more or try FXAA (if needed)

timid ember
#

whats the error here?

#

In VSC, the error is shown as a red underline on ContextMenu

#

im currently learning enums

cosmic dagger
timid ember
#

please tell me

cosmic dagger
#

did you read the error message?

timid ember
#

yes but i cant understand it

cosmic dagger
timid ember
#

what does it mean by method delcaration

cosmic dagger
#

it is only valid on methods. did you place it on a method?

#

okay, do you know what a method is?

timid ember
#

no

cosmic dagger
#

well, that's a problem as it's a basic concept and very important . . .

#

you have a method in the image you posted. not sure how you don't know that . . .

timid ember
#

oh

#

public class isnt a method?

cosmic dagger
#

public class <InsertClassName> is a class, not a method . . .

#

i recommend following a beginner C# tutorial to learn the basics. these are concepts you really have to understand . . .

timid ember
#

does this hav anything to do with it?

cosmic dagger
# timid ember does this hav anything to do with it?

no. you placed [ContextMenu] above a type declaration—which is not allowed, hence, the error. i posted what and where the type declaration is. the error states it is only valid for method declarations (which i also posted what and where that is) . . .

timid ember
#

I am using contextmenu to show my enums

#

wait

cosmic dagger
timid ember
#

why does this work

cosmic dagger
cosmic dagger
cosmic dagger
eternal falconBOT
cosmic dagger
#

use formatting for small blocks of code or a paste/bin site for large chunks . . .

#

@timid ember

timid ember
#

yes i saw

#
// namespace yo
{
    public class the : MonoBehaviour
    {
        [SerializeField] GameState myCurrentGameState;
        [SerializeField] ammobullet ammotype;
        [ContextMenu("Show")]
        // Start is called before the first frame update
        private void ShowGameState()
        {
            Debug.Log($"state :- {(int)myCurrentGameState},{(int)ammotype}"); 
        }
        // Update is called once per frame
        public enum GameState
        {
            Loading, //0
            Gameplay, //1
            Gameover //2
        }
        public enum ammobullet
        {
            heavy,
            rifle,
            pistol,
            smg
        }
    }
}
cosmic dagger
#

those 3 marks at the beginning are backticks . . .

timid ember
#

ok

#

why does this work

cosmic dagger
#

specifically, which part? where do you expect an error?

timid ember
#

contextmenu

#

i am gonna watch a tut

cosmic dagger
# timid ember contextmenu

uhh, i'm not sure how else to explain it. as the error states, [ContextMenu] is only valid on method declarations. in this snippet, you correctly have it placed on top of a method declaration. That is why it works . . .

cobalt sentinel
#

Hello, have this code, And when the enemy gets hit, he sometimes get hit and sometimes he dont, does someone know why?

rich adder
#

also [SerializeField] is to expose private variables, public are already exposed

#

hence the 3 dots telling you so

cobalt sentinel
#

what can i do?

rich adder
cosmic dagger
cosmic dagger
cobalt sentinel
#

The sword (the yellow thing is the radius of the attack but its the same) is that, and when i click it activates and then disactivates

#

and the red thing is the enemy

#

@rich adder

rich adder
#

also Idk if OnTriggerEnter gets called when collider is already inside does it ?

cosmic dagger
#

@timid ember a method is a block of code containing a group of statements. they can only be defined in a type . . .

cosmic dagger
cobalt sentinel
#

so, if i stay still, it dont gets hit, but if i move it gets hit

rich adder
#

just use an overlap if you need to activate a hurt

cosmic dagger
# cobalt sentinel how can i do that?

if an attack was executed and the sword is still inside the collider, you can register that as a hit. you'd have to create the logic for this, though, it's much easier to use an OverlapXXX or CheckXXX method instead . . .

cobalt sentinel
#

wait

#

i did something more simple

#

i enabled and disabled the box collider

#

and it works

#

Thanks!

hollow wagon
#

@steep rose after a lil searching and understanding stuff I think I choose cc and also the learn.unity Which one. Should I choose

steep rose
#

also wdym which one should you choose?

pulsar meteor
#

why doesnt it show up

cosmic dagger
#

did you save? do you have errors in the console?

pulsar meteor
#

i saved and the only error is cauze i need the field for a object

cosmic dagger
#

what is Einteractcanvas? that variable is not in the pic . . .

hexed terrace
#

!vs

eternal falconBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

hexed terrace
#

☝️ get configured

cosmic dagger
rich adder
cosmic dagger
# pulsar meteor

there you go. PlayerInteract does not exist. do you have a type: class or struct called PlayerInteract?

rich adder
#

get your IDE configured , pretty sure this was mentioned to you yesterday also
#854851968446365696 before you get help , you need a configured IDE

pulsar meteor
cosmic dagger
steep rose
#

so it actually exists

hexed terrace
#

create it

pulsar meteor
#

how

polar acorn
rich adder
#

or just keep coming back each time you can't figure something out basic (don't)

pulsar meteor
#

i made it

#

along tima ago

cosmic dagger
eternal falconBOT
pulsar meteor
polar acorn
#

Post the script with the error as well

pulsar meteor
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerInteractUI : MonoBehaviour
{
[SerializeField] private GameObject EInteractObject;
[SerializeField] private PlayerInteract playerInteract;

private void Update()
{
    if (playerInteract.GetInteractbleObject() != null)
    {
        Show();
    }
    else
    {
        Hide();
    }
}

private void Show()
{
    EInteractGameObject.SetActive(true);
}

private void Hide()
{
    EInteractGameObject.SetActive(false);
}

}

steep rose
pulsar meteor
#

so i dont know how

steep rose
polar acorn
rich adder
#

mind boggling

polar acorn
#

I am aware

eternal falconBOT
short hazel
#

Follow these instructions at all times, no matter how much scripts you need to post here.

#

One link per script, to not disturb the line numbers

#

(they are useful in case you have errors)

finite dove
pulsar meteor
#

i am watching the tt from the beginning

rich adder
#

again.. you need a configured IDE this wouldn't have happened probably

#

as it would probably give you the correct one

finite dove
short hazel
#

If your code editor does not underline errors or does not suggest things as you type them, you indeed need to get it configured first.
Note that this step is required to get help here.
!ide

eternal falconBOT
rich adder
#

we can't help you if you dont show a configured IDE

#

@pulsar meteor even misspelled/capitalized wrong with a configured IDE it would auto correct to most likely correct one

pulsar meteor
#

i dowloade visual studio with unity it is configuratet

rich adder
#

mate its clearly not configured.

deft grail
#

you need to actually configure it

#

and based of the 1 screenshot you provided, it doesnt look configured

pulsar meteor
deft grail
#

thats not the only step to it

rich adder
# pulsar meteor

close vs , click regen project files button, open script by double click

#

then show what it looks like in vs

pulsar meteor
#

it needs to update

ruby python
#

Hi all,

Would anyone be able to take a quick look at my code and see if they can see where I'm going wrong and what is causing my wheels to do this please? Been staring at it a while and it' baffling the crap out me 😕

https://hastebin.com/share/owelidewud.csharp

steep rose
#

and local rotation

#

wait wait wait, why not just make them a child of the wheel colliders in scene view?

ruby python
# steep rose try using local position

I did, and it did the same thing. 😕

Really weird thing though is that it's putting the 'root' object (empty) of the wheels, which are the objects that I'm referencing in the code, in the correct positions/rotations, but it's offsetting the actual visual mesh (which is a child of the root object), which I don't reference anywhere.

And making them a child doesn't work because the collider moves independently of the GameObject it's attached to.

#

Just tried assigning the wheel meshed directly and that works fine. Something a bit screwy going on when the meshes are children of something else. 😕

hallow acorn
#

why does it give me a NullReferenceException? if (playerControls.Interacting.Interact.WasPressedThisFrame())

eternal falconBOT
ivory bobcat
#

Log and see which variable is throwing the nre

nocturne kayak
#

Quick question

#

How would i go about moving a parent through a child?

rich adder
cosmic dagger
#

through? in what sense?

rich adder
#

@nocturne kayak if you mean how parent moves the child transform , you can't

lofty sequoia
#

I'm doing a sprite swap Toggle (UI Element) and modifying the isOn on one of the Toggles, but the sprite swap doesn't change to display the right image unless I click on it

nocturne kayak
#

some people that have been putting up with my BS might have read what i'm trying to do, but basically, i want to use the blue and red axis as transform handles

cosmic dagger
rich adder
#

just make sure child has bigger mass when you do
ohh you're not trying to make them collide? this is a grab tool ?
You need to script it then.

cyan token
nocturne kayak
nocturne kayak
eternal needle
#

Oops someone else said that

nocturne kayak
#

Problem with that approach is

#

the movement constraint is tied to the handle

#

So how would i go about moving a parent based on a child's movement constraint?

#

Is the best way to just take how much the child has moved, subtract that movement to the child and apply it to the parent? or is there a better way?

eternal needle
lofty sequoia
nocturne kayak
#

So i achieved that movement through meta's components alone

rich adder
#

just reference the parent transform and move that lol

lofty sequoia
# rich adder wdym it works just fine

setting the isOn on the toggle via script does not update the Toggle's sprite when using a sprite swap. It only changes when pressing it (must be in the onpointer down that changes the graphic)

rich adder
lofty sequoia
#

UI.Toggle

rich adder
# lofty sequoia

ohh so you mean the checkmark doesn't come up when you do change value via code?

lofty sequoia
#

not the checkmark, but the sprite transition doesn't occur

rich adder
#

those are coming from EventSystem

lofty sequoia
#

ah and it looks like the eventsystem interacts with Selectable. Using Select() on the toggle does what I want

rich adder
#

oh nicee.yup was gonna send the docs link but wanted to link the new one

#

couldn't find it but forgot now its inside a package link lol

hollow wagon
hollow wagon
chilly vigil
#

how do i fix this error "PUN got region list. Going to ping minimum regions, based on this previous result summary: cae;52;asia,au,cae,eu,hk,in,jp,kr,ru,rue,sa,tr,uae,us,ussc,usw,za
UnityEngine.Debug:Log (object)
Photon.Pun.PhotonNetwork:OnOperation (ExitGames.Client.Photon.OperationResponse) (at Assets/Photon/PhotonUnityNetworking/Code/PhotonNetworkPart.cs:2487)
Photon.Realtime.LoadBalancingClient:OnOperationResponse (ExitGames.Client.Photon.OperationResponse) (at Assets/Photon/PhotonRealtime/Code/LoadBalancingClient.cs:3052)
ExitGames.Client.Photon.PeerBase:DeserializeMessageAndCallback (ExitGames.Client.Photon.StreamBuffer) (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PeerBase.cs:877)
ExitGames.Client.Photon.EnetPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/EnetPeer.cs:595)
ExitGames.Client.Photon.PhotonPeer:DispatchIncomingCommands () (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/PhotonPeer.cs:1778)
Photon.Pun.PhotonHandler:Dispatch () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:232)
Photon.Pun.PhotonHandler:FixedUpdate () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonHandler.cs:152)"

kindred marsh
#

When called through CollideMeleeHitbox() CheckCollisions() gives "Object reference is not set to an instance of an object" because the collisionManagement is null, even though it is defined in Start(). CheckCollisions() works perfectly in other situations. Summon melee hitbox is called through a timer that takes in an int and an Action as arguments.

eternal needle
eternal falconBOT
kindred marsh
#

Yes but it shouldn't be; I used this setup and the bottom log came from Start() and the top from CheckCollisions()

cold stag
#

I need a bullet to move in the direction a player is facing using a rigidbody. how do I make the new velocity vector face in the forward vector of the bullet?? Sorry, I'm rusty haha

cosmic dagger
eternal falconBOT
eternal needle
#

Read the bot message..

kindred marsh
#

Gosh I am dense

#

1 sec

eternal needle
autumn pine
#

How would I make a public variable assignable from only one subclass

kindred marsh
#

Cant send the text because I dont have discord nitro lol

cosmic dagger
steep rose
#

!code

eternal falconBOT
cosmic dagger
#

nitro is not required to send links . . .

kindred marsh
cold stag
frank flare
#

Why does it get stuck? The button I'm pressing is supposed to move the cube forward https://cdn.discordapp.com/attachments/497872424281440267/1286651434170843238/2024-09-20_14-32-44.mov?ex=66eeaf06&is=66ed5d86&hm=441034b1ea56e46ed65bd77eafebb4d5818971e9859437830c1c45d87c1617da&

public class KeyboardController : MonoBehaviour
{
    private Camera playerCamera;
    private Mouse mouse;

    void Start()
    {
        playerCamera = Camera.main;
        mouse = Mouse.current;
    }

    void FixedUpdate()
    {
        if (mouse.leftButton.isPressed)
        {
            Vector3 mousePosition = mouse.position.ReadValue();
            Ray ray = playerCamera.ScreenPointToRay(mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                if (hit.collider.TryGetComponent(out Keyboard keyboard))
                {
                    Debug.Log("u");
                    keyboard.DoSomethingInThisKeyboard();
                }
            }
        }
    }
}
public class Keyboard : MonoBehaviour
{
    [SerializeField] private UnityEvent theEventToDo;
    public void DoSomethingInThisKeyboard()
    {
        Debug.Log("y");
        theEventToDo.Invoke();
    }
}
public class OtherPlayer : MonoBehaviour
{
    private Rigidbody otherPlayer_rb;

    void Start()
    {
        otherPlayer_rb = GetComponent<Rigidbody>();
    }

    public void move(float speed)
    {
        otherPlayer_rb.AddRelativeForce(transform.forward * speed * 600f);
    }

    public void rotate(float speed)
    {
        otherPlayer_rb.AddRelativeTorque(-transform.up * speed * 600f);
    }
}
#

move is basically being called in FixedUpdate every frame when I'm pressing the button

kindred marsh
steep rose
frank flare
eternal needle
kindred marsh
steep rose
kindred marsh
#

But not in the top one which is sent by line 43

steep rose
#

i dont see move or rotate being called

#

show me where it is being called

kindred marsh
#

Regions let me collapse code and makes everything easier to read and work with

frank flare
eternal needle
kindred marsh
#

Yes but they dont stay collapsed when you reopen a file

#

Ohh right

#

So for some reason CheckCollisions() is called before Start()?

#

Even though the hitbox is Instantiated before the collisions are checked

steep rose
#

sorry for the late response I was building a flight stick

rich adder
frank flare
#

I think it's problem with that force thing

steep rose
rich adder
# frank flare yes

did you debug other movement
pretty sure this looks wrong
-transform.up is probably changing as you rotate

#

since its the local direction according to the transform

frank flare
steep rose
#

actually you are suppose to do that since you are already using local space

#

i totally forgot about that

#

and i even looked at documentation

frank flare
willow scroll
#

You have to use the Rigidbody.MoveRotatation method, which smoothly changes the direction, checking for any Colliders on the way

wintry quarry
frank flare
willow scroll
wintry quarry
frank flare
wintry quarry
#

Set the angularVelocity - or only add a force once

willow scroll
#

It does respect collisions.

willow scroll
frank flare
willow scroll
#

No, MoveRotation checks for collisions

#

If required, use transform.rotation to teleport the Rigidbody

night raptor
rich adder
#

isn't MoveRotation like Moveposition, it makes other RBs respect its physics movement but itself doesn't collide with anything properly like AddTorque ?

night raptor
rich adder
#

Moveposition doc says its mainly for Kinematics, but doesn't mention anything on MoveRotation page , the name makes me assume its similiar? not sure 😅

autumn pine
#

how can I disable a main class script and all subclass scripts in one call

#

all on same object

eternal needle
wintry quarry
#

That seems like a weird setup

#

wouldn't it only have one?

night raptor
#

Haven't tried whether they change when calling MovePosition/Rotation though

kindred marsh
rich adder
night raptor
rich adder
frank flare
#

what's the purpose of fixed update fixed delta time? isn't fixed update already fixed by itself?

autumn pine
#

like calling a method on a subclass just by doing main.method()

#

instead ends up with a missed reference

kindred marsh
#

Ok fixed my problem by moving everything from Start() to Awake() in the script

frank flare
#

public void move(float speed)
{
otherPlayer_rb.AddRelativeForce(Vector3.forward * speed * 100f);
}

public void rotate(float speed)
{
    // otherPlayer_rb.AddRelativeTorque(-Vector3.up * speed * 100f);
    Quaternion deltaRotation = Quaternion.Euler(new Vector3(0, -speed * 10f, 0) * Time.fixedDeltaTime);
    Debug.Log($"Adding rotation to an object: {deltaRotation}");
    otherPlayer_rb.MoveRotation(otherPlayer_rb.rotation * deltaRotation);
}
rich adder
#

MoveRotation will not care about mass or any of that acceleration, you would need to write your own (could potentially just use a animation curve / lerp)

night raptor
# rich adder OH I see yeah , I assume they are not overwritten in the next physics frame righ...

Just tried with a simple test script just to make sure my assumption was correct and indeed both .velocity and .eulerAngles do change when MovePosition and MoveRotation was called and only happens when the body is set to kinematic. Non-kinematic body just gets teleported and doesn't behave well at all with other bodies when moved or rotated with Move... methods (just tried and confirmed it happens with the rotation as well). Interestingly enough if I call the Move... methods only for a one frame (for a kinematic body), the velocity fields will not change immediately but can only be detected the next FixedUpdate and then the next FixedUpdate they will reset to all zeros

rich adder
#

I wonder if its the same on Box2D.. iirc that has velocity for kinematic? that always throws me off lol

night raptor
# rich adder I wonder if its the same on Box2D.. iirc that has velocity for kinematic? that a...

As far as I know, the 2D engine works pretty much the opposite and non kinematic bodies actually do work well together with the Move... methods. Don't know how it works with kinematic ones but the way I understand it, calling Move... on a non kinematic one will just change the velocity fields so the given position will be reached during the next physics step (assuming nothing is blocking the object)

rich adder
night raptor
frank flare
#

there's angularVelocity for AddRelativeTorue but is there a similar property for AddRelativeForce?

rich adder
#

it was renamed in 6 though to linearVelocity

wintry quarry
#

And what do you mean by "addressing all subclasses"?

signal trail
#

Hello, is adding an event to an animation in the animator the best way to assign hitboxes to a move?

I want to add hitboxes to specific frames and this has been the only solution I have found

cosmic dagger
autumn pine
autumn pine
steep rose
wintry quarry
#

Are you sure it's that error?

#

You should share the actual code and the exact error message you are seeing

steep rose
#

how much of a performance drop if any would using rigidbody bullets from 5 to 10 people or ai and the bullets are shooting at a rate of a quarter of a second compared to translated bullets of the same size of people and rate?

#

just wondering since i will have to implement a bullet system soon

rocky canyon
#

physics on 20 - 40 objects per second as opposed to physics on 0 objects per second?

#

is that what ur asking? lol

steep rose
#

technically yes 😅

#

well

#

i would still be translating the same amount of bullets at the same size of people and rate of fire

signal trail
steep rose
iron wind
#

rigidbody gonna be better, no need to reinvent the wheel

autumn pine
wintry quarry
#

Most likely it would be faster than using scripts to manually move the objects though

steep rose
leaden crow
#

Is this a bug? I'm running into a minor issue where scripts attached to a deactivated parent object are still being called, giving me some weird errors
I can bypass this by running a manual check that the parent is deactivated, but shouldn't Unity do that by default?

cosmic dagger
leaden crow
#

A function that shoots a bullet when the left mouse click is pressed

#

it was getting to this part and stopping since it couldnt access the prefab due to the object being disabled

cosmic dagger
#

you can manually call public methods from deactivated scripts. only certain unity update methods won't run . . .

leaden crow
#

I don't recall this bug happening before I updated to 2022 LTS though

cosmic dagger
#

did you debug to ensure it's being called? did the debug to ensure the script from the deactivated GameObject is calling a method?

leaden crow
#

The only major trouble it caused was reducing the bullets in the magazine of the reserve weapon but I can block access to it by manually checking if the parent is active

#

Ye

#

I put a Debug.Log that returned the name of the weapon the script was being called from

#

I could also tell the script was being accessed since ammo--; was being called in every left click

#

Even when the gun wasnt actually firing

wintry quarry
#

Look at the stack trace in your Debug.Log to see where it's being called from

#

Likely an input handler of some kind

cosmic dagger
wintry quarry
#

My guess is you are perhaps using the new input system and you subscribed to an input action via someAction.performed += SomeFunction;

#

and you never unsubscribed

leaden crow
#

Yes I am using the new input system

cosmic dagger
#

side note: you should format your code an can probably condense that if statement check . . .

leaden crow
#

But as I previously said it also didn't happen in previous versions I had the project on

#

And I was using the new input system aswell

cosmic dagger
#

are you subscribing to an event in Start?

leaden crow
#

yes

ivory bobcat
wintry quarry
#

Trust me - this has nothing to do with Unity versions

#

you are simply not unsubscribing your input listener appropriately

leaden crow
#

I get that
But then why did this bug not happen in 2019 LTS

#

I dont get that

wintry quarry
#

It either:

  • did and you didn't notice
  • You never disabled that object
  • you never pressed the button after doing it
  • your code didn't access anything destroyed or disabled before
ivory bobcat
leaden crow
#

Havent touched the code that handles the firing since I wrote it in 2019 LTS

wintry quarry
wintry quarry
#

you're not going to convince us with this anecdote

leaden crow
#

Perhaps

wintry quarry
#

because everything you're saying is pointing towards an obvious error in your code.

cosmic dagger
# leaden crow yes

please do not use Start to subscribe to events. you want to be able to subscribe and unsubscribe in—your—case you need to deactivate or stop a script or system from running. as Praetor mentioned, use OnEnable and OnDisable . . .

leaden crow
#

I'm switching to that as we speak

#

I didn't know those methods were a thing

steep rose
#

!code for whoever sent that

eternal falconBOT
ebon mist
#

Does anyone know how i can fix my combo script from constantly triggering Attack1

wintry quarry
ebon mist
#

Like when i spam click Attack1 Triggers over and over

#

I tried adding a timer but it did not help

wintry quarry
#

Ok that's not "constant" that's whenever you click

#

so what you are asking is how to add a cooldown

ebon mist
#

yes i guess so

#

but only for the 1st attack the other 2 are good

wintry quarry
#

Well first you should add some Debug.Log statements in here to see what's actually going on.

#

because as far as I can see - this comboStep variable and the correlated if statements should prevent Attack1 from triggering more than once

ebon mist
#

ok ill add some

#

Is there a specific spot i should put them?

wintry quarry
#

I would put them in each of those combo step if statements

ebon mist
#

ok

wintry quarry
#

inside PerformCombo

steep rose
#

quick question how would i be able to get the specific transform of a point in my array

    public Transform[] WPTransforms;

    [SerializeField] private int RandomPoint;

    private void Start()
    {
        RandomPoint = Random.Range(0, 4);
    }

    void Update()
    {
        WPTransforms[RandomPoint] = //something
    }
#

i am just now learning arrays

wintry quarry
#
Transform example = WPTransforms[RandomPoint];```
ebon mist
#

All the combo steps are in the log i think im just clicking so fast its resetting to Attack1 before the animation finishes

steep rose
#

oh, alright

cosmic dagger
steep rose
#

yeah im not the best at arrays as you see 😅

#

i put them off for a while

#

thank you though

wintry quarry
ebon mist
#

Yeah i want to keep exit time so the full attack plays

wintry quarry
#

you can do this with an animation event for example.

ebon mist
#

Thats the part i dont understand because i Have a animation event that sets canAttack to true but it dosent work

wintry quarry
#

because your code never sets it to false anywhere

ebon mist
#

ooooh ok you think i should set it to false untill the animation event triggers it back on?

wintry quarry
#

yes

ebon mist
#

Ok i shall try thank you so much

sour fulcrum
#

Honestly no clue where this question should go since I guess it's editor related but kinda not,

What's the vibe on running IEnumators without a monobehaviour?

#

I've seen some examples online on how you can kinda run through them yourself but my initial testing of them seemed to produce results that ignored yields?

eternal needle
sour fulcrum
#

Ah ok, probabably a good time for me to learn how they actually work 😄

#

For context im trying to do some webrequest/downloadhandler stuff for editor related things but was curious outside of that usecase aswell

steep rose
#

am i on the right track here to finding the transforms of the overlapsphere colliders?

    [SerializeField] private Collider[] overlapcolliders;

    Transform overlaptransforms;

    void Update()
    {
        overlapcolliders = Physics.OverlapSphere(transform.position, 50f, WPtransformmask);

        foreach (var hitCollider in overlapcolliders)
        {
            overlaptransforms = hitCollider.transform;
        }

        currentpointtransform = overlaptransforms[RandomPoint];

       distfrompoint = Vector3.Distance(currentpointtransform.position, transform.position);
    }
frosty hound
#

overlaptransforms is not an array or a list, so no, this won't work.

#

It should also be giving you an error.

steep rose
#

it is giving me an error, im currently trying to get it to work

#

would i make it an array then get the hitcollider array of transforms or just the transform

frosty hound
#

I don't know why you need to store all the transforms into another collection, you have them all in overlapcolliders

steep rose
#

i thought that gave me a list of colliders

#

oh, nevermind i think i figured it out

steep rose
#

arrays are tough, at least for me

upper forge
#

How do get a parent gameobject and find the child of that gameobject parent and then disable it ?

cosmic dagger
upper forge
#

i got it !

#

Is there anyways to set the transform of an animations that plays?
I have one playing on the main character but the position is way off

near wadi
#

again, !code

eternal falconBOT
cyan crag
swift elbow
# upper forge i got it !

Using find methods are very inefficient and slow. you should reference your gameobject in the editor instead by making a public variable and dragging in the reference

swift elbow
cyan crag
#

ok

swift elbow
#

try disabling domain reload in project settings, if its on

cyan crag
#

its off

near wadi
#

would the possibility of clearing Library help them at all, since they say they have restarted the editor several times to no avail

swift elbow
swift elbow
near wadi
#

ok, i leave it to you guys

cyan crag
swift elbow
#

what version are you using?

cyan crag
swift elbow
#

yeah this happens to me on a similar version

#

i dont think this will help, but you should try closing your project and deleting your library folder, like Hunanbean mentioned

cyan crag
#

where is the library folder im quite new to unity

#

found it

#

will this make me restart my project?

swift elbow
#

make sure you only delete that, and make sure your project is closed.

cyan crag
#

so i delete the library folder

swift elbow
#

after you delete it simply reopen your project and the files will regenerate on its own

swift elbow
cyan crag
#

i delete this

#

ok

#

ok so i reopen

#

hopefully this works

swift elbow
#

it'll take a few mins for the project to reopen