#archived-code-general

1 messages Β· Page 85 of 1

potent sleet
#

not sure how this related to the previous code πŸ˜…

pearl swallow
#

It's just if its within a certain range, it can shoot the player.

hexed pecan
#

Side note, use ForceMode.Impulse instead of multiplying with some crazy number like 100

potent sleet
#

what is inRangeFire how's it related to movement though

pearl swallow
#

It isn't I'm just posting more bits of code, I'm just throwing things that could possibly cause weird stuff in the moving code.

potent sleet
pearl swallow
#

They aren't, I did that.

#

I did the debug.log and made different ones to make sure it wouldn't trigger. It just constantly moves regardless of state.

#

Would ResetPath() possibly work to stop it?

pearl swallow
#
        if (distanceFromPlayer >= 35)
        {
            spiderMesh.SetDestination(spiderMesh.transform.position);
            inRangeFire = false;
            Debug.Log("working");
        }

        else if(distanceFromPlayer<35 && distanceFromPlayer >= 20)
        {
            spiderMesh.SetDestination(player.position);
            inRangeFire = false;
            Debug.Log("Called");
        }

        else if(distanceFromPlayer <20 && distanceFromPlayer >= 15)
        {
            spiderMesh.SetDestination(player.position);
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
            inRangeFire = true;
            Debug.Log("initiated");

        }

        else
        {
            spiderMesh.SetDestination(spiderMesh.transform.position);
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
            inRangeFire = true;
            Debug.Log("Last");
        }
vale karma
#

Because no one saw my message on the the other channel so I waited a bit and posted it here

pearl swallow
#

I'm 70/30 that there's a rule against doing that.

potent sleet
pearl swallow
#

"Working" when it is outside the 35 unit radius and "Last" when it is too close.

#

So effectively the spider needs to be stopped when x>=35 or... when x<15

potent sleet
pearl swallow
#

Correct.

#

Well

#

It doesn't move the player

#

It kind of just... zigzags a bit on the ground

potent sleet
#

a dirty fix but you can try set agent speed to 0 when in those if conditions

#

normally setting destination to itself works for me .

pearl swallow
#

Okay... could using ResetPath() also be an option for stopping it?

potent sleet
#

I never used it

vale karma
#

So when dose it not count as cross posting

knotty sun
pearl swallow
#

I'll try doing the speed thing.

#

Oh... I wonder if SetPath might work...

potent sleet
proud wedge
#

Hey ya'll can I ask a question

pearl swallow
#

That's why this is here.

proud wedge
#

Aha, cool

#

So I have a script that controls the rotation of a turret

#

and I'm trying to get the state of the rotation from the turret, but whenever I use Transform.Rotation, it throws an error saying its not defined for Transform

#

How do I get that rotation?

potent sleet
#

it's not captial R

proud wedge
#

ah

potent sleet
#

neither is Transform unless you're making a separate reference other than itself

proud wedge
#

Gotcha

#

So are lower cases typically only to refer to self?

potent sleet
#

any monobehavior has transform prop because it always belongs on a gameObject

#

every gameObject has transform and vice versa

pearl swallow
#

Figured it out.

#

Well, I did a really stupid way of it, at least I think.

south ferry
#

Hey all ... I am trying to remember what is the name of this pattern:
Example: if (_lastDeviceUsed.displayName is "Mouse" or "Keyboard" or "")
Does anyone know? πŸ™‚

pearl swallow
#

navmesh.isEnabled = true (or false).

potent sleet
pearl swallow
#

Stopping the one agent.

potent sleet
#

I know but still seems overkill

#

something else is wrong

#

you shouldn't have to do that

pearl swallow
#

I renable it afterward.

#

It works fine.

#
if (distanceFromPlayer >= 35)
        {
            spiderMesh.enabled =false;
            inRangeFire = false;
            Debug.Log("working");
        }

        else if(distanceFromPlayer<35 && distanceFromPlayer >= 20)
        {
            spiderMesh.enabled =true;
            spiderMesh.SetDestination(player.position);
            inRangeFire = false;
            Debug.Log("Called");
        }

        else if(distanceFromPlayer <20 && distanceFromPlayer >= 15)
        {
            spiderMesh.enabled = true;
            spiderMesh.SetDestination(player.position);
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
            inRangeFire = true;
            Debug.Log("initiated");

        }

        else
        {
            spiderMesh.enabled = false;
            transform.LookAt(new Vector3(player.position.x, transform.position.y, player.position.z));
            inRangeFire = true;
            Debug.Log("Last");
        }
potent sleet
#

Hey if it works, that's all it matters, But I would still look into why it had to be done

pearl swallow
#

I will.

potent sleet
#

did agent.Speed = 0 not work tho @pearl swallow

pearl swallow
#

No

#

It still moved.

potent sleet
#

yeah it's odd then something is overriding it

pearl swallow
#

Though I'm wondering if it may be because of the terrain not being flat?

#

But Navmesh isn't a collider.

dusty hare
#

Hey ... anyone know how to read vertex color in a C# script? I need to know the color of a specific vertex.

#

I already have a handle on the vert

#

as Vector3

potent sleet
pearl swallow
#

Most likely

#

Idk, half the time I use Unity something is getting haunted.

potent sleet
#

you can debug things like NavMeshAgent.destination

#

to check were they were actually going

#

also things like hasPath etc.

pearl swallow
#

I'll tweak it later. I'm just happy it functions.

limber fog
#

ok so I have this code

    {
        Window.SetActive(false);
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if (Opener == true && Window.active == false)
        {
            Debug.Log("frund");
            compinfo.HowManyScreensUp++;
            Window.SetActive(true);
            Window.SendMessage("Loading");
        }
        else if (Opener == false && Window.active == true)
        {
            compinfo.HowManyScreensUp--;
            Window.SetActive(false);
        }

    }
}```

i put it on an object and duplicated the object three times.
it works for the first two objects, and yet...
pearl swallow
#

Is it an array or something?

limber fog
#

err, i just put the script on each rawimage and pluged whatever game object i want opened into window in the inspector

pearl swallow
#

Is the last one a button or something?

limber fog
#

nope, all three of them are rawimages

pearl swallow
#

And the 3rd one is connected properly?

limber fog
#

yup, in fact can switch out the game object I have in window and the first and second one will still activate whatever is in the window varible but the third still doesn't

regal epoch
#

when running my game, it suddenly freezes and i have to force close unity. I debugged myself into knowing where it freezes. There is this function i call on button click. The first time i call it, everything is fine and it does what its supposed to do. The second time tho it freezes the whole thing. In the script there are a few debug points. when it freezes, it doesn't even print the first one. so im guessing something is going wrong when i call the method?

    {
        Debug.Log("0");
        objectsToHide.SetActive(false);
        objectsToHideButtons.SetActive(true);

        Debug.Log("1");
        do
        {
            int rndNameIndex = Random.Range(0, names.Length);
        } while (rndNameIndex == previousRandomName);
        previousRandomName = rndNameIndex;
        Debug.Log("2");

        textDisplayName.GetComponent<Text>().text = names[rndNameIndex];
        Debug.Log("3");
    }```
main token
#

Hi, I have an assortment of points on the XY plane, and I would like to be able to draw a web between the points. Does anyone have any idea how to do this properly?

#

currently my code looks like this:

