#archived-code-general

1 messages ยท Page 66 of 1

vagrant blade
#

But yes, raycast from the camera is the usual way to detect interactions

ruby trellis
#

I do want to select the objects that are really far away so that would have to be set quite high

ruby trellis
vagrant blade
#

I don't know how accurate it will be when things become that far though.

ruby trellis
#

well I'll try if it doesent work I'll keep looking

uncut plank
ruby trellis
#

I guess a spherecast could help then

uncut plank
#

it could get stuck on some obstacle along the way

ruby trellis
#

do raycasts stop when hitting an object?

#

damn

uncut plank
#

dont fix what isnt broken

eternal geyser
#

.

ruby trellis
#

I guess yeah

#

Ill get on it

uncut plank
#

perhaps youre calling this coroutine every frame

buoyant mural
uncut plank
#

though this is a pretty inefficient way of implementing this

buoyant mural
#

and something else

uncut plank
#

it's better to just use deltaTime instead of a coroutine

buoyant mural
#

delta?

uncut plank
#

if you increase a value by x * Time.deltaTime every Update, it will increase at a constant speed of x

buoyant mural
#

Ok

#

That's not what I want though

uncut plank
#

what are you trying to make then

buoyant mural
#

Well it's quite hard to explain

#

it worked this is the final code

inland escarp
#
    IEnumerator CalculateTrajectory(Bullet bullet)
    {
        while (true)
        {
            bullet.flightTime += 0.1f;
            //print("Fire1");
            bullet.lastPosition.x = 0.0f;
            bullet.lastPosition.y = bullet.startPosition.y + bullet.height;
            bullet.lastPosition.z = bullet.startPosition.z + bullet.distance; 
            CalculateZDev(bullet);
            CalculateYDev(bullet);
            bullet.newPosition.x = 0.0f;
            bullet.newPosition.y = bullet.startPosition.y + bullet.height;
            bullet.newPosition.z = bullet.startPosition.z + bullet.distance;

            //print("FlightTime:" + bullet.flightTime);
            print(bullet.lastPosition);
        
            if (Physics.Raycast(bullet.lastPosition, bullet.newPosition - bullet.lastPosition, Vector3.Distance(bullet.lastPosition,bullet.newPosition)))
            {
                print("Hit.");
            } 
            Debug.DrawRay(transform.TransformPoint(bullet.lastPosition), transform.TransformDirection(bullet.newPosition - bullet.lastPosition), Color.green, 5.0f);
            yield return new WaitForSeconds(0.1f); 
        }
    }

I've tried sending this in beginner but nobody else has had much luck so perhaps someone in here might find something.

I'm trying to make a raycast based ballistic system. Problem is the rays are acting up and I'm not entirely sure why. Any ideas?

#

This is what it should, and did, look like. Problem is that the rays would not shoot out in transform.forward.

mossy snow
#

what do the calculate methods do? And you perform the raycast as though the bullet position were already in world space, but then you transform it anyways so either the raycast is wrong or the debug line is wrong

sudden crest
#

Im trying to create a simple dialogue system
but im having trouble switching between each dialogue
whenever the player presses e again
can anyone help
I always get dialogue3 the first
and nothing else

inland escarp
sudden crest
#

if(Input.GetKey("e") &&distance>Vector3.Distance(player.position, npc.position)){

   

    if(Physics.Raycast(r,out hit,distance)){
add(b);
StartCoroutine(Dialogue1());




    
    }}



buoyant mural
#

GetKeyDown

#

Change it to GetKeyDown

sudden crest
#

ok

#

lemme try

buoyant mural
#

GeyKey means even if held

#

So not press

#

Hold

sudden crest
#

ummm

#

now the second dialogue gets skipped

#

while the first and third get played

buoyant mural
#

Use GetKeyDown(KeyCode.E) instead of "E" won't fix your problem but it's a better way

mossy snow
inland escarp
#

In calculateydev, flight time should be bullet.flighttime - it's been fixed

buoyant mural
#

Else if statement

#

@sudden crest

else if(b == 1){
 
count = 1;
b = 2;
return;
}
else if(b == 1){
 
count = 2;
return;
}```
#

You might have a mistake here

broken light
#

whats a good way to step through an algorithm and also draw the results out via gizmos ? if using VS step through the gizmos wont draw so its not helpful

#

its useless reading the variable data as its just too many numbers to track to know wtf is going on

mossy snow
inland escarp
mossy snow
#

(1/2 * gravity * Mathf.Pow(bullet.flightTime, 2.0f)) evaluates to 0

inland escarp
mossy snow
#

1/2 does integer division = 0

#

0 * gravity * Mathf(...) = 0

#

make one a float or use 0.5f

inland escarp
#

ooh, sorry. misunderstood what you said, ty

sudden crest
#

@buoyant mural now it just shows the first dialogue

#

and nothing else

inland escarp
mossy snow
#

no, copied as-is, moved your trajectory into start instead of on button press with no other changes

#

do you have any scaling on your object?

#

that's probably what's happening here

inland escarp
#

on my gun object

mossy snow
#

TransformDirection takes scale into account. Switch to TransformVector

inland escarp
#

Although when I look around while a bullet is moving, the bullet also seems to move around

mossy snow
#

whoops, got them reversed actually. This means your trajectory is affected by scale though, that's probably not what you want. Why not just use world position the whole way through?

#

yes, because you're transforming the path by the shooter's position, rotation, and scale

inland escarp
mossy snow
#

? it's just a coordinate system. Presumably your bullet should no longer be affected by the shooter's position once fired, so convert local -> world on shoot, then deal in world position thereafter. It'll make the raycasting correct too

inland escarp
simple egret
#

transform.forward is "in world space"

#

As long as you have a way to pass that to the projectile at the right time, and you make the bullet follow that direction, it'll work

#
// Gun
var clone = Instantiate(prefab);
clone.transform.forward = transform.forward;

// Bullet
transform.position += transform.forward * step;

^ Will work whatever your current rotation is

inland escarp
#

in

Debug.DrawRay(transform.TransformPoint(bullet.lastPosition), transform.TransformVector(bullet.newPosition - bullet.lastPosition), Color.green, 5.0f);
simple egret
#

As simple as calculating the direction from the last pos to the current one, with the right distance

Vector3 dir = curPos - lastPos;
float distance = dir.magnitude;
dir.Normalize();

Physics.Raycast(lastPos, dir, out _, distance);
inland escarp
#

whats curPos?

simple egret
#

No point or direction transformations, everything is in world space already

#

Projectile's current position

#

In world space

inland escarp
#

ah, for some reason i read it as cursor position

simple egret
#

Ah yeah, I guess it can be interpreted like that too

inland escarp
#

If you can see those tiny green dots

simple egret
#

Looks like the positions you feed in the direction/distance calculation aren't right

inland escarp
#

wait for debug, do I have to times the direction and distance together?

simple egret
#

Depends, are you using DrawRay?

inland escarp
#

yep

simple egret
#

Yeah you need to multiply the second arg with the distance

inland escarp
#

yep it works now

#

actually

inland escarp
simple egret
#

So that depends on how you move that projectile in code

inland escarp
#

How should I be moving it?
Current Code for context:

    IEnumerator CalculateTrajectory(Bullet bullet)
    {
        while (true)
        {
            bullet.flightTime += 0.1f;
            //print("Fire1");
            bullet.lastPosition.x = 0.0f;
            bullet.lastPosition.y = bullet.newPosition.y;
            bullet.lastPosition.z = bullet.newPosition.z; 
            CalculateZDev(bullet);
            CalculateYDev(bullet);
            bullet.newPosition.x = 0.0f;
            bullet.newPosition.y = bullet.startPosition.y + bullet.height;
            bullet.newPosition.z = bullet.startPosition.z + bullet.distance;

            //print("FlightTime:" + bullet.flightTime);
            print(bullet.lastPosition);
            Vector3 direction = bullet.newPosition - bullet.lastPosition;
            float distance = direction.magnitude;
            direction.Normalize(); 
            if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
            {
                print("Hit.");
            } 
            Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
            yield return new WaitForSeconds(0.1f); 
        }
simple egret
#

Not sure, nothing actually moves an object here. Is the bullet an object in the scene, or purely a class instance in code?

inland escarp
#

purely a class instance

simple egret
#

Okay I see, interesting way of doing it!
So, upon creating the bullet instance, you should pass whatever "forward" it needs to go into a field or property

#

Could be as easy as bullet.forwardDirection = transform.forward

#

Then you set up the movement around that variable

inland escarp
simple egret
#

I think so, if I understand it correctly the "distance" and "height" simulate bullet drop?

inland escarp
#

yup

#

Sorry for somewhat leaching off of you rn, I'm half asleep but want to finish this so that I can sleep peacefully instead of brainstorming how to fix this. I've been trying to fix this for a few days now.

simple egret
#

Okay I see now how it's working. So yes, you'd need to add the deviation values, move towards the next position using the "forward direction" variable, and recalculate that "forward direction" value so it accounts for the previous deviation you just applied

inland escarp
#

aight ty

inland escarp
#

or am i being dumb

#

prior to normalizing it

simple egret
#

No these aren't related until after you shoot the raycast

#

If you do that, you'll lose the deviation, and your bullet will fly straight

#

Raycasting downwards

#

It'll do something like that:

#

Dotted: bullet travel path
Solid: raycast direction

inland escarp
#

Ook

#

and where do i put my bullet.forwardDirection variable once i've added distance and height to it's z and y?

simple egret
#

Summed up, the whole process goes like that:

Initialize the forward direction when the instance is created.

Compute deviation, and add it to the forward direction. Move your bullet to that new position.
Compute the direction/distance for the raycast and fire it.
Update the forward direction to be the raycast direction we just created, so devialtion is accounted for.
Repeat the past 3 instructions until the bullet needs to be destroyed

#

The forward direction doesn't get updated until the very end of a "step" (an iteration)

#

It'll look like this in the end:

#

(I've offset the arrows so you see them, in reality they overlap)

inland escarp
simple egret
#

From the current position, if you re-calculate and apply a deviation for each iteration

#

You do

inland escarp
#

would that not just be direction then?

#

as we're doing current - last?

simple egret
#

Yep; but current is the one after you apply the deviation

sharp saddle
#

I'm trying to make a randomly generated map with rooms that connect with eachother here is my script: // Add an opening to the connector room where the new room is attached
GameObject connectorRoom = GameObject.FindGameObjectWithTag("Connector");
Vector3 openingPosition = connectorRoom.transform.InverseTransformPoint(newPosition);
if (opening == Vector3.forward)
{
connectorRoom.GetComponent<Room>().AddOpening(RoomOpeningType.Front, openingPosition);
}
else if (opening == Vector3.right)
{
connectorRoom.GetComponent<Room>().AddOpening(RoomOpeningType.Right, openingPosition);
}
else if (opening == Vector3.back)
{
connectorRoom.GetComponent<Room>().AddOpening(RoomOpeningType.Back, openingPosition);
} I'm getting the error NullReferenceException: Object reference not set to an instance of an object
Generator.Start () (at Assets/scripts/Generator.cs:113) and I'm not sure what to do. I've already tagged the prefab of the connector as a "Connector".

bronze rampart
simple egret
#

So you can't know the value of current before you apply the deviation, and apply that to your position

#

In my schema above, there would be 4 deviation recalculations (don't forget the one at the starting point)
So, 4 positions moves, 4 previous-to-current-direction calculations, 4 raycasts, and 3 "forward direction" recalculations (since the first one is pre-calculated when you spawn the bullet)

sharp saddle
simple egret
sharp saddle
simple egret
#

Through a tag?

#

Ah yeah right

#

If it was null it would have thrown the error on the line where you do the InverseTransformPoint stuff

#

So, it doesn't have a Room component attached

#

FindObjectWithTag might be picking up another object you tagged "Connector" by accident?

inland escarp
# simple egret So you can't know the value of `current` before you apply the deviation, and app...

Where'd I go wrong? It doesn't work.

    IEnumerator CalculateTrajectory(Bullet bullet)
    {
        while (true)
        {
            bullet.flightTime += 0.1f;
            bullet.lastPosition = bullet.newPosition;
            CalculateYDev(bullet);
            CalculateZDev(bullet);
            bullet.forwardDirection.y = bullet.height;
            bullet.forwardDirection.z = bullet.distance;
            
            bullet.newPosition = bullet.forwardDirection;
            
            Vector3 direction = bullet.newPosition - bullet.lastPosition;
            float distance = direction.magnitude;
            direction.Normalize(); 
            if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
            {
                print("Hit.");
            } 
            Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
            yield return new WaitForSeconds(0.1f); 
        }
    }
simple egret
#

Again, you don't touch the forward direction until the very end

#

And especially don't put the deviation values in it!

inland escarp
#

Isn't that step 2?

simple egret
#

You add them to the current position, to get the new position

bullet.newPosition.y += bullet.forwardDirection.y + bullet.height;
lament ocean
#

I've been looking around and I cant seem to find a nice way to handle collision between different teams and their projectiles. Would I really just have to make a collision layer for each teams projectile and units?

#

I'm looking for this kind of interaction
Every team should collide with eachother and not themselves
Every teams projectiles should collide with eachother but not their team or their teams projectiles

inland escarp
# simple egret You add them to the current position, to get the new position ```cs bullet.newPo...