private void OnDrawGizmos() {
            List<GameObject> drawn = new List<GameObject>();
            
            for (int i = 0; i < _points.Count; i++) {
                for (int j = i + 1; j < _points.Count && !drawn.Contains(_points[j]); ++j) {
                    
                    Gizmos.DrawLine(_points[j].transform.position, _points[i].transform.position) ;
                    drawn.Add(_points[j]);
                }
                
            }
            
        }```
heady iris
#

So you want to connect nearby points together?

#

sounds like you need to make a maximally connected planar graph

#

to use a bunch of big words

#

i.e. you have as many connections as possible, but no two connections cross

main token
#

sounds like its gonna take more time than I'm willing to spend rn lol

heady iris
#

It's non-trivial

#

It's easy if you have a graph library. I did find one of those for a game jam a few months ago

#

it wasn't the worst to set up

steady moat
main token
#

It's mostly to visualize an algorithm I wrote which uses Divide and Conquer to find the pair of points with the smallest distance between them. Ideally I would want something like this:

#

I only want them to connect to reasonably adjacent points

plush hedge
#

@main token For each node, do a raycast within a limited distance towards each other node.

heady iris
#

you could approximate this by adding colliders each time you link up two nodes πŸ€”

main token
#

wdym, like checking intersecting colliders?

heady iris
#

yeah, you'd shoot a raycast to see if the path is clear

#

it'd be an approximation of an algorithm to generate a planar graph

main token
#

how would that be done in practice? Like raycasting towards a certain object, then comparing the object hit to the target?

heady iris
#

something like that

#

it would be very funky

main token
#

hey if it works, it works

heady iris
#

In mathematics and computational geometry, a Delaunay triangulation (also known as a Delone triangulation) for a given set P of discrete points in a general position is a triangulation DT(P) such that no point in P is inside the circumcircle of any triangle in DT(P). Delaunay triangulations maximize the minimum of all the angles of the triangle...

#

relevant concept

#

I remember seeing someone post a library for this on the unity forums a few years ago

#

a Delaunay triangulation avoids thin triangles

plush hedge
#

I would just do a POV graph (each node raycasts towards each other node), keeping track of all connections for each node. Then discarding all but the shortest connections and drawing them. It's naive and inefficient, but super simple to implement.

#

(POV: points of visibility)

#

Actually you don't need to raycast even

solemn rune
#

small question: How do you deal with properties in a Editor / Inspector script? How would I trigger certain functions after manually changing a public variable in the inspector?

leaden ice
solemn rune
#

Thanks. OnValidate() runs everytime any public property changed? Would there then be a way of knowing what value changed? Trying to wrap my head around how to implement it; Im not used to making extensive editor scripts πŸ™‚

#

The NaughtyAttributes plugin seems more handy prob

solemn rune
#

Thanks @leaden ice always on poin!!

simple egret
#

Your code editor probably tells you that the variable inside the loop is unused, its name will have a faded color, compared to other variable names, as well as a suggestion to remove it

regal epoch
#

oh yea youre right. it doesnt say remove, but it is grayed out. Thanks

solemn rune
#

Question: I'm trying to make a custom editor where I can manipulate a (cubic) bezier curve

#

so far so good:

#

For the next step I'd like to add Nodes for P1 and P2 (the two tangents), so I can drag and drop them with the mouse.. Anybody any idea on how I'd go about that? Some terms to steer me in the right direction?

solemn rune
#

rotate the 3D handle so that it seems 2d, and draw it on the inspector rather then in the scene view?

wintry crescent
#

Hi, I'm working with configurable joints, and I'm trying to get the local position of an anchor through code. .targetPosition doesn't seem to do the trick, what can I use instead?

#

.anchor returns the local position unscaled and unrotated, it seems

solemn rune
#

How do I paste code here?

wintry crescent
#

!code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

solemn rune
#

Thanks

steady moat
#

Is it for a spline editor ?

solemn rune
#
[CustomEditor(typeof(T_Bezier2))]
public class T_Bezier : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        Rect rect = GUILayoutUtility.GetRect(10, 1000, 200, 200);
        T_Bezier2 bez = (T_Bezier2)target;

        GUI.BeginClip(rect);

        Vector3 positionHandlesPosition = Handles.PositionHandle(new Vector3(200,200,0), Quaternion.Euler(new Vector3(0,0,0)) );
        Handles.DrawAAPolyLine(Texture2D.whiteTexture, 5, bez.points); 

        GUI.EndClip();

    }
}
#

this gives me null errors when I try to create a position handle in the Inspector, anyone any idea?

steady moat
#

You are not suppose to use it in an inspector

#

But in the scene.

solemn rune
wintry crescent
#

try OnDrawGizmos maybe

#

OnDrawGizmosSelected maybe

steady moat
#

OnSceneGUI

solemn rune
#

yeah i need it in the inspector. Looking into OnDrawGizmos!

wintry crescent
steady moat
wintry crescent
#

sry

solemn rune
#

ahh okok. Yeah I need to be able to move nodes by dragging them with the mouse. I suspect I just draw tiny cubes in OnInspectorGUI, but I need to register the mouse clicks and movements

steady moat
solemn rune
#

So P1 and P2 are the tangents, I would like to drag them in the visualization part, rather then having to set the numbers

wintry crescent
solemn rune
#

and btw the bezier curve drawn there is done in OnInspectorGUI with Handles.DrawAAPolyLine, it's not just Windows' paint πŸ˜„

steady moat
#

What are you doing with your Bezier curve ?

solemn rune
steady moat
#

Like, what is your purpose.

solemn rune
steady moat
#

Since when you need bezier curve for that ?

solemn rune
#

well, lets say Simulation of a physics engine lol.. Its neither here nor there, im really just trying to fix a inspector script πŸ˜›

steady moat
#

Is there any reason why you would not use the scene view ?

#

Like what are you doing with it.

#

Is it interpolation ?

wintry crescent
#

@solemn rune why don't you just use AnimationCurve? It's a cool 2D bezier curve editor, built in

steady moat
#

Kinda what I was going to suggest.

#

If you use it for interpolation at least.

wintry crescent
#

But it'll be slow for a physics engine
use trigonometry if u can

solemn rune
#

can i use that as part of a custom editor script?

wintry crescent
#

why not?

#

just put an animationcurve in your script

#

and it's there

solemn rune
wintry crescent
#

no custom editor required, even

solemn rune
#

Ahh ok, yeah I need the tangent positions etc for my formulas, cant use keys

wintry crescent
heady iris
#

that just gives you the value at a specific point on the curve

#

iirc, animation curves store the tangents as slopes

wintry crescent
#

can't you calculate it though, from that

steady moat
#

You first need to have the curve

solemn rune
#

Yeah you prob could. But, I'm using quadratic and cubic beziers etc, already doing it in code etc

#

Plus, I like this part, learning about editor scripts and visualisation, it's a nice change of pace

steady moat
#

I still do not know why you are trying to make a bezier in the inspector. It is not really made for that.

solemn rune
#

Well, in essence, using bezier calculations is a more flexible way of Lerping or Slerping something

#

the bezier in the editor is just the visualization of the bezier calculations used

steady moat
#

If you do not want to manipulate the point

#

But bezier curve are never used for Lerping

#

There are way to complex for that.

solemn rune
#

I use the bezier formulas to interpolate stuff.. and so far so good, especially since I do the calculations myself in script.. All I need is 3 or 4 Vec2s

#

the math is not That complex

steady moat
#

It is not complex as the math, but as the performance.

solemn rune
#

but it would be really heavy if I did that multiple times per frame, and then having to look that up in an animation curve yeah

steady moat
#

And unrequired flexibility

heady iris
#

but it's very common to do transitions with cubic bezier curves in, say, web browsers

steady moat
#

It is like doing 3-4 lerp betwen 3-4 points

#

Pretty sure animator does not use bezier curve.

solemn rune
#

a simple quadratic bezier: position = (1.0f - t) * (1.0f - t) * p0 + 2.0f * (1.0f - t) * t * p1 + t * t * p2; It's not that heavy...

#

Granted I prob wouldnt use it in a shader or something, but in my use case it isnt impacting any performance at all. And, it gives me way more flexibility in interpolating

wintry crescent
#

How can I create a field, to which I will be able to attach either a rigidbody or a articulation body?
Both inherit from Component
I don't want anything else to be attachable

wintry crescent
potent sleet
#

it's not that much work really, you could just make a bool control which one can be inserted

#

hide the field depending on bool

wintry crescent
#

yea, but that's a whole other class
I guess I'll just make 2 fields, like the people who made the spring joints that I'm using did...
IDK why I was trying to be smart

potent sleet
#

eh it's more to do with if you can find a simpler way to a problem why not take it

swift falcon
#

can please anyone send me a video that has script for 2d health and attack i couldn't find any that actualy works ?

potent sleet
#

I seriously doubt there is one that doesn't work especially in tutorials on youtube

swift falcon
# potent sleet where did you look ?

no it just that it isn't what i want like if they show what i need there is no link to code and if there is a link to code it isn't what i want

heady iris
#

it's not going to be EXACTLY what you want

#

if it was, there would be no point in making a game, because it would already exist

swift falcon
heady iris
#

i seriously doubt that you're doing something so incredibly unique that all existing reference material is useless

#

health and damage is basically just making a number go up and down

potent sleet
icy gate
#

if we compare a value assign to a variable and instantiating an object, how many times more heavy is instantiating an object?

potent sleet
wintry crescent
#

when you do it a lot

#

Camera.main is another thing like that

icy gate
#

I see

#

I was making a pool manager and thought, that's a lot of code to grab an object and store it, I started wondering if it's starting to be more slower than instantiating an object

wintry crescent
#

depends how you grab it

#

singleton? basically free
GameObject.Find? probably better instantiate

#

but if you're running it once (or rarely), it doesn't matter anyway

#

unless you're doing it at least every frame you're good with whatever solution you come up with

wintry crescent
icy gate
#

yup, thanks I'm using singleton for the manager and not using slow methods like get components, or find, so yeah, it's decently optimized

wintry crescent
# icy gate yup, thanks I'm using singleton for the manager and not using slow methods like ...

singletons can be a bit much code, yes, but they are fast and very very cool
just remember that you should initialize it in Awake and call it in Start
and despite what documentation would lead you to believe, you can't actually initialize singletons in Awake, and call them from somewhere else in OnEnable, which, according to this
https://docs.unity3d.com/Manual/ExecutionOrder.html
should be possible.
In truth, OnEnable and Awake are called in order only on one object
Like
foreach (obj in objects)
{
obj.Awake();
obj.OnEnable();
}
or something like that
I'm saying it cuz it bit me in the ass once, and I didn't find the issue for a couple of hours...

fathom pewter
#

Hi there. Im trying to pause my game using a gamepad as our only way of controlling the game. Ive been trying to set time.timeScale = 0 to pause our game but i realize that this makes it impossible to use the pause menu. Is there a way to circumvent this?

icy gate
wintry crescent
# fathom pewter Hi there. Im trying to pause my game using a gamepad as our only way of controll...

This is an extremely annoying issue
what I did, is I had a PauseManager with a static bool isPaused, and all objects checked it
or all objects derived from PausableObject, registered themselves on the PauseManager, and PauseManager called Pause and Unpause on those objects
but that's a ton of effort
I think there is a way to keep UI going despite timescale being 0, but I don't remember how it went

#

I am not sure if there is a way to do it
I think there could be

#

I'm not sure if fixedTimeStep won't keep going, meaning FixedUpdate will keep getting called though

fathom pewter
#

hmm okay. i appreciate your help

wintry crescent
#

Does anyone know, why, if I do something like this

joint.connectedArticulationBody = default;

or

joint.connectedArticulationBody = null;

I get an error "A joint can't connect the body to itself." but when I do the same with joint.connectedBody, there is no error?
the articulation body does not turn to null when I check in the inspector after it was called

visual fractal
#

The way unity handles code is rather confusing. How do I get collisions to disable if I press a key?

heady iris
#

that's a very vague statement

#

"the way unity handles code"

#

so you want to make an object stop colliding with anything when you push a key

visual fractal
#

Yes.

visual fractal
heady iris
#

yes, errors are sometimes weird

heady iris
#

If you aren't using the new input system, then you'll just do something like this to get input

#
if (Input.GetKeyDown(KeyCode.F))
{
  // ...
}
visual fractal
#

OK... I'll try that.

heady iris
#

disabling colliders is like disabling any other behaviour: set the .enabled field of the behaviour to false

#

you can stick a list of colliders on a component with

#

public List<Collider> colliders;

#

and then iterate over all of them to turn them on and off

#
foreach (var collider in colliders)
  collider.enabled = false;
visual fractal
#

Ah. That's what I was struggling with. Thanks.

junior pollen
#

hello, i have a problem with my 2d rigidbody jumping, tried separating the input and physics into Update and Fixedupdate but my jump height is still determined by the player's velocity, what i need is consistent jumps whenever i try to double jump https://gdl.space/zabobeqofe.cs

visual fractal
#

Try using ForceMode. Then you can choose whether or not to use velocity, mass, air friction, ect.

junior pollen
#

i tried using addforce

#

tried both with impulse and force but it doesn't work for some reason

visual fractal
#

Are there no more options?

junior pollen
#

not sure

visual fractal
#

Which part of the code is this? I'm on the link you sent.

heady iris
#

or is the first jump the problem

junior pollen
#

yep

#

double jump depends on the player velocity

earnest gazelle
#

Is there any way to rename a word in all places, classes, properties, methods, etc.? jetbrains rider
For example StuffManager class, StuffType enum, _stuff field, stuff variable, DoStuff() method.
Replace Stuff/stuff with a new word

junior pollen
#

so the sooner you press the higher you go

heady iris
#

rb.velocity = new Vector3(rb.velocity.x, doublejumpForce - rb.velocity.y);

#

why doesn't this just set the y velocity?

junior pollen
#

?

#

i feel like this line was useless

heady iris
#

it sets your y velocity to doubleJumpForce minus your current y velocity

junior pollen
#

i tried to do something like rb.velocity -= rb.velocity.y

#

but ig that doesn't work?

heady iris
#

what do you want to do?

#

you can't just do random math

junior pollen
#

realised that

#

basically consistent double jumps

heady iris
#

then just set the y velocity

#

like you do for the single jump

visual fractal
#

Maybe try doubleJumpForce + rb.velocity.y.

heady iris
#

it would make the second jump make you move faster than you were

junior pollen
#

hm

visual fractal
#

Or just add the force of a single jump to your y velocity.

junior pollen
#

would that still work?

visual fractal
#

Convert the Jumpforce into a vector.

#

You can do that with C#, right?

junior pollen
#

ah like new Vector2(rb.velocity.x, jumpForce)

#

?

junior pollen
heady iris
#

rb.velocity = new Vector2(rb.velocity.x, jumpForce);

#

you already do this

#

just...do it again

junior pollen
#

that'll make both jumps equal

visual fractal
heady iris
#

rb.velocity = new Vector2(rb.velocity.x, jumpForce + rb.velocity.y);

junior pollen
#

why not just use doublejumpForce instead of jumpForce?

visual fractal
#

Try that.

#

It'll probably work.

junior pollen
#

like if i want the doubleJump to be consistent but different height value than the jumpForce

heady iris
#

sure

junior pollen
heady iris
#

use a different number

junior pollen
#

:/

#

double jump still the same

#

i feel like i need a way to completely reset the y velocity to 0 and then double jump

visual fractal
#

You could write the code like I did. It's not the right way of doing it, but its allows double jumps.

#

And triple, quadruple, and any other jumps that you might need.

junior pollen
#

hm

#

i'll try finding a fix, if that doesn't work then sure

visual fractal
#

And if you hold the jump button you continuously go upwards...

junior pollen
#

uhhhh

#

that is flying...

visual fractal
#

It's buggy, but it works.

junior pollen
#

well it can probably be fixed

visual fractal
junior pollen
#

ah nice

visual fractal
#

The referenced script (Unknown) on this Behaviour is missing!

#

What is this?

junior pollen
#

tried doing this in the double jump couroutine but it also didn't work :/
rb.velocity = new Vector2(rb.velocity.x, 0);
rb.velocity = new Vector2(rb.velocity.x, doublejumpForce);

junior pollen
junior pollen
#

yes where did you see/get that error

visual fractal
#

The debug log.

junior pollen
#

uhh

visual fractal
#

?

junior pollen
#

im confused, you talking about my code or yours?

visual fractal
#

Mine.

#

I accidentally replied to your message.

junior pollen
#

yep

visual fractal
#

Everything in my code is working, it's just displaying the warning.

junior pollen
#

you probably deleted a script that you had assigned on a prefab or something

#

basically nothing

junior pollen
visual fractal
#

Probably correct, but how do I stop it?

junior pollen
#

check the prefabs that you made to try and find a missing script on the script component

random oak
#

how would I count these squares on tilemap by a certain amount ? the white dots

visual fractal
junior pollen
#

wait

#

check your c# script

#

it should say public class (the c# script name)

#

or else the script won't work

#

the class definition of a script needs to be the same as it's name

wintry crescent
#

How can I easily do an OnComponentAdd and OnComponentRemove inside a component?
I want to set the layer of the object to something when a component is added, and changed to default when it is removed

hollow hound
#

How can I get the contact position for the collider (onTrigger)?

woeful furnace
hollow hound
leaden ice
#

Just an overlap

hollow hound
#

I think I can get bounds of two colliders and find an overlap myself, but is there a more efficient way?

somber nacelle
#

What is the purpose for this?

void basalt
#

Regardless of the purpose, this should give you exactly what you need

rugged storm
#

hay is this a good way to iterate through a list of targets to find which is the closest?

glossy basin
#

Hello there, has somebody used UniTask before? I am having some issues with it

rugged storm
glossy basin
#

My uni task state is always pending, so whenever a new task is added, it stays there

glossy basin
#

I have literally 0 knowledge on both task and UniTask, I just followed some guides, so any help would be appreciated πŸ˜„

#

here is the async function that waits for generating the chunks

#

and here is the function that generates the actual chunk

cosmic rain
#

I'd also be extra careful with calling async methods from update.

glossy basin
cosmic rain
#

And where is that called?

#

Or rather, why is your task waiting for it to finish?

glossy basin
cosmic rain
#

Wait. It's waiting while it is finished. Is that waht you want?

#

The task would only complete when this job is runing.

glossy basin
cosmic rain
#

Wait while implies that when the condition is true, you wait.

clever pier
#

do you guys know any thing about lag compensation?

glossy basin
clever pier
#

thanks

cosmic rain
glossy basin
#

the profiler shows me an INSANE amount of calls to the async

cosmic rain
#

Okay, well, you could make clear logic that would track if a task is currently running, and avoid starting a new one.

glossy basin
#

I guess this is also the reason I get some garbage from time to time

glossy basin
cosmic rain
distant venture
#

Question: In a script, I'm unable to reference one type of interface, and yet I'm able to reference another type of interface defined under the same conditions and namespace. Does anyone have any idea why?

cosmic rain
distant venture
cosmic rain
distant venture
glossy basin
cosmic rain
distant venture
glossy basin
cosmic rain
#

It will make it so much easier for everyone if you just shared the relevant code

distant venture
cosmic rain
#

And the script where you try to access it?

distant venture
#

`namespace Cleverous.VaultInventory
{
[RequireComponent(typeof(Collider))]
public class RuntimeItemProxy : NetworkBehaviour
{

...

    public virtual void TryPickup(IUseInventory requestor)
    {
        IUseInventory inventory = null;
        IInteractable interactable = null;

...`

#

I'm sorry, the script is quite long, so I've tried to abbreviate it.

dense stream
#

hi is there anyone here?

#

can i get some help with a code problem i have

cosmic rain
cosmic rain
dense stream
#

hi

#

@cosmic rain hi nice to meet u

cosmic rain
#

Also, I see that you're getting help in the other channel. Please don't cross post

dense stream
#

sorry duley noted thank u @cosmic rain

distant venture
cosmic rain
#

Also, if the error only happens in VS code and not in unity, there's probably something wrong with your code editor.

distant venture
#

OK, I appreciate the help, I'll look into that.

cosmic rain
#

Also it goes without saying, but your code files all need to be in the Assets folder of your project.

distant venture
distant venture
cosmic rain
distant venture
cosmic rain
#

Are you making use of assembly definitions in your project perhaps?

distant venture
# cosmic rain Are you making use of assembly definitions in your project perhaps?

https://www.youtube.com/watch?v=HYqOSkHI674
I'm watching this video, because I don't know what that is, lol.

Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP

In this video, you'll learn how to use Assembly Definitions to organize your code in Unity.

#Unity3D #UnityTutorial #GameDevelopment

πŸ‘¨πŸ’» Join our community: https://discord.gg/NjjQ3BU
❀️ Support the channel: https://www.patreon.com/infalliblecode

My Favorite Unity Assets πŸ’―β€΅...

β–Ά Play video
distant venture
#

@cosmic rain I appreciate your time and help so far. Thank you.

cosmic rain
distant venture
#

@cosmic rain The answer is yes.

cosmic rain
#

Well, then that's probably the problem.

distant venture
#

@cosmic rain As a workaround, I guess I'll try to move this function over to another script, or something like that. Thank you for your help, you saved me a lot of headache.

cosmic rain
distant venture
smoky pike
#

I have two vectors - v1 and v2 and need to find the angle theta relative to the x-axis. How would I go about doing so? I current am just doing atan(v2.y-v1.y/v2.x-v1.x), but the angle is computed incorrectly when I'm in any quadrant other than the first one.

void basalt
#

@smoky pikeatan2?

smoky pike
shell scarab
#

not being able to use the ?? operator on unity objects is a travesty

swift falcon
#

use ternary

shell scarab
#

yes ik. I'm just sad I have to do

get => _instance != null ? _instance : new();
```rather than
```cs
get => _instance ?? (_instance = new());
swift falcon
#
get => !_instance ? _instance : new ();
#

pretty much same length

smoky pike
# void basalt <@856213207819485204>atan2?

How would I integrate this with a Quaternion? I have the angle and am instantiating a line with that angle at a certain point: Quaternion.Euler(0f,0f,angle); but the angle of the lines seem to be instantiated in the 2nd quadrant

shell scarab
#

I find comparing game objects to bools gross

void basalt
shell scarab
#

there's nothing different than comparing to null as far as i know

swift falcon
#

the bool is just doing the != null behind the scenes:3

shell scarab
shell scarab
smoky pike
plucky karma
shell scarab
shell scarab
plucky karma
#

Don't use Monobehaviour objects?

shell scarab
#

also cool, I honestly didn't know you can do ??=

shell scarab
swift falcon
shell scarab
#

way easier access for peeps to modify the values of the singleton

shell scarab
plucky karma
swift falcon
#

I thought it does

plucky karma
#

??= only works if left hand is "true" null.

#

Not boolean value that unity overrode.

shell scarab
# swift falcon I thought it does

https://github.com/microsoft/Microsoft.Unity.Analyzers/blob/main/doc/USP0001.md

If you use the == operator to compare a UnityEngine.Object to null, it will return true if the UnityEngine.Object is destroyed, even if the object itself isn't actually null. The ?? operator cannot be overridden in this way, and therefore behaves inconsistently with the == operator, because it checks for null in a different way.

GitHub

Roslyn analyzers for Unity game developers. Contribute to microsoft/Microsoft.Unity.Analyzers development by creating an account on GitHub.

plucky karma
#

Plus, I think internally, you can't access the constructor? It's also marked private?

shell scarab
#

I've never had a problem doing new GameObject()

#

also I realize what I told you to do would do nothing, I was assuming you had the quaternion you wanted @smoky pike

#

you need help getting the quaternion, right?

shell scarab
#

and you're on a 2D plane, and want to make the object face that angle?

smoky pike
#

yep

shell scarab
#

did you get it working with atan2?

smoky pike
#

i got the angles which seem to be correct

shell scarab
#

try doing

transform.right = (Vector2)(Quaternion.Euler(0,0,angle) * Vector2.right)
#

off the top of my head I think that'll rotate the right vector to the correct angle

smoky pike
#

the transform for the instantiated gameobject correct?

smoky pike
shell scarab
#

This isn't really a coding question, but yayyy I have a null pointer to a gameobject, what do i do? I can't delete it. (the script error is because it's supposed to have a reference to that object)

void basalt
#

oh you mean it comes up when you press play

shell scarab
#

yes it does

#

it's not gonna fix a null pointer to this broken game object lol

void basalt
#

Pretty odd error. GameObjects on the backend are native C++ objects I'm pretty sure

#

are you using unsafe code?

shell scarab
#

nope!

void basalt
#

In the editor

#

the gameobject is greyed out

#

so that likely has something to do with it

shell scarab
#

parts of unity have c# pointers, so maybe it's not in the c++ part lol

dusk apex
#

https://stackoverflow.com/a/68557338

Probably the error is due to the fact that you are destroying some prefab that is not unpacked, so not destroyable by the runtime GameObject.Destroy that is to destroy a cloned copy from the scene.

visual fractal
#

'PlayerMotor' does not contain a definition for 'Move' and no accessible extension method 'Move' accepting a first argument of type 'PlayerMotor' could be found. Please help. I don't understand a majority of these error messages.

void basalt
#

nobody can help you without posting code either

visual fractal
#

Good point.

shell scarab
#

ok I fixed it.

#

I edited the scene file in notepad++ and found the broken gameObject (not that hard considering there's not many lol) and just deleted the text for it and now it's fine!

amber haven
#

When finding the distance between a client and an enemy, I run the command every frame to detect distance, all that is changing is the enemies and clients position by very small increments, yet I get random extreme outliers like this (see distance from target). Any ideas on how I can fix this. Btw both the client and host are run from the same pc so I don't think its a lag problem. Help with this would be greatly appreciated.

cosmic rain
amber haven
# cosmic rain For starters, looking at the code could be helpful
if(!IsHost){return;}

HostDistance = Vector3.Distance(NetworkManager.Singleton.ConnectedClients[0].PlayerObject.transform.position, Dalek.transform.position);
ClientDistance = Vector3.Distance(NetworkManager.Singleton.ConnectedClients[1].PlayerObject.transform.position, Dalek.transform.position);

if(HostDistance < ClientDistance)
{
    Target = NetworkManager.Singleton.ConnectedClients[0].PlayerObject;
    print("Distance from Target: " + HostDistance + "\n" + "Distance from Non-Target: " + ClientDistance + "\n" + "Target: " + "Host");
}
if(HostDistance > ClientDistance)
{
    Target = NetworkManager.Singleton.ConnectedClients[1].PlayerObject;
    print("Distance from Target: " + ClientDistance + "\n" + "Distance from Non-Target: " + HostDistance + "\n" + "Target: " + "Client");
}
```Run in update
cosmic rain
#

I'd check if Dalek, ConnectedClients[0] and ConnectedClients[1] always refer to the same objects.

amber haven
#

Yeah they are always referring to the same object

#

The only time they wouldnt be is if I was hosting the game via the build instead of through the editor.

cosmic rain
#

Are you sure? Maybe print their names along the debug log?

#

If they are, then something's moving them to weird positions for a frame

#

According to your logs.

amber haven
#

Yeah

amber haven
#

rn the naming system is just auto assigned, 0 is always the host and 1,2,3 etc are always clients.

orchid bane
#

Does Transform.InverseTransformVector only change the representation of the vector or the vector gets changed instead?

amber haven
# cosmic rain According to your logs.

Target: [Host] Name: 0
Distance from Target: 67.07581
Distance from Non-Target: 77.5272

Target: [Host] Name: 0
Distance from Target: 27.38524
Distance from Non-Target: 67.06821

Target: [Client] Name: 1
Distance from Target: 67.05099
Distance from Non-Target: 77.54034

Its still happening randomly, here is a new log that also shows names

amber haven
cosmic rain
#

No. The object's name

amber haven
#

Ah no, I am measuring the distance between the players and the dalek.

cosmic rain
#

Yes, that why I'm asking

#

Here's how you log needs to look like to provide good debug info:

Distance from player0 to Dalek0: 3637
Distance from player1 to Dalek0: 3648
amber haven
#

Okay I'll rewrite them in that format

amber haven
# cosmic rain Here's how you log needs to look like to provide good debug info: ``` Distance f...

Distance from player0(Host) to Dalek0: 8.965793
Distance from player1(Client) to Dalek0: 7.23741
Closest player is player1

Distance from player0(Host) to Dalek0: 8.914283
Distance from player1(Client) to Dalek0: 14.93916
Closest player is player0

Distance from player0(Host) to Dalek0: 9.003682
Distance from player1(Client) to Dalek0: 7.063987
Closest player is player1

Okay here is another extract from the logs using your formatting showing the randomly changing positions.

#

The dalek is a nav mesh agent so could it be that randomly tping it somewhere for a frame?

cosmic rain
#

Okay. So at least it's clear that it's player1 position that jumps.

amber haven
#

Yeah

#

I have noticed its only on the client

#

the client is run on a built version whereas the host is run through editor

#

thats the only difference I can think of

cosmic rain
#

Did you try logging the same stuff on the actual client?

#

Or is on the client?

#

Or the host?

amber haven
#

The host

#

I will also run it on the client if that helps

cosmic rain
#

Ok, and is it a host authoritative game?

#

Where is the player1 moved?

amber haven
#

No its player authoritative

amber haven
cosmic rain
#

Ok, so outputting same logs on the client could help.

amber haven
#

Its only in the logs

cosmic rain
#

1 frame could easily be missed by a human eye.

amber haven
#

true

#

if I record it at 60fps and have the application set to 60fps it should capture every frame right?

#

then run through in a video editing software frame by frame

cosmic rain
#

If you confirm via the log that the issue doesn't happen on the client, then it must be something about syncing positions between the client and the host.

amber haven
#

yeah

cosmic rain
amber haven
#

I could have the player send their position to the host via an rpc rather than by the dalek checking the players position through its object on host side?

cosmic rain
#

You're thinking about walk-arounds before you even understand the issue. That's not how debugging works.

amber haven
#

Okay

#

I'll set up the client side logger

amber haven
cosmic rain
#

What exactly throws that error?

amber haven
# cosmic rain What exactly throws that error?

I'm pretty sure its

HostDistance = Vector3.Distance(NetworkManager.Singleton.ConnectedClients[0].PlayerObject.transform.position, Dalek.transform.position);

ClientDistance = Vector3.Distance(NetworkManager.Singleton.ConnectedClients[1].PlayerObject.transform.position, Dalek.transform.position);

cosmic rain
amber haven
#

I have it so that when you press tab the player movement script is temporarily disabled

#

and you mouse is unlocked from the screen

#

The pause menu has no connection to the dalek code

#

so idk why this is happening

cosmic rain
#

Why would Dalek code matter at all? The issue was with the player position.

amber haven
#

I agree

cosmic rain
#

When you disable the movement controller, it either does something with the position itself or with what/how it syncs with the host.

#

That's what I can guess from the limited information available at least.

amber haven
#

I'll send the code

amber haven
# cosmic rain That's what I can guess from the limited information available at least.
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Tab))
        {
            if(MouseStatus == "Enabled")
            {
                Cursor.lockState = CursorLockMode.None;
                MouseStatus = "Disabled";
                GetComponent<InputManager>().enabled = false;
            }else if(MouseStatus == "Disabled" || MouseStatus == "GameOpenState" )
            {
                Cursor.lockState = CursorLockMode.Locked;
                MouseStatus = "Enabled";
                GetComponent<InputManager>().enabled = true;
            }
        }
    }
ashen yoke
#

you know how ref counting is done?

#

or any similar application

cosmic rain
ashen yoke
#

please replace string literals with consts

amber haven
# cosmic rain Ok, and what does the InputManager do?
    private PlayerInput playerInput;
    private PlayerInput.OnFootActions onFoot;

    private PlayerMotor motor;
    private PlayerLook look;

    void Awake()
    {
        playerInput = new PlayerInput();
        onFoot = playerInput.OnFoot;
        motor = GetComponent<PlayerMotor>();
        look = GetComponent<PlayerLook>();
        onFoot.Jump.performed += ctx => motor.Jump();
        onFoot.Crouch.performed += ctx => motor.Crouch();

        onFoot.Sprint.performed += ctx => motor.startSprint();
        onFoot.Sprint.canceled += ctx => motor.endSprint();
    }
    void FixedUpdate()
    {
        motor.ProcessMove(onFoot.Movement.ReadValue<Vector2>());
    }
    private void LateUpdate()
    {
        look.ProcessLook(onFoot.Look.ReadValue<Vector2>());
    }
    private void OnEnable()
    {
        onFoot.Enable();
    }
    private void OnDisable()
    {
        onFoot.Disable();
    }
cosmic rain
#

Yeah, an enum would be suitable there.

ashen yoke
#