Like this?:

    IEnumerator CalculateTrajectory(Bullet bullet)
    {
        while (true)
        {
            bullet.flightTime += 0.1f;
            bullet.lastPosition = bullet.newPosition;
            CalculateYDev(bullet);
            CalculateZDev(bullet);

            bullet.newPosition.y = bullet.forwardDirection.y + bullet.height;
            bullet.newPosition.z = bullet.forwardDirection.z + bullet.distance;
            
            Vector3 direction = bullet.newPosition - bullet.lastPosition;
            float distance = direction.magnitude;
            direction.Normalize(); 
            if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
            {
                print("Hit.");
            } 
            Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
            bullet.forwardDirection = direction;
            yield return new WaitForSeconds(0.1f); 
        }
    }
simple egret
#

Almost, += for the two newPosition sets

#

Otherwise they'll stay near the world origin as it's not added to the current position anymore

inland escarp
simple egret
#

Maybe it's an optical illusion with the grid, but I see a drop here

inland escarp
#

Oh no, it does drop. The gun is facing the opposite direction.

proud juniper
#

Do any solo devs have insight on what ticketing systems they use to ticket work on their projects, if any do? I find that without using some kind of system (ie, Trello, Monday, a spreadsheet, something) I get way too disorganized too fast.

inland escarp
#

I'm shooting in the air here

sharp saddle
simple egret
inland escarp
#
IEnumerator CalculateTrajectory(Bullet bullet)
    {
        print(bullet.forwardDirection);
        while (true)
        {
            bullet.flightTime += 0.1f;
            bullet.lastPosition = bullet.newPosition;
            CalculateYDev(bullet);
            CalculateZDev(bullet);

            bullet.newPosition.y += bullet.forwardDirection.y + bullet.height;
            bullet.newPosition.z += bullet.forwardDirection.z + bullet.distance;
            
            Vector3 direction = bullet.newPosition - bullet.lastPosition;
            float distance = direction.magnitude;
            direction.Normalize(); 
            if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
            {
                print("Hit.");
            } 
            Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
            bullet.forwardDirection = direction;
            yield return new WaitForSeconds(0.1f); 
        }
    }

No output

simple egret
#

Then that code isn't running, or you disabled info messages in the console

inland escarp
#

wait i may have collapsed everything

broken light
#

Any one know why i get "supplied vertex array has less vertices than triangle array" and for uvs i get "supplied array needs to be same size as mesh.vertices array"

For this code:

        int vertexIndex = 0;
        for (int i = 0; i < _data.Triangles.Count; i++)
        {
            Triangle triangle = _data.Triangles[i];

            _verts.Add(triangle.A.xyz());
            _verts.Add(triangle.B.xyz());
            _verts.Add(triangle.C.xyz());

            _uvs.Add(triangle.A);
            _uvs.Add(triangle.B);
            _uvs.Add(triangle.C);

            _tris.Add(vertexIndex);
            _tris.Add(vertexIndex+1);
            _tris.Add(vertexIndex+2);

            vertexIndex += 3;
        }
inland escarp
#

I accidentally collapsed the logs

simple egret
#

Okay that's definitely not pointing where the bullet is going

#

The vector looks like a correct direction vector, so the issue does not come from there

#

Try stripping out the deviation calculations for now, and try again but this time by adding a constant value each step, on one line, like so

bullet.currentPosition += bullet.forwardDirection * 100;
#

That should be propelling it at 10 units per second towards whatever forward direction

#

And strip the code after that line too

inland escarp
simple egret
#

Yeah, comment all of this onwards

#

Except the yield statement

inland escarp
#
        print(bullet.forwardDirection);
        while (true)
        {
            bullet.flightTime += 0.1f;
            bullet.lastPosition = bullet.newPosition;
            CalculateYDev(bullet);
            CalculateZDev(bullet);

            // bullet.newPosition.y += bullet.forwardDirection.y + bullet.height;
            // bullet.newPosition.z += bullet.forwardDirection.z + bullet.distance;
            
            bullets.newPosition += bullet.forwardDirection * 100;

            // Vector3 direction = bullet.newPosition - bullet.lastPosition;
            // float distance = direction.magnitude;
            // direction.Normalize(); 
            // if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
            // {
            //     print("Hit.");
            // } 
            // Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
            // bullet.forwardDirection = direction;
            yield return new WaitForSeconds(0.1f); 
        }

Like so?

simple egret
#

Yep looks good

inland escarp
#

what do you want to see?

#

do you want me to print newposition?

simple egret
#

Ah forgot there's no object in the scene sorry
Draw a ray from last position to new position in that loop

inland escarp
#

Debug.DrawRay(bullet.lastPosition, bullet.newPosition - bullet.lastPosition, Color.green, 15.0f);

#

@simple egret

simple egret
#

Does it draw towards where you're shooting at?

inland escarp
#

yup

simple egret
#

Testing stuff on my side, hang on

inland escarp
#

aight

ocean osprey
#

Is it possible to access MonoBehaviour scripts through editor window scripts?
If so how

simple egret
# inland escarp aight

Okay I came up with something that works, but the catch is that the drop is measured with a Quaternion ๐Ÿ’€

#

But it seems like it's working correctly

solemn raven
#

hi is it possible to initialize an empty gameobject without a prefab ?

simple egret
#

new GameObject()

simple egret
#

The drop is a rotational value instead of two values. Like "-5 degrees per step"

solemn raven
simple egret
#

But you can see the direction gradually falling over each iteration, and the Y position falls exponentially

#

lmao if I put on more iterations the bullet goes in circles as expected

#

3am, it's bed time
Feel free to ping me if you solve it in the meantime

ocean osprey
#

Is it possible to access MonoBehaviour scripts through editor window scripts

solemn raven
#

hey,
what is the right way to set Rect transform ?

#

is it LocalPosition or something else ?

#

i meant via code

#

I wanna set left, top,Pos Z , right , Bottom to zero and also change the anchor present

somber tapir
earnest epoch
#

@solemn raven Consider setting .anchorMin, .anchorMax, anchoredPosition and .sizeDelta. The transform stuff in the inspector is derivative of how the underlying data is actually stored.

solemn raven
marble halo
#

Ok so I'm trying to make it so the player slides down slopes that are too steep