or a counter

#

if its empty the thing is allowed to happen

#

every time some menu opens it either adds to counter or gets a "token" that it holds

#

other systems react to the stack being empty or having something, disabling themselves

#

solves a lot of issues like ui panel hirarchies, stacked input maps etc

cosmic rain
amber haven
cosmic rain
amber haven
#

I'll try disabling the input script instead of disabling the movement script itself

#

It'll do the same thing without halting calculations done by the movement system, which fixes another bug of how the player doesnt fall when in menu

orchid bane
#

I have a Vector3 in world space. And I have a Transform which I want to use for this Vector3 as world space meaning I want the vector to have the same rotation as the transform. How do I do it?

ashen yoke
#

you have a direction vector?

#

transform already comes with transform.forward which is z+ in world space direction

orchid bane
#

The vector isn't a Vector3.forward but another vector like (-10f, 5f, 3,4f)

ashen yoke
#

i never said Vector3.forward

orchid bane
#

Why did you mention transform.forward then

ashen yoke
#

those are completely different things

#

thats why i mentioned it

orchid bane
shell scarab
# orchid bane

so your picture doesn't match your original description:

I have a Vector3 in world space. And I have a Transform which I want to use for this Vector3 as world space meaning I want the vector to have the same rotation as the transform. How do I do it?
That vector doesn't have the same rotation as the transform nor is it the same vector but in local space. But perhaps Transform.InverseTransformDirection will help you? https://docs.unity3d.com/ScriptReference/Transform.InverseTransformDirection.html
Transforms a direction from world space to local space.

hollow hound
void basalt
hollow hound
shell scarab
hollow hound
shell scarab
hollow hound
shell scarab
#

with the OnCollision method you can use collision.contacts

ashen yoke
#

by which you offset the object so they dont overlap anymore

shell scarab
ashen yoke
#

what should the green point represent?

hollow hound
ashen yoke
#

is the trigger axis aligned?

#

can do something like it

shell scarab
shell scarab
#

you gave bounds and they might not think there's an equivalent for a collider, which includes rotation.

#

wait @hollow hound is this 2D?

hollow hound
hollow hound
hollow hound
shell scarab
hollow hound
hollow hound
leaden ice
#

Like are you:

  • trying to draw something
  • trying to calculate volume of overlapping area?
  • trying to spawn something at contact points?
#

Etc

ashen yoke
#

i dont know if you can hit trigger, you should right?

hollow hound
# leaden ice What's the use case for this?

Find a point of the hit of the hitbox to spawn there another entity.
General question would be: How to find point that is on the surface of area of the overlapping / of two colliders and nearest to the another given point. Preferably without iterating through points in the collider.

leaden ice
#

That will get you "contact points"

hollow hound
ashen yoke
#

if all fails my sleep deprived mind just came up with an idea to keep parallel physics world with kinematic/non kinematic colliders mirroring objects and triggers to get collision points