#
    {
        if (Physics.SphereCast(player.transform.position,Controller.radius,Vector3.down,out slopeHit,player.groundMask))
        {

            hitNormal = slopeHit.normal;
            return Vector3.Angle(Vector3.up, hitNormal) > Controller.slopeLimit;
        }

        else
        {
            return false;
        }
    }```
#

but for some reason the sphere cast isnt working

#

for some reason if the direction is something other than down it works, but it doesnt work right

earnest epoch
#

I would generally use a dot product of your normal and the world up direction rather than measure in degrees (+1 for if normal is same as up, -1 if they're totally opposite). @marble halo

marble halo
earnest epoch
#

So the good news is that it seems your code is working... ๐Ÿ˜„

earnest epoch
#

Remember, your floor normal is looking at the sky, assuming gravity is pulling your character down. @marble halo

marble halo
#

but the sphere cast still gets nothing

#

why wont the damn thing work?

#

also slopes dont point up

earnest epoch
#

Are you possibly interacting with yourself? Edit: probably not if you're checking for ground.

marble halo
#

player.groundMask this should only check the ground layer though?

#

its not set to player

earnest epoch
#

If your ground layer and layermask contain the right values, then you would think so, yes.

#

Your Angle math is backwards anyway; what I mentioned earlier is definitely still going to be an issue.

proud quartz
#

hello! I'm experimenting with changing a UI panel's rectTransform through code but don't know exactly how. Do any of you have any experience with this?

proud quartz
#

perfect. Thank you!

earnest epoch
#

@marble halo You're definitely colliding with something if your code is getting far enough to report 0. I'm thinking that you might be measuring an interaction with your own player because of how the value never changes. Use of Angle() should give you 0 when hitNormal is also exactly Vector3.up. Does your player stay upright at all times? That would give a 0 result if it's being matched by your ground mask.

marble halo
#

player does stay upright at all times

#

not even sure how you can rotate the character controller

earnest epoch
#

@marble halo Well, since you're for sure colliding with something, have you considered checking hitInfo for what you're colliding with?

#

@marble halo You ought to be able to get to the name of the object via hitInfo.collider.gameObject.name

lapis vine
#

for some reason, when trying to read properties/keywords from a material, my script doesn't grab the latest ones (because i assume they are not saved / written to disk) until i recompile something (such as the script). i assumed it may be a problem with the material not saving (and i know calling saveassets is asynchronous but even if i call a wait it still runs into the same issue). i tried about every AssetDatabase, EditorApplication and EditorUtility function to see if i could try and force save before reading and i've gotten nothing yet. any one have any ideas :/

hollow dust
#

how do i have a game object thats attached to my character face the direction my player is facing? in this case i have an arm thats seperate from the capsule player and it kinda, well, looks in its own direction, so i wrote some code and it kind of works? the object faces in the direction im looking, it just does not actually rotate the arms fully with my character, here ill send a vid but heres the code

public class Orientation : MonoBehaviour
{
    public Transform orientation;
    // Start is called before the first frame update
    void Start()
    {
        
    }

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

        Vector3 position = transform.position;
        Vector3 direction;



        direction = orientation.forward + transform.position - position;
        transform.rotation = Quaternion.LookRotation(direction);
    }
}
marble halo
earnest epoch
hollow dust
#

wait why is that done as a file

#

ohhh do i need to convert it

earnest epoch
hollow dust
#

there we go'

earnest epoch
#

You could solve this in code, but the simplest solution would be to parent the arms to yet another child object so you have Player > ArmPivot > ArmModel in the hierarchy.

proud quartz
#

agreed

earnest epoch
#

Let the child ArmPivot rotate and use the child of that child to offset your arm forward into your view.

hollow dust
#

ohhhh

#

so create empty --> armpivot then drag my arms into that

#

and parent the armpivot to my pc controller

earnest epoch
#

Frankly, if all you need is to have your hands follow the pitch of your camera, you shouldn't have to control the yaw rotation of your arms at all; can't they just rotate with the parent capsule? @hollow dust

hollow dust
#

i tried, albiet before the new parenting stuff and it kinda just kept facing one way

earnest epoch
#

Capsule rotates with yaw, ArmPivot rotates with pitch. The arms are actually a further child of ArmPivot. You might be able to simplify all of this.

hollow dust
#

i got it kind of working, it just only does it backwards lol

#

dw

#

i can fix it on my own from here

#

tysm!!

mossy vine
#

Just to make sure. when setting a variable. the difference between public and private is that public allows me to acces that variable in other scripts and private makes it exclusive to that script

#

also i can edit the variable in the inspector. right?

hollow dust
mossy vine
#

oh snap THATS what serialized is for

#

oh so its private i ust wanna edit it in the inspector without having to go back and forth to the code? Do people leave it serialized of just when they are developing

earnest epoch
#

The reason this works is because [SerializedField] has the secondary effect of making the field read/writable by Unity's design-time tools. The inspector sort of doesn't care what is public or private, but happens to treat any public data on components as serialized anyway. There isn't much rhyme or reason to it. You the user aren't what public/private keywords are trying to protect your objects' data from anyway.

mossy vine
#

ahhhh ok im starting to get it. before i know it imma be op in code like you

earnest epoch
mossy vine
#

im learning about simple types now. I did mugen for years so variables are entirely new to me. Different is that our stuff was preset all we had to do was put in the number

earnest epoch
# mossy vine im learning about simple types now. I did mugen for years so variables are entir...
Omi

In this video, we get right into all the fundamental (primitive) data types used in C#.

00:00 Intro
00:17 What is Primitive Data?
01:25 Integrals (Integers)
11:03 Initiation and Default Values
12:38 Nullable Types
13:36 Integrals Not Covered
15:18 Floating Point Numbers (Reals)
18:12 Precision Demonstration (In Unity)
22:37 Char Type
23:46 Tupl...

โ–ถ Play video
#

Also, what I say at the end about string == char[] is only partially true as strings are immutable in C#. I'm going to reupload this video with corrections in the next day or so.

mossy vine
#

oh nice. you did a vid. let me check it out and save it to my learning playlist. TYSM!!!

plucky karma
#

One suggestion would be to show the website where value type's domain is displayed as a table struct - as well as a link reference to the documentation for user who wants to read more into! @earnest epoch

earnest epoch
plucky karma
#

Do express yourself, because eventually you can edit your video. It's fun to edit your footage to help deliver contents clear and informative.

whole comet
#

hi! i'm trying to implement my own version of the vertex lighting parameters for unity_LightAtten. the docs claim y is 1/cos(spotAngle/4) but this cannot possibly be right.
i've plotted out a bunch of bunch of spot angles and their values grabbed from the frame debugger below. spot angle is on the left

{179, 1.4256}
{170, 1.538174}
{160, 1.688059}
{120, 2.732051}
{105, 3.470881}
{100, 3.794776}
{90, 4.613126}
{80, 5.75877}
{70, 7.431356}
{60, 10.00997}
{50, 14.28811}
{40, 22.16552}
{30, 39.18637}
{20, 87.81952}
{15, 155.9076}
{11, 289.6719}
{10, 350.4453}
{1, 35025.5}
#

unfortunately i dont think the source code is available for the built in pipeline or whichever part of the codebase actually calculates these variables so i can't just go check

#

anyone have any ideas?

tidal locust
#

Hey Team, I am trying to make night club laser, What I have is a line render and with that, I was told to use Partical system. How ever with saying that, I am trying to make more then one laser beam and something that looks some what real. This is my code so far.

using UnityEngine;
using System;

public class LaserController : MonoBehaviour
{
    public float laserLength = 50f;
    public float laserDuration = 0.1f;
    public Color laserColor;


    
    public float fireDelta = 0.5F;
    private LineRenderer lineRenderer;
    


    private void Start()
    {
        
        Debug.Log("this is working");
        lineRenderer = GetComponent<LineRenderer>();
        lineRenderer.material.color = laserColor;
        lineRenderer.enabled = true;
    }

    private void FireLaser()
    {
        lineRenderer.enabled = true;
        lineRenderer.SetPosition(0, transform.position);
        lineRenderer.SetPosition(1, transform.position + transform.forward * laserLength);

        // Adjust the laser light range based on the laser length
        
        Invoke("StopLaser", laserDuration);
    }


    void Update()
    {
        float[] spectrum = new float[256];

        AudioListener.GetSpectrumData(spectrum, 0, FFTWindow.Rectangular);

        for (int i = 1; i < spectrum.Length - 1; i++)
        {
            float tmp = spectrum[i] * 5;
            if (tmp >= 1.2f )
            {
                FireLaser();
            } 
            Debug.Log(tmp);
            
        }
    }

    private void StopLaser()
    {
        lineRenderer.enabled = false;
    }
}

so this code is listening to a audio track, for its highs, once done so. it will trigger the lasers.
But my lasers are not looking like lasers, I am not sure how to get the partical system to work with the line render

leaden ice
tidal locust
leaden ice
#

i have no idea what your project template has to do with anything other than the fact that the different render pipelines have different postprocessing frameworks

#

you'll want Bloom either way.

tidal locust
#

ahh alright, thank you for the advice ๐Ÿ™‚

sharp saddle
#

I'm trying to make a survival horror game in which the player searches through a randomly generated assortment of rooms, however I keep getting an error that "NullReferenceException: Object reference not set to an instance of an object Generator.Start () (at Assets/scripts/Generator.cs:111)". Here is the pastebin if someone would like to take a look: https://pastebin.com/ASM7vaqx

#

Main issues seem to be from 105 - 120

knotty sun
#
connectorRoom.GetComponent<Room>()

must not have a Room component

cosmic rain
tidal locust
#

Alright, I have got something working and it is looking really good, now to add more lasers to one component

merry vigil
#

p = new Paragraph(string.Format("xxx - yyy : {1}", 0, 9));
p.Alignment = Element.ALIGN_CENTER;
document.Add(p);

Friends, I have such a code snippet. But this prints plain text to the pdf file. I want to make one image print of it. How can I do it ?

sharp saddle
cosmic rain
sharp saddle
#

Welp the problem was that I named the script something i shouldnt have thanks for your help thouhg

cosmic rain
#

Script name and class name are 2 different things. Although they have to match for a MonoBehaviour to work propely

#

You enable looping in the animation import settings. As for making it play when moving, it depends on whether you're using the animator or something else.

#

yes

#

Animation import settings. Not the animation component.

#

For that, you should do the beginner pathway on unity learn. Or read the manual.

mossy snow
#

you'll be back for another fish though

cosmic rain
#

Nope. We don't appreciate people that don't put the effort here.

#

I feel like you didn't look at the manual after all...

#

I'm saying that if you did look in the manual, you should know the answer.

#

Where the manual is?

#

google "unity manual"

quartz folio
#

!manual

tawny elkBOT
dim hill
#

Hey, I have a UI button that triggers an upgrade for an object in my game, however for some reason when i press the button the function that it activates runs twice. is there any reason for this?

Here is my code for the listener

rangeButton.onClick.AddListener(RangeUpgrade);

And here is my code for the upgrader

 public void RangeUpgrade()
    {   
        print("Range upgrade executed");
        
        if (statsManager.money >= rangecost && rangelvl <4);
        {
            statsManager.money -= rangecost;
            rangelvl += 1;
            print("range lvl ="+rangelvl);
            print("money ="+ statsManager.money);
            
        }
    }
quartz folio
#

if it runs twice, you either click it twice, or you subscribe twice

#

(subscribing twice can include not unsubscribing when you should, and leaving something subscribed where it just gets called again)

dim hill
#

so i should have a bool that activates when the button is pressed and run the code through that?

#

or i change the buttons interactability

quartz folio
#

No, just make sure you subscribe only once? And any time your objects are destroyed make sure you call RemoveListener

dim hill
#

oh alright, thanks!

inland escarp
#
    IEnumerator CalculateTrajectory(Bullet bullet)
    {
        print(bullet.forwardDirection);
        while (true)
        {
            bullet.flightTime += 0.1f;
            bullet.lastPosition = bullet.newPosition;
            CalculateYDev(bullet);
            CalculateZDev(bullet);

            bullet.newPosition.y += bullet.forwardDirection.y + bullet.height;
            bullet.newPosition.z += bullet.forwardDirection.z + bullet.distance;
            
            //print(bullet.newPosition);
            //bullet.newPosition += bullet.forwardDirection * 100;

            Vector3 direction = bullet.newPosition - bullet.lastPosition;
            //print(direction);
            float distance = direction.magnitude;

            print("Before" + direction);

            direction.Normalize(); 

            print("Normalized" + direction);

            if (Physics.Raycast(bullet.lastPosition, direction, out _, distance))
            {
                print("Hit.");
            } 
            Debug.DrawRay(bullet.lastPosition, direction * distance, Color.green, 5.0f);
            //Debug.DrawRay(bullet.lastPosition, bullet.newPosition - bullet.lastPosition, Color.red, 15.0f);
            bullet.forwardDirection = direction;
            yield return new WaitForSeconds(0.1f); 
        }
    }

Trying to make a raycast ballistic system where bullets have no real object, and are only class instances. My main problem is that my ray is not shooting in transform.forward, but instead in the global z axis. Any help?
Sorry if you've seen this again, I still haven't worked it out.

cosmic rain
inland escarp
#

Yes

cosmic rain
#

Also, why the y z axis and not x?

#

Why not just add a vector?

inland escarp
#

z axis is forward axis

cosmic rain
inland escarp
cosmic rain
#

ummm

inland escarp
#

transform.forward is in the z axis

cosmic rain
#

if you're talking about local space, yes

#

does that mean that newPosition is in local space?

#

transform.forward is not in the z axis btw. That statement doesn't make any sense

inland escarp
cosmic rain
#

Yes, that is correct. It tells you that transform.forward aligns with the local space z axis. But it's not the same as transform.forward is in the z axis

inland escarp
#

that's just being pedantic

cosmic rain
#

And what's more important, raycasts take world space, not local space.

cosmic rain
#

Since you're dealing with "imaginary" objects without resorting to any local-world space transformations, there's no point at all in using the local space.

lapis tiger
#

just started Unity a day ago and i am lovely it, honestly switching from roblox's lua to C sharp is annoying but its really funny ngl.

wintry crescent
#

I've got a bit of a silly question about best practices
If class A makes an object of class B
And class C needs to access said object
and now:

  1. should it get a reference to class A, and get the public reference to the object through A.bObject
  2. should class A get a reference to class C, and call something like C.GiveReferenceToBObject(bObject)
  3. should class D create the object B, and both classes A and C have total access to it?
  4. Should class C do something along the lines of this.bObject = a.bObject and use that?

As of right now, there is only one instance of B
Which means that option 4. seems to be the best
But, it is possible that in the future, B will be replaced by another instance of B, at an arbitrary point in time
which points to other options
How concerned should I be with the possibility of it happening?
I'm conflicted
On one hand, option 4 seems to be the simplest and cleanest option which is good, but on the other, making it so that class C has to be modified when changing class A is a bad practice

#

I am not sure if this is the right place to ask, but I don't know where else I should go

cosmic rain
stable rivet
wintry crescent
stable rivet
#

but this is a pretty vague answer because again it really depends on your situation

wintry crescent
cosmic rain
stable rivet
wintry crescent
wintry crescent
wintry crescent
cosmic rain
# wintry crescent I'll be honest, I don't exactly remember the original situation that has caused ...

The general solution is to define the relationship between the classes. There's usually a hierarchy(tree) of relationships. The dependencies should usually be between a 2 type linked in the hierarchy(parent-child). Ideally it should also be 1 sided dependency. But then again, not all cases have to follow the same rule, that's why it's important to consider the solution within the context of the problem.

cosmic rain
swift falcon
#

if anyone has an idea how to fix this problem please tell me asap:

I have a URL for a unity web request... i need to change a part of it...
so far I have been using _url = originalString.Replace("oldValue","newValue");

but when I send the unity web request i get "malformed url"... how can I solve this please (if something is wrong with it)

please keep in mind, when i write the new url into my web browser the result is correct... I get the result I want

cosmic rain
wintry crescent
wintry crescent
cosmic rain
cosmic rain
swift falcon
wintry crescent
wintry crescent
cosmic rain
wintry crescent
swift falcon
cosmic rain
#

If they have a dependency, it means that they have some kind of relationship

wintry crescent
cosmic rain
#

What dictionary?

swift falcon
#


    async Task<byte> SendingBadSMS(string phonNumber, string message)
    {
        //string _getUrl;
        string stupid = "https://website.something.com:8002/api?username=asfasfasf&password=asfasfasfasf&ani=QuickShare&dnis=919000412202";
        

        string _getUrl = stupid.Replace("919000412202", phonNumber);

        Debug.Log(_getUrl);
        using (UnityWebRequest www = UnityWebRequest.Get(_getUrl)){
          //sending 
UnityWebRequestAsyncOperation task = www.SendWebRequest();

            while (!task.isDone) { await Task.Yield(); }

          if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
                return 0;
            }
            else
            {
                Debug.Log("Text= " + www.downloadHandler.text);
                Debug.Log("downloadHandler= " + www.downloadHandler);
                return 1;
            }



        }
}

wintry crescent
swift falcon
#

the www.error IS malformed url... but if i copy and past the same url into the webbrowser it works perfectly

cosmic rain
plush sparrow
#
int[] sarr ={1, 2,3,4};
if(val.Contains(sarr)
{    
}
swift falcon
plush sparrow
quartz folio
simple egret
maiden junco
#

im getting these errors when trying to building the project

#

anyone who has experienced those?

cosmic rain
swift falcon
cosmic rain
simple egret
#

You should post the log you get in the console, maybe it's not correctly URL-encoded

#

Like a space in the middle that should be converted to %20 or somethin'

swift falcon
quartz folio
#

how do you get phonNumber

simple egret
#

Your browser converts the URL for you as you submit it, not Unity

#

It might be stripping out characters

swift falcon
simple egret
#

No wait

cosmic rain
simple egret
#

You first ensure that the value you get in Unity is correct

quartz folio
#

You keep saying that with 0 proof

quartz folio
simple egret
#

I'm betting on the following:

the phone number is retrieved from an Input Field's underlying TextMeshPro component, instead of the InputField itself

swift falcon
quartz folio
#

Cool, how do you get phonNumber?

swift falcon
simple egret
#

Okay finally more info

cosmic rain
#

That could be reading line breaks as well

simple egret
#

You should loop over the string, and print out each char value, and check that there's no control characters

quartz folio
#

At least check that the phonNumber is the length you think it is

swift falcon
#

why does NO ONE BELIEVE THAT I KNOW HOW TO TAKE A LINE WITHOUT TAKING ANY MORE LETTERS

simple egret
#

Yeah if you "see" 10 chars, but num.Length returns 11, something's up

swift falcon
#

๐Ÿคฆโ€โ™‚๏ธ

simple egret
#

Why are you so difficult to help?

#

Computers make no mistakes

swift falcon
plush sparrow
#

How do I check if an int array contains a sequence of numbers?

quartz folio
swift falcon
plush sparrow
#

Eg
How do I check if int array contains these values {1, 2,3,4}?

simple egret
plush sparrow
#

For eg

#

My array can have {1, 2,3,4,5,6,7,8}

#

I want to check if my array contains {2, 3,4,5}

quartz folio
plush sparrow
#

I checked hashset
But Idk how it can be implemented in this scenerio

quartz folio
#

iterate over your array and check whether the item is contained in the set

plush sparrow
#

I want to check for multiple elements tho

#

Like check for elements {2, 3,4} in an array having {1, 2,3,4,5}

simple egret
#

Iterate over your array and check whether the item is contained in the set

#

For each element, is it contained in the array? Yes - continue to the next element ; No - the array doesn't contain all the expected elements

cosmic rain
plush sparrow
#

I have an array val

int[] val = new int[5]
val.Sort() 

Is not working

plush sparrow
#

No overload for method sort

#

I am getting this error

quartz folio
#

I would google how to sort an array in C#

cosmic rain
#

Oh, the message above is the error?๐Ÿ˜…

maiden junco
cosmic rain
maiden junco
#

so i should search "t:MeshFilter" and then? I already looked for each object that has a mesh filter but i dont find labels like "Editor Only" or similar

cosmic rain
#

MeshFilter Icon

#

not a mesh filter

#

The assets in question is called MeshFilter Icon

#

It's probably a sprite..?

maiden junco
#

nope

#

i have only 3d objects

#

and some ui

#

and im using probuilder

cosmic rain
#

Well, maybe it's used by ui?

#

UI uses sprites

maiden junco
#

i looked for all my ui objects and nope

#

they only use things like UISprite or Checkmark sprites

cosmic rain
#

Welp that's what the error says.

#

make sure none of the sprites are unity/probuilder default resources

#

You can't use them in a build.

maiden junco
#

oh

#

but

#

i used them in the past builds of the same projects

#

how

cosmic rain
#

Well, some of them. Some of them could be editor only

maiden junco
#

i used the same pause menu in 2 weeks

#

oh

#

ok lemme try

cosmic rain
#

In general it's a bad idea to use built-in assets.

maiden junco
#

yeah i know

#

i was so bored to create them

#

it uses a mesh filter icon, that is the icon that is used on the ProBuilder Mesh Filter component on some of my gameobjects in my scene, so maybe is that the problem?

cosmic rain
#
The assets in question is called MeshFilter Icon
Well, it's mentioned in the error: MeshFilter Icon. Try searching it in the hierarchy.
#

Did you just ignore what I was saying?

smoky sonnet
#

That's the move script

#

Im using blend trees btw for the animations

#

I've been stuck with this for so long and idk how to fix this. Any help is appreciated

maiden junco
#

thats it

#

but now im removing every reference to unity built in sprites

#

anyways thank you

sleek bough
#

There's no off-topic here.

cosmic rain
#

Ok, but how is that relevant to this channel?

lapis tiger
#

oops wrong channel

#

sorry about that

left gale
#

Is anyone aware of issues related to use of local functions with unity? Such as possibly leaking memory

leaden ice
maiden fractal
left gale
#

Well, for example I know some historical versions of mono would generate garbage though not necessarily leak it, on some platforms with local functions. It also just wasn't supported on some console platform builds of mono

#

But atm I'm experiencing what looks like a memory leak, possibly native memory, after having added several local functions which enable and disable entities with rendering components

#

And other material property setting stuff.

#

Anyhow thanks for the response. I'm happy to keep using them if I can

idle flax
#

Hey all. I have a small problem concerning one of my gameplay mechanics. I have a script, which enables gameobjets to attach to each other in order to form a burger. It works perfectly, except for the fact that a base will attach itself to gameobjects that aren't already apart of a burger. I don't understand why this happens, as I've added code that should prevent this from happening. Please help!
https://gyazo.com/9761dd0e2877b2f959743f2fec5a5b17

quick token
#

anyone know a way to optimize a scene with a lot of points?

#

im trying to create the chaos game in unity but i need to have about 2 million object to get an accurate image

#

maybe 200,000

#

only problem is it slows unity down a lot

#

for context its basically just a way of creating fractals

leaden ice
#

Rather than trying to show them all at once

#

That's way too many objects

#

You could also look into drawing this with a shader or something instead of individual objects

blissful whale
#

is it possible to check if a collider collided with more than 1 object?

rocky jackal
#

how can i lerp the rotation of an object so the x and z returns to 0 but the y rotation stays the same ? i tried it like thi but it doesnt work

blissful whale
#

can you provide a link if you have one? I think I cannot search properly

leaden ice
#

You should not ever be touching the xyzw of a quaternion basically

#

They are not euler angles

rocky jackal
blissful whale
#

Okay this worked

#

I was typing it to OnTriggerEnter method so it did not show up

leaden ice
#

Now in this new screenshot you're making the same mistake again

#

With rotation.x

rocky jackal
#

ah thank you so it would be transform.eulerAngles.y ?

leaden ice
#

Those are not euler angles and you should stop trying to use them as id they are

leaden ice
rocky jackal
#

thank you, i hate quaternions and rotation stuff

chilly beacon
#
void proceduralGen() {
        noiseMap = new float[height, width];
        // Generating random float value to use as seed
        float randomFloat = UnityEngine.Random.Range(0, 10000000f);

        // Checking if useRandomSeed Boolean is true in the inspector
        if (useRandomSeed) {
        // public int seed variable
            seed = randomFloat;
        }
        System.Random pseudoRandom = new System.Random((int)seed);

        // Offset to add to Perlin noise
        float offsetX = randomFloat + 100f;
        float offsetY = randomFloat + 200f;

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                float xCoord = (float)x / width * scale + offsetX;
                float yCoord = (float)y / height * scale + offsetY;
                noiseMap[x, y] = Mathf.PerlinNoise(xCoord, yCoord);

                // Add randomization to the Perlin noise
                float randomValue = (float)pseudoRandom.NextDouble() * 2f - 1f;
                noiseValue += randomValue * 0.1f;

                // Edge of the map is water
                if (x == 0 || x == width - 1 || y == 0 || y == height - 1) {
                    map[x, y] = 0;

                } else {
                    map[x, y] = (pseudoRandom.Next(0, 100) < randomFillPercentage) ? 0 : 1;
                }
            }
        }

    }```