hollow hound
ashen yoke
#

or alternatively turn trigger into kinematic and write your own trigger

hollow hound
#

So will try to formulate my question one more time in case it was too abstract.
I want to find a point (green) on the surface (blue) of the area (yellow) of the two overlapping trigger colliders (grey), that is nearest to the another given point (red).
Preferably without iterating through points in the collider. There are can be some movement, but it's not always the case (so I can't rely on previous position and need to work with static colliders). The shape of the colliders can be more complex than boxes and circles. All this in 2d.

hollow hound
leaden ice
#

See what happens if you use Vector2.zero as the cast direction

void remnant
#

hello! is it possible to make a shader that does the effect shown in my scuffed image? Basically, you add the material to the mesh and it generates a water effect above it: waves on a set height and underwater effect in between the ocean floor and water waves level (less light, everything is blue etc).

swift falcon
thin aurora
swift falcon
#

hmm

#

you want the player inspector?

thin aurora
#

A video, specific instructions on how the code works, or stuff like that

#

Try loggin the values you use and see what goes wrong

swift falcon
#

this is the inspector

swift falcon
#

it stays the same

#

I'll record a video

#

hold on

leaden ice
#

What debugging steps have you taken so far?
What does "just floats randomly" actually mean?

Also looks like networking is involved which complicates things a lot

swift falcon
#

at first when I create a world everything is fine and I can jump and stuff

#

I fall down onto the ground slowly

#

what's confusing is

#

everything is only fine

#

when the caves are still generating

#

when they stop

#

I start to float

leaden ice
#

What debugging steps have you taken

swift falcon
#

but ik it has nothing to do with caves

swift falcon
#

nothing happened

wooden jewel
#

I have this block of code that reads asset from a folder. It works fine in Unity Editor, but in standalone build, it cannot find the folder. How can I fix this ?

leaden ice
#

You should start adding log statements and questioning your assumptions about the code

leaden ice
wooden jewel
wooden jewel
fallen epoch
#

I have a couple of problems currently.

  1. I have a shader that (should) apply bloom and can apply a dissolve effect. The bloom isn't showing, I have a PP volume with bloom active so I don't know why it isn't working.

  2. I don't know how to go about making that dissolve effect happen while keeping the rest of the game paused. I've looked a bit into changing the time scale to 0 and coroutine looping a lerp for it but I can't quite get the logic working out so it doesn't stop entirely or runs the entire lerp during a single frame.

Help please ❀️

fallen epoch
#

Yeah, I found WaitForSecondsRealtime but couldn't mentally figure out how to use it for what I want πŸ˜…
Being sick doesn't help my brain function though, and thanks for the shaders channel reminder!!

sleek bough
sleek bough
fallen epoch
#

I'll fiddle with it and come back if I'm somehow working myself into a mental dead end. Helps to have some code to reference too πŸ˜…

ember ore
#

How do you usually avoid that something spawns inside another Object?
Or for example that something is perfectly placed?

E.g. Imagine you highlight some part of a Gameobject or whatever. You want to spawn in an Arrow pointing on that highlighted part.
So how do you programatically place that arrow that it does not spawn in the gameobject itself? This is more theoretically...
In the attached image it should spawn perfectly in the space outside the gameobject itself.

Are there some algorithms for this? How would you do that?

hollow hound
quartz folio
#

I see that was recommended to you... in that case the docs say what it returns

#

Additionally, this will also detect other Collider(s) at the collider start position if they are overlapping. In this case the cast shape will be starting inside the Collider and may not intersect the Collider surface. This means that the collision normal cannot be calculated in which case the collision normal returned is set to the inverse of the direction vector being tested.

fallen epoch
#

Vector2.zero is (0,0), points nowhere and provides no direction - makes sense you would get nothing from trying it. I'd expect some warning or debug log though

hollow hound
hollow hound
#

So there no mechanism to get the overlapping area and working with it (find a point inside it, for example)?

heady iris
#

I'm having trouble understanding what you want.

#

do you want to get a position that's in the overlap between the rectangle and the line?

hollow hound
#

I want to find a point (green) on the surface (blue) of the area (yellow) of the two overlapping trigger colliders (grey), that is nearest to the another given point (red).
Preferably without iterating through points in the collider. The shape of the colliders can be more complex than boxes and circles. All this in 2d.

heady iris
#

hmmmm, that could get tricky fast

#

..which is basically collision detection itself!

#

I wonder if you could use non-triggers. You get a set of contact points.

#

not sure how usable that data would be

plain coyote
#

I am using 2022 unity, is there a place where I know which version of dotnet unity supports?

heady iris
#

tbh, the most obvious solution to me is to do a batch of raycasts

hollow hound
plain coyote
heady iris
#

yeah

#

so:

  • intersect two colliders
  • find the closest point
#

here's one thought

#

the green dot will be located at one of two places

hollow hound
heady iris
#

it could be on one of the corners of the intersection area

#

or it could be the closest point to the original collider

#

but I don't see any obvious way to get those corners from triggers overlapping

heady iris
#

i feel like i'm back in my 4000-level algorithms class, haha

#

will this be on the exam

mental rover
#

this is the type of thing that's extremely tricky to do in the analytically correct & general case - if you can make any assumptions or approximations anywhere it will help a lot

heady iris
#

yeah

mental rover
#

but if you want to do what you're describing, it's almost certainly going to mean iterating over collider points in some way - either to check, or to construct a new one from the intersection

cosmic rain
#

I'd generate a density field(or whatever it's called) for each shape, intersect them and then do some vector math.πŸ€”

plain coyote
# hollow hound Ideally to the surface of the overlapped area because red point can be inside of...

well yeah, this is a common case, it can be easy or tricky depending on the shape.

Not sure if the unity standard colliders provide help or more complexity here

but basically , an Idea is to find the edges of intersection
I guess (not a proof but my mind is kinda telling me this could be correct)
one of the two vertices that define the edge is the closest point.
(this will fail if the point is within the radius of the circle that bounds the overlapped edge)

so your time required is 2 * number of edges * time_required_to_constructed an overlapped edge to find the point.

heady iris
#

What's the gameplay goal here?

plain coyote
quartz folio
#

No

plain coyote
#

πŸ™ƒ there must be a workaround or something no?

hollow hound
hollow hound
vagrant blade
#

Find the nearest vertice, and determine the nearest adjacent. Then use math to find the intersection point between two lines

late lion
#

Since we're talking about geometry math...
I have a capsule (in 3D) that is intersecting with an infinite plane. How can I calculate the area of the intersection, as an axis aligned quad? Here's what it would look like, taken from the side and from the top. The red rectangle is what I want to calculate. The orange egg looking thing is the actual intersection shape, that I don't care about. I just need the bounding box around it.

I would also be satisfied with just the 2D version as a starting point. That would be the red line in the first picture.

heady iris
#

annoyingly, you can't get collision events between two kinematic rigidbody colliders

swift falcon
#

what could possibly be causing this jerking movement on the camera? if it's static or attached to the player directly everything works just fine

public class CameraController : MonoBehaviour
{
    public Camera mainCamera;
    public float lerpSpeed;

    private Vector3 position = new Vector3();

    void Update()
    {
        position.x = Mathf.Lerp(mainCamera.transform.position.x, transform.position.x, lerpSpeed);
        position.y = Mathf.Lerp(mainCamera.transform.position.y, transform.position.y, lerpSpeed);
        position.z = mainCamera.transform.position.z;
        mainCamera.transform.position = position;
    }
}
heady iris
swift falcon
#

neither the player nor the camera have this snapping

#

hmm

hollow hound
heady iris
#

is the player a rigidbody? if so, try putting Interpolate on

swift falcon
#

yeah I'm moving player in fixedupdate

#

thanks

#

that fixed it

heady iris
#

Interpolate does wind up making the object appear one frame behind where it should be, iirc

swift falcon
#

should've probably looked into the docs more

swift falcon
#

yeah I know what it does

heady iris
#

oh yeah, this actually explicitly talks about camera problems :p

#

also, cinemachine tends to Do The Right Thing

swift falcon
#

it just forcefully recalculated the graphic on every fixedupdate iirc

#

well, the graphic's position

plain coyote
hollow hound
#

And even if only "affected" by collision lines would be checked, the nearest point on this line can be outside overlapping area : (

#

Oh, your proposal about grouping can solve this

plain coyote
hollow hound
regal epoch
#

i have this txt file i want to use for my game. I want to import it into an array to be able to read every line individually. how would i do this. I had something working but found out this wasn't going to work on phones. right now i have
var txtFile = Resources.Load<TextAsset>("textfile");
this does read the file, but is not making it an array. how would i turn this into an array

regal epoch
fallen epoch
#

Hmmm... still struggling to get the game paused while I'm running a coroutine for some shader lerping.

Currently, I've got the coroutine which loops until the elapsed time is past my animation duration (the actual lerping only works because I'm yield returning some fraction of a real second at the end of every loop). I'm trying to "pause" the game by just making it run in a while loop for the same duration in real time (using unscaledDeltaTime).
I even tried setting a variable at the start of my coroutine and after the internal loop to try to handle "coroutine is currently running" but when I made a while loop based on that, it made an infinite loop. Frustrating.

#

Just found something that might help.
Storing the coroutine function as an IEnumerator and checking if .MoveNext() is true - if so it is running?

#

Nope, doesn't work so good for me :\

placid mantle
#

Why would I need to create an instance of a scriptable object, if scriptable objects aren't living things in the hierarchy?

#

Is that like instantiating a prefab?

hexed pecan
#

It just depends on how you use your SO

#

Might not need it

hollow hound
#

Seems like this kind of problems more suitable for math.exchange, not for unity code-general. 😁

placid mantle
#

Ok thanks. I was watching a Unity video about them and saw the function and wondered why it would be used, I'll leave it for now. Thanks

mental rover
#

if you can say that the overlapping colliders will always be two rectangles it's immediately easier to solve

strange jacinth
#

Hey, can i get somehow list of collisions with points and normals from rigidbody? I tried using OnCollision events but I'm getting only last ContactPoint that it made.

placid mantle
#

I don't think I'm going to do anything super fancy with them. I've been exploring how to use them passing data across between scenes using delegates too.

#

I'm struggling a bit now because I dont want to use a singleton as I've heard they're not best practice but I can't seem to get my static class to subscribe to the delegates since they have no Awake or OnEnable function

#

How do you get static classes subscribed to delegates and events?

latent latch
#

singletons are fine

#

not likely to dig yourself a hole with them, unless you're using them across, say different characters. But for creating single type systems of management, such as object pools, they are fine.

heady iris
#

i don't like the phrase "not best practice"

#

it implies there is a Right Thing to do, and that everything else is a Wrong Thing

placid mantle
#

I need it to manage character data between scenes, and that data may change so will have a few functions on it too.

placid mantle
#

As you can probably tell I'm very new to it all

hollow hound
heady iris
#

Singletons can be a headache if you realize they're not so single after all

#

for example: in one game of mine (a ripoff of Alien: Isolation, more or less), I started with the assumption that there would be one enemy

#

and one player, too

#

so I had lots of code that just reference the single static monster and the single static player

#