so i wish to make a 2d island using cellular automata and then use perlin noise fill the island with biomes i have got 70% of the code working but i want to add a **seed** for ths where the shape of the island and all the biomes within the island stay the same when i insert the seed but i dont whats wrong with my code here
#

and it doesnt generate the biomes proprly

#

and the biomes dont stay constant with the seed

#

this is the entire code for my script

vagrant raptor
#

Hello, how can I make interface operations asynchronously in my game in Unity, I want to do it as fast as I can, what is the fastest way you know

leaden ice
vagrant raptor
# leaden ice What do you mean by interface operations exactly?

I am a plugin developer in a unity game and I can do interface operations in the main threade, that is, just interface operations, changing the text content, etc. In order to do this, the game provides me with certain functions, which method can I call them in the fastest way.

leaden ice
#

There's no fast or slow way to call them

#

There's only one way

simple egret
#

User Interface maybe? Or C# interface?

vagrant raptor
#

gui

#

ui

#

I'm sorry my English is not good, I can't explain myself well.

simple egret
#

You can't be any faster because there's only one way of changing what you want, and those are already optimized

#

Like a TextMeshPro Text that will only redraw the text in the game if it changed

#

Pass the same string 10 times and it'll only perform a redraw once, the first time

vagrant raptor
#

Let me rephrase my question, how can I run my method on the main thread as fast as possible without occupying the main thread?

swift falcon
#

guys i want to change the position here how do i do that ?:

#

Instantiate(projectile, transform.position, Quaternion.identity)

#

should i do:

#

Instantiate(projectile, transform.position = 93 12 43, Quaternion.identity)

#

?

simple egret
swift falcon
simple egret
#

They mean new Vector3(x, y, z)

#

Replace the XYZ with the numbers you want

vagrant raptor
swift falcon
simple egret
#

No

#

Replace transform.position with the new Vector3 operation

vagrant raptor
#

'Task mymethod = domethod(arg1,arg2);
await Task.run(async() => mymethod()') when I run it this way the result is much faster but
await domethod(arg1,arg2);; why do I get a slower result

#

I don't understand asynchrony very well, can you help me a little bit?

swift falcon
swift falcon
#

like this right

simple egret
#

Try it

swift falcon
#

because it told me in the debug that they cannot convert from 'double' to 'float'

simple egret
#

There we go

#

If you have errors say so

swift falcon
#

it is an error

#

" cannot convert from 'double' to 'float' "

simple egret
#

Yeah but you said "will this work" but you already tried it and knew there was an error

swift falcon
#

no the error just popped

simple egret
#

Instead say "I got an error, here's my code, here's the error"

swift falcon
#

after i inserted the code

simple egret
#

Alright. In Unity you need to add f at the end of decimal numbers so they're interpreted as floats. Example 3.14f

restive ice
#

I'm writing a dependency injection framework, and I am having some troubles figuring out the right builder pattern.

RegisterDependency<TDependency> returns a DependencyBuilder<TDependency>.

I can then stack build statements onto that call like so:

LocalContainer.RegisterDependency<FooBehaviour>().FromInstance(fooBehaviour).WithId("someId");

Now normally you would do a Build() call at the end to check if the required parameters have been passed in the earlier calls, but I am looking for a way to make that happen automatically.

How do I make the builder call a check function at the end of these stacked calls only, without making that specific end call? the syntax here would look much cleaner if I could leave out the last call here ``LocalContainer.RegisterDependency<FooBehaviour>().FromInstance(fooBehaviour).WithId("someId").NowActuallyRegister();`

I asked chatgpt and it came up with implementing IDisposable and then registering my dependencies like

using (var builder = LocalContainer.RegisterDependency<string>().FromInstance(someStringDependency))
{
    // Do something with the builder
} // Dispose will be called automatically at the end of the using block

but that seems silly, as i dont need to have access the builders anymore and a seperate using block for each dependency is very user unfriendly.

ivory saddle
#

Does unity have a filedrop callback or is there any way I can get the functionality for it?

potent sleet
ivory saddle
#

Wait, Nevermind, I think I misunderstood something.

potent sleet
#

there is no built in method in unity for drag n drop

simple egret
#

But I wouldn't recommend as it's not clear on when the build actually happens

#

I'd stick to an explicit Build() method

restive ice
restive ice
#

now you can resolve that by for example returning something from the Build call and then checking if the value is returned

#

but that would again make the syntax of registering my dependencies more complex

rocky jackal
#

how could i smooth out the rotation ?

potent sleet
tepid charm
#

worst line of code I've written so far:

if (UnitManager.instance.soldiers.Find(x => x.index == buckets[(i) * sideTiles + j][i2].index).unit.team == soldier.unit.team)
simple egret
rocky jackal
restive ice
#

I want LocalContainer.RegisterDependency<FooBehaviour>() to throw an error

LocalContainer.RegisterDependency<FooBehaviour>().FromInstance(fooBehaviour)
to be the minimum

and then have optional builder stacking like be allowed

LocalContainer.RegisterDependency<FooBehaviour>().FromInstance(fooBehaviour).WithId("someId")

tepid charm
#

this one is also pretty ugly but not as bad

sorter.distance = (buckets[(i - x) * sideTiles + j + y][i2].transform.position - soldier.transform.position).sqrMagnitude;
restive ice
#

normally it makes sense that you would call a final Build() or whatever if you need to actually do something with what the builder returns, but for this framework syntax it makes it weirder

potent sleet
tepid charm
#

that gives me PTSD from rotation matrices

simple egret
rocky jackal
potent sleet
# rocky jackal yes and only arround the local forward axis

eg:```cs
Quaternion startRotation = transform.rotation;
Quaternion endRotation = transform.rotation * Quaternion.AngleAxis(-angleDifference, transform.forward);

float t = 0f;
float rotationTime = 0.5f;
while (t < rotationTime)
{
t += Time.deltaTime;
float normalizedTime = t / rotationTime;
transform.rotation = Quaternion.Slerp(startRotation, endRotation, normalizedTime);
}```

rocky jackal
#

this does smooth the rotation but now it does not only rotate arround the local transform forward it sometimes rotates arround all directions

rocky jackal
potent sleet
rocky jackal
tepid charm
rocky jackal
#

it behaves really weird but i think i can replace all the code with two joints

maiden junco
#

now it works

prisma roost
#

i was wondering if in this channel i can ask about mirror and fizzy steamworks coding or if thats another channel

slow grove
#

Hey guys, Iโ€™m making a 6dof flight system, but want to have players able to walk around the ship, and for ai to be able to pathfind in the ship. Iโ€™ve kind-of settled on two solutions:

  1. The ship the player is on stays completely stationary and at the origin, while the rest of the universe rotates/moves around it, but this has the issue of not really being able to make collisions work

  2. Parent player characters to the ship theyโ€™re on and actually move and rotate the ship, but this seems to have the issue of probably not being able to get ai pathfinding to work (though I havenโ€™t really tested it yet, this is just intuition)

Any advice on which one I should do?

haughty kiln
slow grove
#

With solution 1 (which is the one Iโ€™ve got) itโ€™s pretty painful to get the skybox to rotate correctly, and Iโ€™m honestly not sure how I would make the players ship collide with stuff

#

Also does it change anything if Iโ€™m not using a rigidbody character?

haughty kiln
#

You could feed rotation data into a skybox shader to spin it properly

slow grove
#

Iโ€™ll have to play around with that but seems much more sensible than what Iโ€™m doing

haughty kiln
#

With solution 1 if your obstacles have rigidbodies it's possible to have collisions but your ship would never move out of the world origin

violet cipher
#

` public Text scoreText;
int score = 0;

// Start is called before the first frame update
void Start()
{
    scoreText.text = score.ToString() + " Collisions";
}`
haughty kiln
#

I mostly just read that there was a collision and either destroyed/damaged and stopped my ship but I bet you could work out some way to do better collisions

violet cipher
#

why is this giving off a null freference exception

#

everything is defined

slow grove
#

Hm, Iโ€™ve tried adding rigidbodies to the obstacles but my ship just phases through them, would it be possible to make the ship bounce off of them?

violet cipher
#

but it says there is a nullreference exception at the line in VOID start

haughty kiln
tepid river
slow grove
#

Yeah, I think i need a custom skybox shader to be able to rotate in more than one axis though

haughty kiln
#

You could set it up in Shadergraph with a Vector3 as a property, it shouldn't be too difficult once you get all of the axis to match

#

You do lose some features because of that though because it will be your own skybox shader. So it would be a solid color unless you mapped a texture to it

slow grove
#

๐Ÿ‘ many thanks

haughty kiln
#

There will still be plenty of problems in the future but it's a step haha

tepid river
# slow grove ๐Ÿ‘ many thanks

also, i keep track of the scenes absolute universe postion with a double vec3, instaed of float3, because the floats with their precision issues where the cause for the whole ordeal.

dusk geode
#
//TODO: nicen up
        float targetFront = 0;
        float targetBack = 0;
        DebugExtension.DebugWireSphere(raycastAnchorPlane.position, 1f);
        if (Physics.SphereCast(raycastAnchorPlane.position, 1f, -raycastAnchorPlane.transform.up, out _, 1f, ~steeringRaycastIgnoreLayer))
        {
            Debug.Log("Grounded");
            TorqueUpright(relativeSurfaceNormal);

            //Vector3 axisInRaycastPlane = raycastPlane.ClosestPointOnPlane(axisBack.position);
            //Vector3 axisInAgentBodyPlane = agentBodyPlane.ClosestPointOnPlane(axisBack.position);

            agentBody.AddForce(
                agentBody.transform.forward * agentController.moveAxis.z * 5,
                ForceMode.Acceleration
            );
            targetFront = steeringParameters.axisMaximumDisplacement * agentController.moveAxis.x;
            targetBack = -steeringParameters.axisMaximumDisplacement * agentController.moveAxis.x;
        }
        axisFront.transform.localRotation = Quaternion.Euler(0, targetFront, 0);
        axisBack.transform.localRotation = Quaternion.Euler(0, targetBack, 0);```
anyone have an idea why my spherecast here does not seem to be true whenever I touch the ground ?
#

i have to awkwardly shuffle around over it for it to register

#

the white sphere is the spherecast

#

no the plane is not on the ignore layer

#

ah overlap sphere seems to be the choice here

cinder nymph
#

someone know why Bolt setup dont finish?
if i click generate it doesnt work and in visual scripting appear this:

left gale
#

Does a unity crash saying invalid scene handle, in a variety of different callstacks, usually actually trying to allocate memory either with physics or in renderables (ie, mesh geometry allocation), mean anything to you guys? My thought is that we are doing a lot of touching of entities off the main thread which is known trouble, but would it exhibit this sort of error? And secondly is there any sort of global hook for being notified or asserting when an entity is activated deactivated or it's scene changes or this sort of thing?

cinder nymph
#

!bug

tawny elkBOT
#

๐Ÿชฒ To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.

๐Ÿ“ If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click โ€˜Report a problem on this pageโ€™!

๐Ÿ’กIf your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.

For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting

left gale
#

?

#

It's the game that is crashing, not the editor. If that is suppose to be for my benefit

left gale
#

Why would I do that every time my game crashes?

cinder nymph
#

someone know why Bolt setup dont finish

slow grove
noble mortar
#

Does anyone know how I can make it so my text replaces the old text and the old text keeps it font?
I'm trying to make it so it seems like the mc is understand ancient text.
https://gdl.space/tumodocuro.cpp

slow grove
simple egret
median folio
#

Hello, I had an idea that I suspect will be above my skillset but wanted to give it a try anyway. So I'm using a third party asset called DoTween in my project to control the way certain objects move around.

I have recently learning about adding a layer of abstraction and wanted to give it a go. So that if DoTween ever goes under or I want to switch to a different system I only have one place to do this inside of.

Some of the use cases are easy like DoMove(amount to move) I can make my own method called MyMove which will just call DoMove.

Things get trickier with callbacks though, this is when doTween allows me to call a method on my script after a move has happened like this DoMove(amount to move).OnCompleted(method to call)

If I'm calling my own static MyMoveManager script how would I pass it my method on my current class ? Something like this maybe?

My Class:
MyMoveWithCallBack(Action callback, moveAmount)
{
DoTween.Move(moveAmount).OnCompleted( callback)
{
simple egret
azure heath
#

Can anybody see why this array keeps wiping itself? I'm baffled.

                        Debug.Log("Drop down.");
                        oneWayPlatArrayCached = oneWayPlatArray;
                        if (oneWayPlatDropActive) StopCoroutine(oneWayPlatDropCoroutine);
                        StartCoroutine(oneWayPlatDropCoroutine);

private IEnumerator OneWayPlatDropCoroutine()
        {
            oneWayPlatDropActive = true;
            IgnoreArrayOfCollisions(true, oneWayPlatArrayCached);

            yield return oneWayPlatDropInterval;

            IgnoreArrayOfCollisions(false, oneWayPlatArrayCached);
            oneWayPlatDropActive = false;
        }

        void IgnoreArrayOfCollisions(bool ignore, Collider2D[] collider2Ds)
        {
            for(int i = 0; i < collider2Ds.Length; i++)
            {
                if(collider2Ds[i] != null) 
                {
                    Debug.Log("Collider is named " + collider2Ds[i].name);
                    Physics2D.IgnoreCollision(box2D, collider2Ds[i], ignore); 
                }
            }
        }

Only the first IgnoreArrayOfCollisions() outputs a Debug.Log, and the collisions are never reenabled.

'Drop Down' only appears once in the console, so it's only being called once. I'm really confused.

median folio
buoyant mural
#

I have a coroutine which is running for some reason even after I stop it (and the bool that makes it get called is also set to true(which means it wont get called))
Here's my code (The coroutine IEnumerator Rotate): https://pastebin.com/itSEQqe8

dim spindle
#

It should just throw an error in console and or Player.log

icy inlet
#

I've been trying to tackle on slopes for the past years creating this game. I am out of options and this is as far as I could go.

Here are the two functions that are used for walking:

    public void Walk(float maxSpeed)
    {
        if(CanRotate)
        {
            CameraToForwardRotation();
        }

        if(!CanMove) return;

        Vector3 wishDir = SlopeItUp(dir);
        float acceleration = grAccel;

        wishDir = wishDir.normalized;
        Vector3 speed = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
        if (speed.magnitude > maxSpeed) acceleration *= speed.magnitude / maxSpeed;
        Vector3 direction = wishDir * maxSpeed - speed;

        if (direction.magnitude < 0.5f)
        {
            acceleration *= direction.magnitude / 0.5f;
        }

        direction = direction.normalized * acceleration;
        float magn = direction.magnitude;
        direction = direction.normalized;
        direction *= magn;

        rb.AddForce(direction, ForceMode.Acceleration);
    }

    public Vector3 SlopeItUp(Vector3 playerDir)
    {
        Vector3 finalDir = playerDir;

        if(OnSlope())
        {
            finalDir = Vector3.ProjectOnPlane(playerDir, slopeHit.normal);
            Debug.DrawRay(transform.position, finalDir, Color.cyan);
            // rb.useGravity = false;
        }
        // else
        // {
        //     rb.useGravity = true;
        // }

        return finalDir;
    }```

All functions are being called right, the ground check for slopes is right, everything is right, I think what's wrong is the actual calculation. I have no idea where I'm wrong here and why is it so slow to get back to running after stopping on a slope as shown in the vid.
#

i am once again going insane over this shit

#

i'll have to visit a therapist by the time im done with this

timid crater
#

Good evening! I need help with this error, I have been getting for days whenever trying to instantiate a player using Nakama multiplayer feature:

"spawnPoint.transform UnityEngine.UnityException: get_transform can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function."

It's a spawn function so it can't be in start or awake, here's the code:

public void SpawnPlayers(string matchId, IUserPresence user, int spawnIndex = -1)
    {
        Debug.Log("Spawning players..");

        //If the player is already spawned, return.
        //if (players.ContainsKey(user.SessionId)) return;

        //Define a spawn point for the player.

        GameObject spawnPoint = spawnIndex == -1 ?
            spawnPoints[UnityEngine.Random.Range(0, spawnPoints.Length - 1)] :
            spawnPoints[spawnIndex];

        bool isLocal = user.SessionId == localUser.SessionId;


        var playerPrefab = isLocal ? networkLocalPlayerPrefab : networkRemotePlayerPrefab;


        player = Instantiate(playerPrefab, spawnPoint.transform.position, Quaternion.identity);


        if (!isLocal)
        {
            player.GetComponent<PlayerNetworkRemoteSync>().NetworkData = new RemotePlayerNetworkData
            {
                MatchId = matchId,
                User = user
            };
        }


        players.Add(user.SessionId, player);

        Debug.Log("Adding the player to the dictionary.");

        if (isLocal)
        {
            localPlayer = player;
        }
    }
mossy snow
#

What's your question? Make sure SpawnPlayers is only called on the main thread like the error tells you. You are probably calling it in a constructor, but without any more context it's impossible to say for sure

mossy snow
icy inlet
icy inlet
#

let me look into that

timid crater
# mossy snow What's your question? Make sure SpawnPlayers is only called on the main thread l...

My bad I didn't make it clear, so why whenever I add a breakpoint to the player = Instantiate(playerPrefab, spawnPoint.transform.position, Quaternion.identity); line and hover over "spawnPoint.transform" this error pops up: "spawnPoint.transform UnityEngine.UnityException: get_transform can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function." Resulting in no player prefab being instantiated. How can this be fixed?

icy inlet
#

now the question is should i be even normalizing the direction

mossy snow
icy inlet
timid crater
mossy snow
#

you still need to account for the y component, but the end calculation just shouldn't affect horizontal velocity

icy inlet
#

but it doesnt seem to shoot up only on the y, it seems like it shoots up on all of them

#

i might be wrong hold on

mossy snow
true palm
mossy snow
#

looks like whatever you're using for matchmaking is invoking this callback on separate thread

timid crater
#

How should I invoke it in the main thread?

#

Or what is the main thread actually? I tried looking it up but couldn't understand

#

Is it something like this?

mossy snow
#

Maybe time to read up on threads. Yes something like that would work, or a script that checks a concurrent queue or something similar that you post work to. There are libraries to help also. What are you using for matchmaking? I would be surprised if it didn't address this, assuming it wasn't you that invoked the callback with Task.Run or something

icy inlet
timid crater
#

Would you recommend a better alternative for matchmaking besides photon? @mossy snow

mossy snow
mossy snow
#

What does OnReceivedMatchmakerMatched look like? the docs for this library look like everything should be awaited in the main thread context already

golden lichen
#

I have this super simple game where your character just follows your mouse, but I think it would be fun to be able to control the character through your webcam by tracking your hand positionโ€”is there a recommended plugin I should use for this kind of task?

mossy snow
#

hmm that looks fine, other than the lack of try/catch which maybe someday haunt you when you have invisible exceptions

golden lichen
#

I'm unsure what you mean by that
I created this game, so I think it's an original idea?

cold parrot
#

if its all you, you should 100% publish this (when its done)

timid crater
#

@mossy snow Have you tried Unity's Netcode, if yes what do you think of it?

golden lichen
#

currently I have a secret link on itch.io, but it's not published yet
I'd still like to add extra functionality, like the webcam hand tracking controls that I mentioned earlier

cold parrot
golden lichen
#

that's why I'm asking for recommendations

cold parrot
#

it looks fun and is very easy to understand

dim spindle
#

are you calling vampire survivors a meme

icy inlet
cold parrot
dim spindle
mossy snow
#

something is insanely broken there Meta

icy inlet
dim spindle
#

because uh thats a slightly large number

#

just slightly tho not like 10000000000x too big

icy inlet
#

lmaoo

golden lichen
# cold parrot the recommendation is to try all

there's no possible way I'm going to be able to "try all" (most of what I've seen is related to vr headsets, which is not what I want), is there at least a handful of plugins that are easy/popular?
I don't think any sane person would want to purchase every webcam tracking plugin in the asset store just to "try them"

icy inlet
uncut plank
#

better ask it on some kind of forum

golden lichen
#

oh, I see

icy inlet
#

@mossy snow i changed some things up, now the z and x are right (they are the same on normal ground), but the project on plane decides to make the Y 11 and not 30 as it should

eager yacht
#

I've seen this, but I am not sure how useful the resource is. https://www.youtube.com/watch?v=RQ-2JWzNc6k Most things I found are expensive, external hardware (Leapmotion, VR controller, AR glove/ring, etc), or are very expensive to run.

Visit http://brilliant.org/Murtaza/ to get started learning STEM for free, and the first 200 people will get 20% off their annual premium subscription.

In this video, we will learn how to track hands in a 3D Environment. We will write the Hand tracking code using python OpenCV and CVZone. From there we will transfer the data to our unity 3D Env...

โ–ถ Play video
#

@golden lichen didn't mention I guess

icy inlet
#

@mossy snow wait shit i just set the Y to 30 and it works??

icy inlet
#

well i shouldnt because 30 is only for when going up a slope and -30 for when going down, but this is actual progress

#

i guess ill math.sign the projectonplane?? hol on

noble mortar
oak viper
#

for some reason I cannot use ParentConstraints in script. Do guys have an idea why that is?

#

Its like visual studio doesnt know what it is

narrow summit
#

Namespace probably

#

using UnityEngine.Animations;

oak viper
#

thanks a lot. Thats it. wasnt aware of that.

open dome
#

can somone help me with this problem when I tried to load my game into a browser?

#

it is a multiplayer game

mossy snow
#

look at the browser js console like it says to see what the error was

narrow summit
#

Best guess would be that you're using something that isn't available on WebGL

open dome
#

it is an error 227

mossy snow
#

well that wasn't helpful. Does it run normally in editor or as a standalone build? Do you have any dependency that doesn't work in webgl?

open dome
#

It usually runs as a standalone build and it runs normally within both the editor in the build. I am not aware of any dependency that doesnt work in webGL.

#

I have created a project with a different version of the game and it has run fine

#

does the universal render pipeline work within WebGL?

mossy snow
#

the docs say yes

open dome
#

hm\

#

should I provide links to my scripts such as the playerManager, Launcher and playercontroller?

narrow summit
open dome
#

how do I view the logic?

leaden ice
#

your code is the logic

open dome
#

got it

open dome
#

I fixed the problem. I found out that one of the scripts had UI elements that were public variables, so I simply changed them to serialized fields

#

thanks for everyone who attempted to help

narrow summit
#

what

hard sparrow
#

Is there a way to do foreach key in _myDictionary or no? Foreach keyvaluepair doesn't let me modify the value.

#

And I don't see how to do a for loop

leaden ice
thorny onyx
#

whats the defaultvalue of a float playerpref?

#

and i see now i spelled score wrong lol

limpid crow
#

what is causing it?

somber nacelle
#

this is a code channel

thorny onyx
#

thanks

limpid crow
granite nimbus
#

is it possible to somehow make an ordered dictionary / hashmap? I want both mapping and iterating

solemn raven
#

hey,
is there is any way to curve the corner of an image within unity ?

#

is it possible to curve only 1-2 corners out of the 4 corners?

vagrant blade
#

No

#

The image is sprite based, you can't modify it. There are assets on the store they let you generate UI images to do exactly what you're asking.

vagrant blade
merry ridge
#

Does anybody have any advice for nested coroutines for resetting cooldowns? I would like to make my character have a cooldown reset if he collects a powerup while currently experiencing the same powerup. Say they pick up a speed up, and it lasts for 5 seconds. If they pick up another speed up during that 5 seconds, I want it to reset to 5 seconds again. Anybody know the best way to do this?

latent latch
#

You can save the reference to the coroutine and check if it's still running

#

if it is, stop the coroutine and start anew

slender nacelle
#

hi guys, whenever i exit play mode i get this error:

The property database "Library/Search/propertyDatabase.db" is already opened.
UnityEditor.EditorApplication:Internal_InvokeTickEvents ()
ive googled but not sure how to fix it, think it might be related to a crash im having

cobalt wave
#

check if the coroutine is still running and if it is set the cooldown to 0
no need to stop the coroutine and rerun it

hard sparrow
leaden ice
rain minnow
hard sparrow
#

Wouldn't thatt make it false..?

lunar forum
#

What does "=>" do? I've tried searching for it, but I can only find examples of it being used - not explanations of it.

leaden ice
#

it separates the parameter list from the body of the function

stable osprey
#

good practice is to try using => as much as possible

#

watch VS suggestions closely as it usually instructs on how to do so

lunar forum
#

Does it have a name?

leaden ice
stable osprey
#

we call it => ๐Ÿ”†

lunar forum
#

lol

#

Thanks

frigid shard
#

Is there a way to place battle music when an enemy is nearby or is in range?

west sparrow
#

Most definitely.

frigid shard
#

Or an enemy with no movement or action as of the moment

#

Like a dummy

west sparrow
#

Triggers, distances, raycasts, manual custom intensity etc.

frigid shard
#

Yeah but how do you turn the main music off once you get close to an enemy.

west sparrow
#

In our first horror game, all the audio is proceedural. We track how afraid we think the player is, and select visual and audio effects based on their anxiety, fear, and anger levels. So a heartbeat starts up, gets louder. Interacting increases possibility of audio playing audio clips etc. And fear spikes (seeing an alien) is what triggers big scare samples

#

You can check the distance to the nearest bad things, how far they are, their individual power, when you last saw one. So just tie the audio in that way.

A simpler approach is just to overlap trigger spheres when near a bad guy

Or just trigger new audio if you become visible or detected (metal gear style)

frigid shard
#

And when you defeat it the main music goes back?

latent latch
#

It's up to however you want to code it

#

Usually games do a fade on music transitions instead of* instantly/abruptly playing the next track

west sparrow
#

Yeah. In our case, anxiety slow reduces if you haven't seen anything scary in a while. Some things, like a flickering broken tv, still adds hidden fear. So it's environmental. But you can control all of that depending on the project

#

Just gotta code it ๐Ÿ™‚

frigid shard
#

So just basically just look up tutorials how to do music properly?

#

And give it a test?

frigid shard
#

Also how do you make Lego like damage. To where once they die pieces scatter and disappear for a few seconds and Lego builds?

worldly hull
#

normally its extremely hard to do procedual generating of those effects

#

ppl normally will break the model to pieces , and align them to make them look like a whole

burnt shore
#

hey does anyone know how to fix this

#

i dont know how to fix it

worldly hull
#

when u need it to scatter, just scatter them

frigid shard
worldly hull
worldly hull
frigid shard
#

Like do I just make the part of that body invisible. But wouldn't that make a more lag with the rig being on the floor everywhere?

#

Oh wait nvm.

#

Yeah I'm a newbie to this.

chilly beacon
#

i am experiencing extreme lag spikes when generate perlin noise values my noise map is around 400 by 400 ish and i think unity is rendering the entire map at once, what steps should i use to optimise this make a chunk wise rendering or render area up to players visibility or the area of the camera is only rendered at a time? kind of new any ideas

leaden ice
#

Unity already performs Frustum culling by default so the "only render the area of the camera" thing happens automatically

cosmic rain
chilly beacon
#

When I generate a randomly using left click it gives me a huge lag spike for 3secs

cosmic rain
#

That still doesn't tell us much. You'll need to share the relevant code. Or even better, do the profiling first and share the profiling results.

cobalt wave
#

I think they are asking you "how" are you generating perlin noise

chilly beacon
#

The thing is currently my map size is not exactly what I want I want the map to be alot bigger and I don't know how I could optimize the lag issue

cosmic rain
chilly beacon
dim spindle
chilly beacon
#

the thing is that i currently generate a map of the size of 100 x 100 tiles

#

and this small ends up give a bit of lag

#

and my plans are to have a world the sze 800 x 800 tiles

#

and when i do try to generate a world of that size it takes like a solid 30 seconds to just generate

#

and ends up being too laggy to even move around the player character

#

this is my inspector window

cunning shard
#

Does Unity provide any way to prevent a Rigidbody from colliding with a specific layer by instance?

quartz folio
#

There are layer overrides on rigidbodies, yes

cunning shard
#

Am I missing something lol

leaden ice
cosmic rain
cunning shard
#

yeah that's the actual issue

#

I'm using Unity 2020.3.36f1

quartz folio
#

Then no, you have to use the layer the gameobject is on

chilly beacon
cosmic rain
cunning shard
quartz folio
#

Just change the layer? What are you asking?

cobalt wave
#

@chilly beacon the initial lag is caused by the for loops which is "okay" since you do sort of have to have a loading time in a game, it's expected.
I don't know why it lags during runtime though, it should only lag when you press the mouse button, or in other words, when you generate the world.

cunning shard
#

Yeah, I'm gonna change the layer, how does it prevent them from colliding with other layers?

quartz folio
cunning shard
#

Lemme do the funny, never looked at the collision matrix

chilly beacon
cobalt wave
#

not really

#

I guess you could try using some optimizing tehniques, but I don't know any for loops

cosmic rain
#

You could also profile your current implementation and try to optimize the bottlenecks, but there's a limit to how fast you can get it with one CPU thread.

cunning shard
#

Let's say Layer1 is gonna instantiate a Layer3, Layer1 shouldn't be hit by Layer3, whereas Layer2 should be hit instead.
Same goes for Layer2 instantiating a Layer3 and doing the funny with Layer1.

leaden ice
cunning shard
#

Something like that

leaden ice
cunning shard
#

Yeah but that requires two colliders

leaden ice
#

?

#

yes the two colliders you want to not hit each other

cunning shard
#

Well uh

#

I'm not currently using a collider aside from Rigidbody

chilly beacon
cunning shard
#

Shouldn't Rigidbody have a collider?

leaden ice
#

so you don't have a problem

cunning shard
#

Bruh dum momento

#

Nvm, I was brain-lagging

cosmic rain
cobalt wave
#

not alot will be gained by profiling

cosmic rain
#

By profiling they can see how many iterations of what calls take what time.

cobalt wave
#

they can't really make it much more efficient, the loops are the problem because if you look at the code (no need for profiler) you can see that they have 6 different double nested loops, all that have 10000 calls

cosmic rain
#

It could be even something unexpected, like massive GC allocations

cobalt wave
#

which adds up to 60000 calls a frame

#

so yea, you can optimize the inside as much as you want, but the inefficient writing is the problem

cosmic rain
cobalt wave
#

if you look at the code you can see that they can't really optimize the inside of the loops too much because they are already doing what they need to do

#

you could gain maybe a few fractions of a millisecond, but that improvement still gets overshadowed by the fact that there are 6 different loops that all do different things (meaning you would need to optimize each loop). even if they shaved away a few fractions of a ms, the overall time taken will still be (6 x 100 x 100)

#

my bad

#

but arguing about this doesn't matter, since just tidying up the code will speed it up

cosmic rain
#

I'm not saying that in this current situation, they can optimize a lot the inside of the loops.
But profiling would make it easier for them to see what the issue is. It is fine if you can figure it out just from reading the code, but it's not always possible. They should learn how to use the profiler even if in this particular case, it's already clear what the issue is.

#

Or are you gonna review personally every single script they share and tell them what the issue is? Teach them how to fish, don't give them the fish.

cobalt wave
#

I'm not saying that, I'm saying that the profiling in this case is useless because the reason is beyond obvious
digging with the profiler while not understanding the fundemental problem of using too many loops for using necessary complex tasks will only send you in a rabbit hole of insanity because you'll be shaving off insignificant amounts while ignoring the very simple problem

#

profiling is great if you eliminated everything else

cosmic rain
cobalt wave
#

also I missed a loop
it was actually 300000 calls
with the code I sent it should be only 50000

swift falcon
#

is there way to add mod support to your game

potent sleet
chilly beacon
thin aurora
rustic ember
#

I have two MonoBehaviour scripts, let's call them "Health" and "AICharacterController". I want the AICharacterController to listen for updates to a variable in Health. Is this possible, and if so, how?

somber nacelle
rustic ember
#

I am trying to learn new things after I realized that I am kind of stuck in my ways

potent sleet
next sparrow
#

HI everybody, I'm trying to split my dynamic textures load so that my game freezes less but I'm a bit confused about how to proceed. From what I understand, there seem to be two ways to handle this, load asynchronously or using multithreads. Is that correct? Let's say I need to load 10 textures of 4Mo on average, if I use File.Load, then the game would load them one by one and hang until all of them are loaded right? If I load them asynchronously, will it avoid this freeze?

rustic ember
potent sleet
lunar lynx
#

im trying to use layermasks in code, where all layers are affected except Ignore Raycast layer.
do I input in c# the binary representation of 111011, 110111, or their decimal equivalents?

#

*i know ignore raycast layer is automatically ignored, but assuming i want to do it thru code

plucky inlet
#

you need bitcasting afaik, or you just use a pbulic layerMask property

#

bitshift, not cast ๐Ÿ˜„

lunar lynx
#

is bitshifting the only way? seems like a hassle to mix a collection of ands and ors ๐Ÿ˜ญ

somber nacelle
#

just use a LayerMask variable

lunar lynx
#

I have tried using public layerMasks and they work fine, but it makes the organization messy

plucky inlet
#

Did you read the link? You can just tell the layer int and bitshift it to a layermask to use it

lunar lynx
#

yes, I've read about bitshifting, but the issue is requiring multiple 1's not in sequence

#

so youd need a colletion of and and ors

somber nacelle
#

or just use a LayerMask variable and the ever so convenient LayerMask.GetMask method

next sparrow
plucky inlet
lunar lynx
#

yeah

#

a list of layermasks

latent latch
#

Yeah, don't use literals for the masks because once you change them on the inspector then you've got to change them all in your code.

lunar lynx
#

oh yeah ok good idea

cobalt wave
knotty sun
swift falcon
somber nacelle
next sparrow
#

I'm using a coroutine to load the texture using UnityWebRequest

#

`
UnityWebRequest uwr = UnityWebRequestTexture.GetTexture("file://" + path);

    yield return uwr.SendWebRequest();

    if (uwr.result != UnityWebRequest.Result.Success)
    {

//Error
}
else
{
// Get downloaded asset bundle
Texture2D tex = DownloadHandlerTexture.GetContent(uwr);
}`

#

This is my coroutine, from what I found online. Textures do load but still some freeze. I was expecting something a bit smoother, like the character still playing the animation and the texture filling little by little like some games do

cold parrot
next sparrow
cold parrot
next sparrow
#

Hm, so if I want to make it faster I'd need to add some multithreading ?

#

Is it possible?

cold parrot
#

Not really

#

Multithreading is already there (internally) if you use webrequest

next sparrow
#

Ah I see

cold parrot
#

Best you can do is load images as structured byte arrays (DDS) and write those directly into a preallocated texture

next sparrow
#

Ok, just one last question then, what takes more time, the texture loading or the texture init ?

cold parrot
#

Depends on how big the image is, itโ€™s format and where you load it from. Typically though, the decompression (jpg/png) takes the longest (assuming SSD on the local PC)

next sparrow
#

Ok, and the decompression happens only once during loading then?

cold parrot
next sparrow
#

Got it, thanks!

kind tide
#

hey guys

swift falcon
#

Hello guys, I am wondering if someone can help me with a question about null handling. Is a simple null check with an if statement the standard in Unity or using C# try and catch (error handling system) a better practice?

plucky inlet
#

avoiding null would be best practice, but if you cant avoid it for some reason, having a simple null check is totally fine

hard estuary
# swift falcon Hello guys, I am wondering if someone can help me with a question about null han...

NullChecks seem to be better for scenarios where you want to have an individual reaction to each possibility. E.g.:

if (renderer == null)
  renderer = GetComponent <Renderer>();
if (collider == null)
  collider = GetComponent <Collider>();
if (stats == null) 
  Debug.LogWarning ("Stats variable is not set up in GameObject: " + name, gameObject);

TryCatch seems to be better if you want to cover a bigger area of code with a single reaction. Also, TryCatch is pretty neat if you're using methods you don't want to modify.

swift falcon
#

@hard estuary so for simple object collisions a try-catch will be a little overkill I guess

#

So for simple code this:

Player player = other.GetComponent<Player>(); if (player != null) { player.damage(); }

Is better than this:

try { player.damage(); } catch (NullReferenceException err) { Debug.Log("Object other is Null"); Debug.Log("System Message: " + err); }

#

Thank you both

thin aurora
# swift falcon Hello guys, I am wondering if someone can help me with a question about null han...

Do not try-catch expected behavior in your code ever. You are always able to check beforehand if certain conditions are met, and bail out of execution if predicates meet. Try-catching exists to handle unexpected exceptions in your code that do not happen under normal circumstances , and the point is properly informing users and handling the code in an alternative way if it can be saved. Throwing exceptions is also costly on performance.

plucky inlet
#

If you get a null error, you SHOULD get it to know your code is not optimised very well. Guessing that you might have an object or not is a bad habit of avoiding errors ๐Ÿ˜‰

faint horizon
#

Hi there. Does anyone know how I can set the default parameter for a Vector2 to zero when passing it via function parameters? I've tried the following but I get an error.

#

public void init(Vector2 pos = Vector2.zero) { }

faint horizon
#

Oh I see

#

OK that makes sense. Thanks ๐Ÿ™‚

thin aurora
thin aurora
#

Google "reference" types and "value" types. It's very useful to understand the differences. Reference types are null by default and value types can't be null @faint horizon

faint horizon
#

@thin aurora So if I want to pass nothing via the parameters would this still work?

thin aurora
faint horizon
#

OK yes that's worked

#

Thank you ๐Ÿ™‚

plucky inlet
#

seriously? you owe me 10 second sof my life ๐Ÿ˜„

thin aurora
plucky inlet
#

So you want the next state?

#

Or any?