then I realized that I want to have multiple players (mostly controlled by AI; it's not actually a multiplayer game)

#

so I had to rewrite a fair bit

#

now I'm thinking I want to have multiple enemies, too, and that's gonna be...a fair bit of rewriting

#

Although, that's not exactly the problem I was originally envisioning: that's a change from "one" to "many"

#

that's always going to be a some work

#

The big problem I can foresee with singletons is realizing that some actors need to refer to one thing, whilst others need to refer to another

#

you need to go from "they just read the singleton" to "someone hands them a reference"

mental rover
subtle herald
mental rover
placid mantle
#

Thanks @heady iris . Makes sense, for things that could grow I should look at alternative systems. But for something simple like a game-manager like I'm trying to create, its fine?

subtle herald
#

Again, not necessarily a wrong thing entirely though. But think what ya want. Time for work.

heady iris
#

Something with the "game manager" role makes sense as a singleton

#

there is a single manager for the game

heady iris
#

some people get very dogmatic about this stuff

#

probably after overdosing on Clean Code

hollow hound
placid mantle
#

Thanks for the input guys. I'm gonna crack on and use a singleton, but I've learnt a bit more about static classes and scriptable objects in the process so thats a plus too.

subtle herald
mental rover
plain coyote
#

if this is what you are looking for, then I am not sure if you unity does provide such support for those things, but in general you can google convex (hopefully your shapes are not concave) polygon clipping algorithm, they are a bit tough if you have not implemented one before.
Sad to say I don't think there is a simple way to do it, unless unity has an out of the box support using its built-in colliders (I think it is doable because the colliders are fixed in shape).

hollow hound
hollow hound
lone cape
#

Hey, i created game, there is login where you put key and login to get access but question is can anyone read memory and hack it that we will pass that screen and play ?

#

And how i can project game

potent sleet
lone cape
#

I mean this screen sends req to my server and checks

#

But idk if they can just disable that screen and go on

hexed pecan
potent sleet
#

you need to make a validation

heady iris
#

that's the part I don't like

#

it's vague Badness

gray mural
#

hey guys, how to reset all rigidbody factors in script?

I reset player's position and rotation when the game is over (when enemy hits player). Then I change timeScale for a while and player is still moving, because of the previous Ridigbody.AddForce

heady iris
#

You can also set the velocity to zero.

gray mural
heady iris
#

That’s the problem, isn’t it? :p

#

AddForce doesn’t β€œstick around”

gray mural
hexed pecan
#

Might wanna reset angularVelocity too

hot torrent
#

If i have multiple triggers on a gameobject and one of the attached script calls OnTriggerStay() wich of the colliders does it pick to check for collision?

heady iris
#

I don't believe you can check which one it was.

trim schooner
#

If they're on the same GameObject or a child.. all of them

heady iris
#

If you have two different kinds of colliders, you should put them on two separate objects, and have scripts on each one to handle those colliders

dull yarrow
#

Is possible to create a scriptable object with another script in it?
For example i am creating a scriptable object called item with itemType, itemImage, etc
And i want that object to have another script in it, for exemple itemStats, with another set of variables

hot torrent
hot torrent
astral edge
#

is it possible to create a script that automatically resizes imported imaages of a specific extension, they are auto resized? Would this work?

`using UnityEngine;
using UnityEditor;

public class ImageResizer : AssetPostprocessor {

void OnPostprocessTexture(Texture2D texture) {
    // Check if the imported asset is a texture
    if (assetPath.EndsWith(".png") || assetPath.EndsWith(".jpg") || assetPath.EndsWith(".jpeg")) {
        // Resize the texture to 1024x1024 pixels
        TextureScale.Bilinear(texture, 1024, 1024);
        // Save the resized texture to a new file
        byte[] bytes = texture.EncodeToPNG();
        File.WriteAllBytes(assetPath, bytes);
        AssetDatabase.ImportAsset(assetPath);
    }
}

}`

#

Hmm I'm not super savvy with coding

heady iris
astral edge
#

Yeah, I'd like to set that so they all import at 1024 by default, and I can adjust some accordingly.

trim schooner
hot torrent
trim schooner
#

of course

hot torrent
#

hm

dull yarrow
hot torrent
#

how do i decide wich of the colliders gets used for that?

hot torrent
trim schooner
hot torrent
#

i imagine it like this!

#

this is inside the scriptable object's code

heady iris
#

if you have a serializable type called Foo, you can make a field of type Foo

#
public class Bar : ScriptableObject {
  public Foo foo;
}
#

you can assign an instance of Foo to that field

#

if Foo is also a ScriptableObject, then you can create an asset that holds a Foo and assign it to the field on a Bar

hot torrent
heady iris
#

also, if you have a Rigidbody on a parent object, it will receive collision events for its child colliders

hot torrent
#

isn`t a rigidbody necesary if i want trigger collision checks?

trim schooner
#

only on one of the colliding objects

hot torrent
#

so i don't have to put it on the trigger object?

trim schooner
#

If the object(s) you expect to hit the trigger has a rigidbody.. then no, the trigger doesn't need it

hot torrent
#

but the object that is the trigger is actively moving...

trim schooner
#

There could be a case where the objects hitting the trigger don't have rigidbodies, so you would put the rigidbody on the trigger

#

sigh

Only ONE of the colliding objects REQUIRES a rigidbody for the collisions to work, more than one rigidbody is fine, in the cases that they're required

hot torrent
#

i get that!

#

ok i think i have an idea for a solution brb

gray mural
#

is the any way to do lambda "equals" in C#?
like that:

int num = (condition) ? 1 : 2; // that's default one

int num = 
{
  if (condition) return 1;
  return 2;
};
leaden ice
#

Do you mean a switch expression?

solemn rune
#

Hya. I'm trying to drag and drop drawn rects in the inspector (custom editor script). I have a (background) rect (rect0) made with GUILayoutUtility, and used with GUI.BeginClip, within which all the dragging action should take place. Then I draw a tiny rect with EditorGUI.Drawrect (rect1). I am able to detect clicks in rect0 ( with if rect0.Contains(currentmousePosition), but I cant use the same on my tiny, draggable rect1. if (rect1.Contains(current.mousePosition) never fires.. Anyone any idea?

solemn rune
#
public override void OnInspectorGUI()
{
    DrawDefaultInspector();

    Rect rect = GUILayoutUtility.GetRect(0, 1000, 200, 200);

    GUI.BeginClip(rect);

    Rect rectP1 = new Rect(bez.p1.x, bez.p1.y, 10, 10);


    EditorGUI.DrawRect(rectP1, Color.red);


    GUI.EndClip();

   
    Event current = Event.current;
    bool wasMouseDown = false;

    if (rect.Contains(current.mousePosition))
    {
        if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
        {
            Debug.Log("Left-Mouse Down");

            if (rectP1GUI.Contains(current.mousePosition))
            {
                Debug.Log("clicked in rectangle 1");
            }
    }

}
gray mural
leaden ice
#

why are you saying it's non-lambda

gray mural
leaden ice
#

instead of a lmabda expression?

gray mural
leaden ice
#
Func<bool> myDel = () => true;```
gray mural
#

we can do this:

bla = (bla % 2 == 0) ? bla : bla + 1;
#

but cannot do this:

bla =
{
  if (bla % 2 == 0) return bla;
  return bla + 1;
};
leaden ice
#
Func<int> myLambda = n => n % 2 == 0 ? n : n + 1;
var result = nums.Select(myLambda);```
gray mural
leaden ice
#

there is no additional function

#

Func<int> is just a delegate type

#
Func<int, int> myLambda = n => {
    return n % 2 == 0 ? n : n + 1;
};```
Here it is again without compile errors
#

Func<int, int> means "a function that accepts an int parameter and returns an int"

gray mural
leaden ice
#

No I think it's totally possible

heady iris
#

I still have no idea what you're asking about

leaden ice
#

aand I've showed you how to do it

#

and you don't like it

#

🀣

heady iris
#

you can literally just Do It

gray mural
leaden ice
#

Maybe you don't like the word "Func"

#

We can do it without the word Func

#
public delegate int MyCustomDelegate(int param);

void Example() {
  MyCustomDelegate ex = n => {
    return n % 2 == 0 ? n : n + 1;
  };
  var results = myArray.Select(ex);
}```
heady iris
#

you can't write it that way, because that's not how the C# syntax works

heady iris
gray mural
gray mural
#

the next question then: Is it nice to do smth like that in Unity?

private readonly (((float min, float max) neg, (float min, float max) pos) x, float y, ((float min, float max) neg, (float min, float max) pos) z) spawnPos = (((-13, -6), (6, 13)), .09263992f, ((-11, -6), (6, 11)));
heady iris
#

i'm scared

leaden ice
#

this isn't a unity question

#

it's a C# question

#

and C# does have tuples

gray mural
leaden ice
#

if you are feeling Masochistic, you can certainly use tuples

heady iris
#

is that tuple syntax?

#

i haven't actually tried doing that before

leaden ice
#

but I recommend just making an actual struct

heady iris
#

yeah

leaden ice
gray mural
gray mural
heady iris
#

how do I install Windows (so that i can run unity)

gray mural
steady moat
gray mural
gray mural
heady iris
steady moat
gray mural
leaden ice
steady moat
heady iris
#

it's all basically the same thing to the computer

gray mural
steady moat
#

Programmer are not computer unfortunately.

plain coyote
#

so , I decided to take a leap of faith and try my luck at compiling a .net6 library to 4.8 framework, to use it inside unity.

Any general tips so I can ensure my compatibility with unity?
or is it generally speaking, if it runs under 4.8 framework, it will run in unity?

vale karma
#

Hi every one so I made a quick and easy code for my first person camera movement. Sadly when look to much to the left I can see my player and my camera seems higher then I placed it

heady iris
#

!code

tawny elkBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

heady iris
#

please do not send photos of your screen

vale karma
#

Oh sry

heady iris
#

you can use win+shift+s to clip part of your screen on windows

#

assuming you're logged into discord on this machine

#

use code blocks or one of these paste sites for code

vale karma
#

Na I am not i use my phone

#

Give me a second

fringe ridge
#

Any ideas why in visual studio class Ping is accessed normally and everything is good, but then when I try to build the game it shows that class Ping cant be accessed or found

heady iris
#

what is Ping from? what kind of build are you making?

plain moon
#

Why I can't store AttractorData[] AttractorStructs; I try NativeArray but there's error : BallData used in NativeArray<BallData> must be unmanaged (contain no managed types) and cannot itself be a native container type.

public struct BallData
{
    public int Identifier;
    public Vector2 Position;
    public Vector2 Force;
    [NativeDisableContainerSafetyRestriction] public AttractorData[] AttractorStructs;
}
public struct AttractorData
    {
        public float Force;
        public Vector2 Position;
        public Vector2 Direction;
        public int AttractionType;
    }
rain coral
#

Hello I’m trying to make a mechanic in the game where I can command troops from 1-20 with formations but I don’t know where to start

warm stratus
#

hey, i have a problem to get the audio sources on a gameObject (it is a prefab maybe it is the problem)
AudioSource[] audioSources = GetComponents<AudioSource>();

fallen epoch
#

I assume that script's on the same game object as the AudioSources?
Did you try replacing AudioSource[] with var? πŸ˜›

knotty sun
warm stratus
knotty sun
#

of course there is Unity 101 basics, you should know this

warm stratus
#

a...

fallen epoch
#

In the default UI layout, when you have a game object selected, it's on the right hand side of the screen

warm stratus
#

somewhere here?

fallen epoch
#

That entire window is the inspector πŸ˜…

knotty sun
#

no, the whole inspector for the complete game0bject

warm stratus
knotty sun
# warm stratus

how can you not know this, you added AudioSources to an object did you not

warm stratus
knotty sun
#

well if the script added them why do you need GetComponents?

late lion
plain moon
warm stratus
#

i use GetComponents to add them into a list which each frame low the volume of each element to smoothly stop the sounds between scenes

#

@knotty sun

rugged storm
#

Hay im making a turn based game and the enemy turns are not very computationally heavy so they end up happening almost instantly and all the enemies move at basically the same time, how would I go about slowing this down so it looks a little nicer and stuff?

late lion
knotty sun
# warm stratus <@556797857584381953>

you are missing my point. If you add the AudioSource components in script you alreasy have a reference to add to your list, you dont need to use GetComponents

warm stratus
#

but i still don t understand why it don t work

rugged storm
#

in my script I basically go through enemy.TurnLogic(); for each enemy during thier turn is there a way i could wait until say the movement animation of one enemy is done before the next one's turn

knotty sun
warm stratus
knotty sun
#

ok. So show the inspector of this gameobject in play mode once the audiosource has been added

violet mesa
#

Does anybody know how to get a bullet list in textmeshpro?

wide terrace
swift falcon
#

Plz could anyone tell me if there is an error unity keep saying that "skull" could not be found

public class Area : MonoBehaviour
{
public skull[] enemyArray;

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.CompareTag("Player"))
    {
        foreach (skull enemy in enemyArray)
        {
            enemy.chase = true;
        }
    }
}
violet mesa
gray mural
knotty sun
hexed pecan
swift falcon
knotty sun
#

well what do you expect then? Magic?

violet mesa
#

i basically want a dot (bullet) before every new line

fallen epoch
heady iris