#archived-code-general

1 messages · Page 118 of 1

granite nimbus
#

Couldn't create 'C:!my\gamedev\unity-projects\testing-package-template\Packages\com.company-name.package-name/~UnityDirMonSyncFile~44d261d1b2c0f344499aeafe0c15a0ca~'

ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.UIElements.PropertyField.<CreatePropertyIMGUIContainer>b__43_0 ()
// etc...

first is yellow warning, second is red exception

steady moat
#

Is it in the package ?

mighty vigil
#

Events ❤️

steady moat
#

And what is the object throwing the error ArgumentNullException: Value cannot be null. ?

granite nimbus
steady moat
#

You cannot do that.

granite nimbus
#

cannot do what?

steady moat
#

Delete folder in [project-root]/packages/[some-package]

granite nimbus
#

the reason being?

steady moat
#

THey are managed by unity.

#

Same if you could, they would be regenerate each time.

granite nimbus
#

?

#

in packages there are embedded packages

mighty vigil
#

Those are your unity project packages that are handled by the unity package manager

steady moat
#

It is package.

granite nimbus
#

not ones downloaded through PM

whole dawn
mighty vigil
granite nimbus
#

I have full moral rights to modify them

#

they are not in packagecache

steady moat
mighty vigil
steady moat
#

That being said, deleting folder works correctly

#

I have done it several time.

#

So, your issue is something else.

#

Maybe there is editor code running while you do your operation and it does not like it

granite nimbus
steady moat
#

So beware.

granite nimbus
mighty vigil
#

Events are useful for cases where you'd want X happening as soon as Y happens, and you don't want to constantly check whether Y happens, so when Y happens it simply triggers an event that would make X happen.

At least that is my rudimentary understanding of events

@whole dawn

static matrix
#

Question: When you asynchronously run a function, does it also asynchroiously run all functions called by the function?

whole dawn
restive dirge
#

Hi does this make any sense getting the component interface of a gameobject when ontriggerd?(ie, the triggerd gameobject implements an interface, can we get that interface and call a function )

mighty vigil
granite nimbus
#

yeah maybe I have to mess with PM somehow, but I don't know how

mighty vigil
#

Something like updating UI is a great use case for events

granite nimbus
#

doing PackageManager.Client.Resolve() doesn't do anything

#

🤯

whole dawn
mighty vigil
#

Events are used to ensure more control over order of execution, yes

#

But "simultaneous" is a word I'd like to avoid

paper mirage
#

Is there a way to make a public variable readonly to other scripts, but writable when serialized in inspector?

#

In essence I need something like a property with a public get and private set, but also serializable so that private set can be used via Inspector

primal wind
#

I don't think it possible, you would have to make two variables

paper mirage
#

Ah, that's too bad

granite nimbus
#

in OnValidate for example

paper mirage
#

I found a way, actually

[field: SerializeField]
public float FloatProperty { get; private set; }
#

the "field:" prefix makes the property serialized

#

And you can set its value in inspector

quartz folio
#

it makes the backing field serialized

granite nimbus
paper mirage
#

yeah

quartz folio
#

Which is a distinction worth making because when you need to ever refactor that property into a full property then you're going to have to move the attribute and add FormerlySerializedAs with some weird syntax

paper mirage
#

but it's just less code than doing it manually

paper mirage
#

I choose to not use that method anyway though, as properties also don't jive well with attributes

#

I like my headers

quartz folio
#

(it's serialized as <PropertyName>k__BackingField for anyone wondering)

granite nimbus
#

wtf is the k__ naming convention though

quartz folio
#

🤷 some internal C# choice that presumably means something

sweet perch
#

idk if this is the right place to ask this, but does anyone know what these warnngs mean?

[Worker0] To Debug, run app with -diag-job-temp-memory-leak-validation cmd line argument. This will output the callstacks of the leaked allocations.

[Worker0] Internal: There are remaining Allocations on the JobTempAlloc. This is a leak, and will impact performance

#

tried googling, there are some threads but its just everyone stating that they had the same issue and that updating editor fixed it

#

but im on the latest editor version

amber heart
#

It there a way to have differing custom code between scriptable objects of the same type?

#

For instance an OnUse method on different instances of an Item ScriptableObject

#

Or should I have additional Scriptable Object classes that inherit from Item that have their own defined behaviour?

mystic yoke
potent sleet
#

this aint a code question bud

steady moat
amber heart
icy inlet
#

How the hell am I supposed to put in the T type of IPlayablebehaviour without adding "where T : class, IPlayableBehaviour, new()" to the function im calling GetBehavioursAndBindings with? (It's an Input System event response so i cannot specify the generic class so I end up in a paradox)

            Dictionary<UnityEngine.Object, List<IPlayableBehaviour>> behavioursAndBindingsFromTimeline = new Dictionary<UnityEngine.Object, List<IPlayableBehaviour>>();

            PlayableUtilities.GetBehavioursAndBindings<IPlayableBehaviour>(currentTimeline, behavioursAndBindingsFromTimeline);```
Start of GetBehavioursAndBindings:
```cs
public static void GetBehavioursAndBindings<T>(PlayableDirector director, Dictionary<Obj, List<T>> behavioursAndBindings) where T : class, IPlayableBehaviour, new()```
topaz ocean
#

The other day someone said that its a bad idea to reference the skinnedMeshRenderer component that comes with a FBX prefab, what is the logic behind this?

icy inlet
#

how is it a bad idea

topaz ocean
#

Im not sure

#

I think simferoce said it

#

Im divided on this because the point of the fbx prefab is to allow proper configuration of an imported mesh, it feels a bit roundabout if instead I approached it by separating it into mesh and material references to assign when I create a new skinnedMeshRenderer

icy inlet
#

it depends on what you are trying to change

#

within the skinned mesh

#

if you need to change an instance of a material then sure

#

im not sure why you would need to access it

plush ledge
#

hi so i'm working on a weird lil thing where this cursor can select objects, but because of how i've done the code it selects both and I know why (charactercontrollers are disabled at the start and enabled when selected, just both charactercontrollers get enabled when I need to enable one and I don't know how to separate them lol) I just don't know how to fix it as i'm quite new

plush ledge
# potent sleet show code
public class MagicMovement : MonoBehaviour
{
    public float speed = 6.0F;
    public float rotatespeed = 3.0F;
    Vector3 moveDirection = Vector3.zero;
    CharacterController controller;
    Rigidbody rb;
    public bool ObjInUse;
    bool triggered = false;

    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
        rb = GetComponent<Rigidbody>();
        ObjInUse = false;
        controller.enabled = false;
    }

    
    // Update is called once per frame
    void Update()
    {
        if (triggered = true && Input.GetButtonDown("Select") )
        {
            ObjInUse ^= true;
            controller.enabled ^= true;
        }
        


        if (controller.enabled == true)
        {
            rb.isKinematic = true;

            moveDirection = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Depth"), Input.GetAxis("Vertical"));
            moveDirection *= speed;

            transform.Rotate(Input.GetAxis("VerticalRotate") * rotatespeed, Input.GetAxis("HorizontalRotate") * rotatespeed, Input.GetAxis("DepthRotate") * rotatespeed);

            controller.Move(moveDirection * Time.deltaTime);
        }

        if (controller.enabled == false)
        {
            rb.isKinematic = false;
        }
    }

    void OnTriggerEnter(Collider collision)
    {
        Debug.Log("Entered");
        triggered = true;
    }

    void OnTriggerExit(Collider collision)
    {

        Debug.Log("Exited");
        triggered = false;

    }

    }
plush ledge
potent sleet
#

you need to make an external scripts which activates/deactivates this script if they have the same one

#

idk how your selection is based on

#

option : Put them in a list, scroll through indexes.
option : Use a ray for selection
option : if it's just those two make the external script do the bool toggle on it

plush ledge
#

but I can work with those options

#

thanks

potent sleet
#

ok gl

tawny mountain
#

Can I prevent collision detection while game is paused?

earnest gazelle
#

How do you avoid mutual dependency (cycle) in this situation?
A building can be damaged by specific animals/enemies.
An enemy/animal can damage specific types of buildings.
Defining an intermediate data structures?

// Mutual dependency
public class AnimalDefinition{
   public BuildingDefinition[] TargetBuildings;
}

public class BuildingDefinition{
   public AnimalDefinition[] DamagedByAnimals;
}
public class AnimalDefinition{

}

public class BuildingDefinition{

}

public class IntermediateDefinition{
   public DamageData[] DamageList;
}
public class DamageData{
   public AnimalDefinition Animal;
   public BuildingDefinition Building;
}

If they change to building and animal groups (enums)

public class AnimalDefinition{
   public BuildingType[] TargetBuildings;
}

public class BuildingDefinition{
   public AnimalType[] DamagedByAnimals;
}
late lion
#

Because usually you would just pick one place to store it, whichever place you think you'll need to access it from more frequently.

#

For example, I might say that Orcs and Goblins are resistant to Fire damage by storing that in their respective definitions, but I wouldn't feel the need to also have a list of those creatures in the FireDamageDefinition.

#

Okay, maybe there's a feature in the game where you can browse creatures based on damage resistances, but then I'd rather go a database and query route.

earnest gazelle
#

I know I can get the other one by another one

earnest gazelle
#

It is logical to put them just in Animal class

late lion
#

I don't like it because it allows for invalid data if desynced.

earnest gazelle
#

Yes, exactly, thanks

#

It solves cyclic dependency but the main problem remains

late lion
#

One question, would it be too limiting if you could only define up to 64 types of animals and 64 types of buildings? If not, you could solve this similarly to how physics collision layers work, with a matrix.

#

The matrix would have to be stored in some central location then, instead of in either the animal or the building.

earnest gazelle
#
public class IntermediateDefinition{
   public DamageData[] DamageList;
}
public class DamageData{
   public AnimalDefinition Animal;
   public BuildingDefinition Building;
}
#

like defining another table to connect both models to each other (n:n)

unkempt shuttle
#

Does anyone know the correct way to calculate the translationOffset for a scripted PositionConstraint? I know it needs something like (target.postion - constraint.gameobject.transform.position) or similar but everything I've tried with adding rotations, inverse rotations on the constraint * position offset, etc hasn't worked. This is for a position constraint, not a parent constraint.

leaden ice
#

Or whatever offset you want, since you're scripting it

#

Rotations etc aren't relevant unless you're going for some specific thing

unkempt shuttle
#

My guess is it isn't as simple as just using positions if there are rotations on the constrained object and the target object

#

Seems like there is something more

languid hound
#

Is there anywhere I can look to get / create smooth movement like Doom? Rigidbody movement while yes is similar is not what I want. Figuring out how to go up stairs is a whole different thing but I cannot for the life of me get the really good accelerating and decelerating

#

I tried playing with physics materials and while yes it can sort of create while I want staying on diagonal surfaces cause the player to slide down

#

I might have to write my own acceleration and deceleration I suppose

heady iris
#

you probably want a character controller

#

doom's movement is not perfectly physical

leaden ice
ember wedge
#

!code

tawny elkBOT
#
Posting code

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

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

unkempt shuttle
glossy cobalt
#

having troubles with composite colliders in 2D, it's breaking a few things in my game.
I have a tilemap with a composite collider, but objects interacting with the collider have weird physics, even though it's a straight line. for example, the player character's y velocity is always between -2 and -3, which breaks code I had written a long time ago.
the weirder one is when my character attacks, it instantiates a sword prefab that has a box collider set to Is Trigger, but this now my x velocity goes from anywhere between 1 to 9.
the issue is coming from composite colliders, as when I turn the composite off and use tilemap collider, these are not issues anymore. same with box colliders, etc.
where can i learn more about composite colliders and why this is happening? this feels like it shouldn't be happening, and I don't know what to do besides use tilecolliders, which is very inefficient.

grizzled needle
#

Does Physics.SphereCast end at the given distance or does it end at the given distance + radius?

#

like, if I want the absolute end of the spherecast to stop exactly at a distance, do I need to do distance - radius?

heady iris
#

i believe the distance is how far the sphere travels

#

the sphere starts centered on the origin

haughty ember
#

I just have a general design question about player health and "game over". Assuming I am using a GameManager script, is it typically better practice to just store the player health and change it in the GameManager, or to keep track of the player health in a script on the player itself, and when that health goes to 0, we call some sort of game over function on the game manager?

heady iris
#

i do the latter

#

oftentimes, I don't really have a distinction between the player and enemies

#

they're all just Entities or whatever

#

i'll have an "OnDeath" event on the entity class

#

the game manager subscribes to this event on the player

hidden parrot
#

Yeah just have an entity class that enemies/player derive from and you can have health, killentity and stuff

#

I also usually keep an IDamagable interface for stuff so I can handle damaging stuff for specific entities easier

swift falcon
#

Hey.

Just looking for any recommendations on a (free) cloud database that's compatible with unity. Making a project and I need to store credentials alongside data related to each person, and then be able to grab that in unity. I heard firebase is pretty good, but i'm not sure if that's just Android/IOS. I need it for PC.

void basalt
#

I assume since you're already hosting the servers, that you have access to some sort of host

void basalt
# swift falcon I'll look into it.

In terms of free stuff, you get what you pay for. There's probably nothing preventing them from wiping your data whenever they feel like it

lean sail
lean sail
#

firebase also has paid storage

#

also i really hate how firebase data is accessed, but it is quick to setup which is why i used it

void basalt
#

OVH has VPS for $7 a month. 40GB storage, 250mbps lines, unlimited transit, raid backups

#

That's really all you need.

haughty ember
#

I guess my only worry with the latter approach is that in my mind it seems like nothing should be able to just use the game manager functions whenever it wants. Like any game object just having public access to the game over function in the game manager seems like bad practice. Am I wrong about this? Still very new to unity (but not new to coding, new to C# though), and just trying to avoid bad coding practices

swift falcon
#

It wont be managing a huge amount of data, so it should be alright.

vagrant agate
#

Can someone take a look at this and tell me how to clamp deltaRotation by startAngle and endAngle during the while loop properly ?
its like as soon as the rotation is > 0 it starts doing a full 360, then proceeds to the intended rotation.

private IEnumerator RotateNeedle(float value)
    {
        //value is 0 to 1
        //0 = 85f
        //1 = -85f
        
        var startRotation = needleIndicator.transform.eulerAngles.z;
        var targetRotation = Mathf.Lerp(startAngle, endAngle, value);

        var t = 0f;

        while (t < 1f)
        {
            t += Time.deltaTime / duration;

            var smoothStep = Mathf.SmoothStep(0f, 1f, t);
            var currentRotation = Mathf.Lerp(startRotation, targetRotation, smoothStep);

            //delta rotation from current to target
            var deltaRotation = Mathf.DeltaAngle(needleIndicator.transform.eulerAngles.z, currentRotation);

            //update rotation
            needleIndicator.transform.eulerAngles += new Vector3(0f, 0f, deltaRotation);

            yield return null;
        }


        _rotationCoroutine = null;
    }
hollow isle
#
Quaternion lookRotation =  Quaternion.LookRotation(target.position, transform.position);
wandPivot.transform.rotation = Quaternion.Slerp(wandPivot.transform.rotation, lookRotation, Time.deltaTime * turnSpeed);

can anyone help me figure out why it's rotation my lil guy here upward? I'd like to lock it to the y axis instead of doing a bunch of weird stuff like it is now.

tiny reef
#

i want to use Rider as my IDE but everytime i restart unity it gets reset to vs code

solemn raven
#

Hi ,
does anyone knows how I could loop throw a txt document and replace some variables in it ? like replacing all [Name] by _name and all [Age] with_age ... etc
i have like 40+ values to replace

fervent furnace
#

string.replace

solemn raven
# fervent furnace string.replace

but it doesn't work with multiple strings , does it ? i have to loop through the whole doc for each variable ? is there is any better method ?

fervent furnace
#

i already forgot how i would handle this, handling c string is annoying
suppose you have a string[][2] table which means for each table[i][0] have to be replaced with table[i][1] in docu (let call it char*A)
first allocate a vector (char*B) (dynamic size char array) then using two pointer scan every word in A and copy to B depends on whether the word is in table

#

for faster look up time you may need a trie or hashtable

#

since you dont know whether the length of table[i][1] is longer than table[i][0], in-text replacement may not be possible to do

cyan lodge
#

Code:

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

public class CameraHolderScript : MonoBehaviour
{
    public Transform player;
    float smoothTime = 12f;
    bool isFirstPerson = true;
    bool isSmoothingToFirstPerson = false;

    // Update is called once per frame
    void Update()
    {
        if (isFirstPerson && !isSmoothingToFirstPerson)
        {
            transform.position = player.position + player.transform.forward * 0.45f;
        }
        else
        {
            Vector3 normalTargetPos = player.position + player.forward * -11 + Vector3.up * 1.5f + player.right * 3;
            Vector3 smoothedPos = Vector3.Lerp(transform.position, normalTargetPos, smoothTime * Time.deltaTime);
            transform.position = smoothedPos;
        }
    }

    public void NewCamModeIsFirstPerson(bool firstPerson)
    {
        if (firstPerson) isFirstPerson = true;
        else isFirstPerson = false;

        smoothTime = 25;
        StartCoroutine(SetSmoothTime(12f, 0.2f));

        if(isFirstPerson)
        {
            isSmoothingToFirstPerson = true;
            StartCoroutine(SmoothToFirstPerson());
            Invoke(nameof(ResetIsSmoothingToFirstPerson), 1f);
        }
    }

    IEnumerator SetSmoothTime(float value, float waitTime)
    {
        yield return new WaitForSeconds(waitTime);
        smoothTime = value;
    }

    IEnumerator SmoothToFirstPerson()
    {
        int a = 0;
        while (isSmoothingToFirstPerson)
        {
            Debug.Log(a);
            a++;
            Vector3 normalTargetPos = player.position;
            Vector3 smoothedPos = Vector3.Lerp(transform.position, normalTargetPos, 20 * Time.deltaTime);
            transform.position = smoothedPos;
            yield return new WaitForEndOfFrame();
        }
    }

    void ResetIsSmoothingToFirstPerson()
    {
        isSmoothingToFirstPerson = false;
    }
}

lethal plank
turbid surge
#

Not sure how much that would help but Slerp is designed for them, fairly sure

cold parrot
turbid surge
#

My bad 👍

shut fiber
#

I need to have an object rotate over time and slow down the speed at which it is rotating.

The object needs to rotate for exactly 10 seconds and end up at the rotation value of X (greater than 360, measured using rigidbody.rotation)

I am guessing I need to do some sort of physics calcultions using rigidbody.angularVelocity and angularDrag, but I do not know any physics at all and no idea how I would approach this. Any advice?

cerulean stag
#

Hi, I've been experiencing a serious error with Unity for a while.
I'm using LTE 2021.3.25f1. There are no stack traces tied to this error - this is all that is displayed
Assertion failed on expression: 'm_BufferData.capacity() >= m_WriteOffset + bytesWritten'

It seems to affect LineRenderers, TrailRenderers, and UI (see video). Restarting Unity seems to fix the problem but it always ends up coming back eventually. Gameplay doesn't seem to be affected by this but I'll have to check again later to see if it does.
I'm using the A* Pathfinding Project by Aron Granberg if that helps. There are no exceptions in my code and the A* pathfinding package is functioning properly. The game is using URP. I have tried re-importing. There aren't any Google results about this specific error so please help I'm at my wits end trying to figure out what's going on 🥲

prisma plover
#

why it gives me this error:
CS0527 Type "IJob" in interface list is not an interface

rotund burrow
prisma plover
#

also, is this a unity bug?? it was there since i created new sub scene

fervent furnace
#

if you are quite sure that you have free()ed all the memory allocated then it may be unity bugs.
since if i havent dispose a persistent native container it will pop up a error instead of a message, idk why

prisma plover
#

it was 40 allocations since created new project

#

i wrote some ecs code but its still 40

#

so if its really an unity bug

#

i should wait for some editor fixes

#

my knowledge from past unity lts versions:
If you want to use a stable unity version, use a lts version that got at least 10 fix updates.

random crane
#

How do I make raycast visible when I use draw raycast? I heard in a Youtube video all you have to do is turn on gizmos but it wont work.

turbid surge
#

Gizmos do have to be on

random crane
#

I did draw line but it wont show up

fervent furnace
#

Try turn on the gizmos icon

turbid surge
#

Are gizmos on in gamme view

#

Yeah they're not turn them on

random crane
turbid surge
#

Is separate for scene and game view

random crane
#

oh

#

I taped it and it wont do anything

fervent furnace
#

You didnt assign the time

random crane
#

wdym?

fervent furnace
#

There is a duration after the color parameter

#

Use a time.deltatime for it to see if it is drawing

random crane
#

like this?

fervent furnace
#

Yes

random crane
#

it still not working

#

oh nvm I think I found the problem

#

it was cause I only had it called when I hit space

fervent furnace
#

Then you can have a longer duration maybe 1 second

random crane
#

I found out I dont need the time perameter I just called the method every frame

#

thx for the help tho.

near crown
#

Hello! I wanted to make an aracade-like driving game, for that the code isnt that complicated, but I wanted that the car doesn't turn over when rotates at high speeds. I tryed myself by limiting the strenght of rotation, the faster you go, but still it turns over. Any suggestions?

turbid surge
near crown
#

nope

turbid surge
#

Rigidbody based?

near crown
#

Yes

turbid surge
#

You can limit the rotation on z

#

In rigidbody constraints

near crown
#

but my car goes weird when i do that

#

I'll send you a video

turbid surge
#

Ok

near crown
#

huh

#

I tested RQ and seems to work fine

#

maybe last time I tested the code was different

#

Grazie @turbid surge!

turbid surge
#

👍

near crown
#

@turbid surge nm

#

My car when it rotates for some reason

turbid surge
#

Send videos

near crown
#

The Z rotation increments

#

slightly

turbid surge
#

Send code and videos

near crown
#

Now, this is slightly increasing

#

I did a test before, and it turned up to 30 degrees

#

before the car reset

#

ngl the car movement though felt a bit restricted when I put the Z restriction

turbid surge
#

It's this

#

You shouldn't be using transform.rotation if you have rigidbody

#

use _yourRigidbody.rotation

near crown
#

aight lets give it a try

#

uhh but Rigidbody.rotation is a quaternion

#

I have a Vector 3 here

#

can I just do eulerangles?

turbid surge
#

Quaternion.Euler

#

eulerangles is deprecated

near crown
turbid surge
#

Send script

near crown
#

this part over here is the important

#

no need of the rest

turbid surge
#
if ((Input.GetKey(KeyCode.W) | Input.GetKey(KeyCode.S))&&!(Input.GetKey(KeyCode.W)&&Input.GetKey(KeyCode.S)))
        {
            if (Input.GetKey(KeyCode.D))
                RB.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y + (rotation_value/SpeedCalculus), transform.rotation.eulerAngles.z);
            if (Input.GetKey(KeyCode.A))
                transform.eulerAngles = new Vector3(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y + -1 * (rotation_value/SpeedCalculus), transform.rotation.eulerAngles.z);
            print(rotation_value / SpeedCalculus);
        }
turbid surge
#

What error

near crown
#

the one I sent

#

in the picture

#

"Assets\Scripts\CarMove.cs(39,17): error CS0176: Member 'Quaternion.Euler(float, float, float)' cannot be accessed with an instance reference; qualify it with a type name instead"

turbid surge
#

And you definitely added this

near crown
#

Wait I have to do like that?

turbid surge
#

Yes

#

That's what the error is saying

near crown
#

I tought it was RB.rotation.euler...

turbid surge
#

RB.rotation is of type Quaternion, you can't access an instance, because is a static method

#

So use Quaternion.Euler

jaunty hare
#

Hi, i'm struggling with a little problem.

I'm using trigger Collider to load and unload my scenes (simple load system) but some times, I have teleporter that will just break everything, the enter trigger is correctly detected but not the Exit.
Someone have a solution or an alternativ ?

turbid surge
jaunty hare
#

into and out

heady iris
#

what does "break everything" mean?

#

this is not very informative

near crown
#

ok. Grazie @turbid surge

jaunty hare
#

the exit isn't detected, so my scene isn't unloaded

turbid surge
#

Easiest way is just to teleport a little left or right of the trigger, if I understand you correctly. Chemicalcrux is right, not enough info

turbid surge
#

If the trigger entry is working fine, then exit will to, it must be code

#

I wasn't expecting either to work tbh

near crown
#

roberto the car is still tilting slightly :(

#

@turbid surge

jaunty hare
#

the teleport code :

 IEnumerator Teleport(Vector3 playerDestination, Quaternion playerRotation, bool rotatePlayer, bool addRotationPlayer){
            /*
            if(!setVariables){
                setupVariables();
            }
            */

            BeforeTeleport();

            if(cc) {
                // Disable before teleport
                cc.enabled = false;

                // Calculate teleport offset as character may have been resized
                float yOffset = cameraOffset.localPosition.y - playerControler.CharacterControllerYOffset;

                // Apply Teleport before offset is applied
                cc.transform.position = playerDestination;

                // Apply offset
                //cc.transform.localPosition -= new Vector3(0, yOffset, 0);

                // Rotate player to TeleportMarker Rotation
                if (rotatePlayer) {
                    if(addRotationPlayer){
                        cc.transform.rotation *= playerRotation; 
                    }
                    else{
                        cc.transform.rotation = playerRotation;
                    }
                    
                    // Force our character to remain upright
                    cc.transform.eulerAngles = new Vector3(0, cc.transform.eulerAngles.y, 0);
                }
            }

            AfterTeleport();            

            yield return new WaitForEndOfFrame();

            if(cc){
                cc.enabled = true;
            }
        }
turbid surge
jaunty hare
#

the trigger enter and exit are juste OnTriggerEnter and OntriggerExit with a debug.log

turbid surge
#

@jaunty hare Send trigger enter exit code, that is likely faulty

jaunty hare
#
        if(other.CompareTag("Player")){
            playerInTrigger = true;
        }
    }

    private void OnTriggerExit(Collider other) {
        if(other.CompareTag("Player")){
            playerInTrigger = false;
        }
    }
heady iris
#

if you're just setting a transform's position, then that could mess up the physics

jaunty hare
#

it's realy basic use of trigger with characterController

heady iris
#

your character has just a character controller, i'm guessing?

#

no rigidbody

turbid surge
#

I was wrong not faulty

jaunty hare
#

yes

jaunty hare
#

I need to add a rigid body and a collider to try if fix ?

heady iris
#

i'm actually unsure how character controllers behave with collision messages

#

i should really figure that out

jaunty hare
#

ok it works by adding rigidbody

turbid surge
#

Yeah I think rigidbodies may be needed for triggers

#

Actually maybe not

jaunty hare
#

character controller must have bad physic with triggers when it comes to fast moovement / tp

#

thanks guys

turbid surge
#

Notes: Trigger events are only sent if one of the Colliders also has a Rigidbody attached.

#

Add a kinematic rigidbody to the trigger object, it'll be less work than enabling/disabling one on the player

jaunty hare
#

will try

#

works fine to, thanks

turbid surge
#

👍

jaunty hare
#

it's better to have a rigidbody in kinematic on the player or 1 on each Important trigger that need to perfectly track player in and out ?

heady iris
turbid surge
#

Better to have on triggers

heady iris
#

actually, i might have put them on the player

turbid surge
#

Well yeah, what's easier

heady iris
#

the fact that i can't remember probably indicates that it doesn't matter, lol

jaunty hare
#

ok thanks !

heady iris
#

you typically put the RB on the moving object

jaunty hare
#

it's just I need to optimize the most possible cause it's vr game

turbid surge
#

Rigidbodies afaik are pretty performance intensive even as kinematic

turbid surge
lethal plank
#

        newPrefabRotation.x += SensitivityX * input_View.y * Time.deltaTime;
        newPrefabRotation.y += SensitivityY * input_View.x * Time.deltaTime;

        itemPrefab.localRotation = Quaternion.Euler(newPrefabRotation);```
turbid surge
#

No clue I hate quaternions

#

I always try to seperate x and y rotation into 2 gameobjects

lethal plank
#

eh

#

idk what is going on tho

#

also this code is from rotate camera script

#

slightly modified

turbid surge
#

@heady iris Might know

heady iris
#

going back and forth between quaternions and euler angles can cause some unexpected results (try rotating a cube on two different axes and noticing how all three Euler angle values change in the inspector)

#

I wouldn't expect this to start misbehaving once you complete a whole turn

#

I usually just store the yaw (Y rotation) and pitch (X rotation) as floats, and then compute a quaternion from those each update

#

instead of trying to modify the current rotation

#

specifically, I'll do

var rot = Quaternion.AngleAxis(yaw, Vector3.up) * Quaternion.AngleAxis(pitch, Vector3.right);
#

yaw, then pitch

lethal plank
#

oh

quartz folio
#

Also don't scale mouse delta by delta time

lethal plank
#

scale mouse delta?

lethal plank
#

alright then

#

so which should i use?

#

bruh it still

#

so i guess something is happening at newPrefabRotation.x += SensitivityX * input_View.y;

heady iris
#

in what way is it "shaking"?

#

i'm having trouble envisioning this

lethal plank
#

idk it just shaking

#

even without modify y axis

frosty lark
lethal plank
#

no

#

it is shaking

#

wait a bit

#

let me show you

#
        newPrefabRotation = itemPrefab.localRotation.eulerAngles;

        newPrefabRotation.x += SensitivityX * input_View.y;
        //newPrefabRotation.y += SensitivityY * input_View.x;

        float x = newPrefabRotation.x;
        float y = newPrefabRotation.y;

        itemPrefab.localRotation = Quaternion.Euler(newPrefabRotation);```
#

dont mind line 3 4 5

frosty lark
#

is there a if statement at all?

lethal plank
#

yes

#

working normally

#

checked

#

without x
object rotate smoothly

heady iris
#

hmm, it seems like it should be ok

#

however, try doing this instead

#

rather than manipulating the euler angles, just apply rotations

#
itemPrefab.localRotation *= Quaternion.AngleAxis(SensitivityX * input_View.y, Vector3.right);
itemPrefab.localRotation *= Quaternion.AngleAxis(SensitivityY * input_View.x, Vector3.up);
#

I don't like to switch back and forth between Quaternions and Euler angles.

#

euler angles suffer from gimbal lock, notably, which can cause weird behavior in edge cases

#

oh yeah, that could be what's going on...

#

Try doing this to see what i mean

#

Make a cube and set its X rotation to -90

#

Then, try changing the Y and Z rotations

#

notice how they do the same thing

#

we're gimbal locked!

#

that is why I do not like to manipulate Euler angles

cerulean stag
# cerulean stag Hi, I've been experiencing a serious error with Unity for a while. I'm using LTE...

sorry for the bump, does anyone know any good way i can start addressing this error? i believe it may be a shader issue but I don't know where to start looking. there's nothing on Google about m_BufferData, m_WriteOffset or BytesWritten aside from a Unity Help post from someone that was experiencing the same thing https://answers.unity.com/questions/1224067/m-bufferdatacapacity-m-writeoffset-byteswritten.html

#

no one answered it though so i cant go off of that post for information

fervent furnace
#

it looks like c++ style code and i know nothing about shader

knotty sun
cerulean stag
#

yeah theres like nothing on this error

cosmic rain
cerulean stag
#

if you're referencing stack traces no, that's all that's displayed

heady iris
#

restart editor

#

especially if it's just happening randomly

cerulean stag
#

that works but it comes back eventually

#

I haven't tested it in builds yet, so I'm not sure if it bleeds into builds

#

i'm teying to find a way to completely stop this error because it has to be tied to something

fervent furnace
#

i believe this is called by assert(XXXX) defined in assert.h in cpp kernel...

cerulean stag
#

i might try completely reinstalling unity editor, do you believe that might help?

cosmic rain
# cerulean stag

Well, there's really nothing we can do about it. You could try searching your code base for that assert, but it's likely on the C++ side. The best you can do is file a bug report. But they would probably not handle it, since unity 5 support ended ages ago.

fervent furnace
#

i havent use assert.h so i am not sure

cerulean stag
cosmic rain
cerulean stag
#

oops yes

cosmic rain
#

Does the error appear in an empty project?

cerulean stag
#

doesn't seem to but i'll try again today

#

could assert issues be resolved with reinstalls? is it mainly an editor side issue?

cosmic rain
cosmic rain
#

So whether it can be resolved depends entirely on the condition that is causing it.

cerulean stag
cerulean stag
cosmic rain
#

Line renderers are being rendered outside of play too, so if it's caused by them, I don't see why it wouldn't appear.

cerulean stag
#

it also leads to some real nasty stuff like this

cosmic rain
cerulean stag
#

i'll try that right now, thanks

#

just need to boot my pc up first

#

i'm a few minutes into messing around with the project after restarting the layout

#

it's not coming back right now, but the issue is that it's so inconsistent with when it pops up lol

cerulean stag
#

after re-enabling the line renderer array code, it's come back. disabling it made it stop within the game but it still shows up in editor especially when i edit prefabs

#

disabling gizmos in scene view doesn't help

#

there has to be a way to completely stop this

#

@cosmic rain I have footage of it occuring in gameplay with the problematic linerenderer code enabled. mind if I DM you?

#

disabled the code, the gameplay is fine now. but it still appears in editor

#

almost exclusively while editing a prefab

cosmic rain
cerulean stag
#

Assertion failed on expression: 'm_BufferData.capacity() >= m_WriteOffset + bytesWritten'

lament knot
#

My mind got so messed up I actually forgot how to add something that checks if something is touching the other thing

#

Does this need to be in Update() part of the code and how do I specify the object I want to be touched? (If it's not the object that the script is attached to)

    public void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player"))
    {
        RandomizeRooms();
    }
}
static matrix
#

any tips for reducing lag on procedurally generated stuff
like each time I load a new chunk, I get a little lag spike. Its not terrible, but it is definitely noticeable, so I was wondering if you guys had any good fixes

static matrix
#

I have

heady iris
#

turning on Deep Profile will let you see much more detail

static matrix
#

its on the instantiation

#

ill try that

heady iris
#

(it will also make the game run very slowly)

static matrix
#

Not sure if this is bad advice but using eulers is easier than Quaternions for me

static matrix
merry tree
#

Hi,
I have a general question.
Are 0 width gaps a problem for unitys physics system/ tinty gaps in general?
I build a system to put track-blocks together perfectly with a 0 width gap, these gaps then connect planes or boxes, with the same height, so it should be complety flat, for some reason though I get collisons at these connection points, where the player would go from one plane to another. This issue has been bugging me for a while, and I am completly clueless. I don't want to scrap my whole system, so can anyone think of a reason for the collisions at the connection points?
am I doning something wrong with the colliders? I basically have a cube slide over plains, which are all at the same height, and there is no gaps (0 width), between the plains but it collides with the pain anyway an is flipped up when moving.
I hope this description is understandable, if not I will gladly answer questions.

heady iris
static matrix
#

but should I not be using Instantiate

heady iris
#

do you mean that the moving object is bouncing into the air

static matrix
#

is that bad practice or smth

heady iris
#

but maybe you're creating too many things at once

#

or their Awake methods are taking a long time

#

(I forget if they get lumped into Instantiate)

#

deep profile should reveal that

static matrix
#

they are

static matrix
#

its like 66% the creation lagging it and like 33% the Awake

#

ill give it another check

heady iris
#

you might just need to instantiate less stuff per frame

lucid valley
#

otherwise spread the spawning over multiple frames is probably the best you can do to avoid large lag spikes

heady iris
#

I used that in an ECS tech demo

#

I was enabling and disabling enormous numbers of entities

static matrix
#

heres the stuff

heady iris
#

Smearing that out over a few frames let me use even more entities

static matrix
#

and yes I despawn when out of range

#

I could try and spread it over a couple of frames

#

I do it with a for loop rn, but maybe I can try and split that?

lucid valley
#

i'd use pooling too

heady iris
#

it would be easy to turn that into a coroutine

static matrix
#

Im not very good at coroutines but I can give it a try

#

right now it is being invoked with InvokeRepeating Maybe I convert that to a coroutine

heady iris
#

you'd need to split up a single spawning process

static matrix
#

I could send my generation code
but it may cause your eyes to implode in horror

#

should I send it

heady iris
#

i'll retaliate with my own generation code if i feel the need to

static matrix
#

ok im sending it
please ask questions about bits as I have a bad habit to not write comments

heady iris
#

use a code sharing site

static matrix
#

o ok

#

let me pull up pastebin

#

or there was that other one

#

what was it called

#

I forget
ill just use pastebin

#

here it is

#

how terrible is it

heady iris
#

so you're spawning the same chunk over and over, occasionally switching which one you spawn

#

looks pretty reasonable

static matrix
#

yeah
the chunks constitute which kind of area a place is

#

each chunk has a list of structures that it will pick from and spawn I think on Awake
so maybe I could do somehting about that

#

but yeah maybe I try to smear the instantiation over a couple of frames
is there an easy way to do that or should I just convert it to a coroutine

#

(Which I guess is kinda easy but im not very used to Coroutines)

heady iris
#

any method that returns IEnumerator can be used as a coroutine

#

yield return null to suspend until the next frame

#

StartCoroutine(TheMethod());

static matrix
#

ahhhh
and can I use Parameters in StartCoroutine?

merry tree
potent sleet
static matrix
#

swell

potent sleet
#

the return is just IEnumerator

static matrix
#

I cant use params in task.run which is my go to Async stuff so that will be nice

static matrix
#

you can??????

potent sleet
heady iris
#

You do have to wrap it up in a lambda

#

but ya

static matrix
#

oh
lambda
I dont know much lambda so that makes sense that I missed it

#

this will be helpful

potent sleet
#

indeed

#

last time i used task in unity tho it threw a fit

static matrix
#

it doesn't for me

potent sleet
#

it was a while ago tho

heady iris
#

I need to figure out exactly how tasks behave in unity.

potent sleet
#

oh it was Task Delay, it would just hang

static matrix
#

I was using it to build navmeshes on runtime and I felt very superiour because I solved it very quickly

heady iris
#

i saw someone say that unity winds up sticking them on all the main thread anyway?

#

lots of herasay. gotta go do some actual reading

#

i didn't see any obvious official documentation when googling it..

static matrix
#

It was working for me, I think putting things on another thread

potent sleet
#

yeah iirc if you want true multithreading you have to use DOTS

heady iris
#

well, just Jobs

static matrix
#

when i Task.Ran it it didn't case a lag spike on generating the navmesh vs when I just ran it

heady iris
#

I guess that's part of the broader DOTS architecture

static matrix
#

so clearly something was working

#

but idk
maybe Im causing irreperable damage to my hard drive

potent sleet
static matrix
#

who knows

cursive bridge
#

heya ya'll! this will be the begining to my coding journey!

static matrix
#

Prepare for endless sleepless nights and yelling at a screen all day

#

its very fulfilling

potent sleet
cursive bridge
#

yay! 😅

static matrix
#

oh

static matrix
#

anyways Ill try to get that into a coroutine
I don't just copypaste the function into a coroutine right?

heady iris
#

i mean, that's basically it

#

make the function return IEnumerator

#

yield return null to suspend

#

that's all

static matrix
#

oh
that seems too easy

#

where do I suspend it?

potent sleet
#

it really is

static matrix
#

maybe after each row because its grid style enumeration

heady iris
#

and break after, say, 3ms

potent sleet
#

wouldnt that just be new WaitForSecondsRealtime(0.3f)

static matrix
#

hmm maybe
but the player would have to move incrediably fast to get out of range before more chunks load

#
IEnumerator GenerateFromCenter()
    {
        for (int x = -2; x < 3; x++)
        {
            for (int z = -2; z < 3; z++)
            {
                bool Occupied = false;
                foreach (Chunk c in Chunks)
                {
                    if (c.coords.X == x + Center.X && c.coords.Z == z + Center.Z)
                    {
                        Occupied = true;
                    }
                }
                if (!Occupied)
                {
                    GenerateChunk(new Coords(x + Center.X, 0, z + Center.Z));
                }



            }
            yield return null;
        }

    }

just like this?

#

and If i call it with StartCoroutine it will loop and I dont have to call it again right?

potent sleet
#

it's a one time thing

static matrix
#

nicee

#

ok hopefully this works

#

it did not work

#

it generated once then didn't do it any more

#

and that was just from the call in start

#

which doesn't even call the function it just does what the function does basically

heady iris
#

did you use StartCoroutine

static matrix
#

let me try again one sec

#

nope

#

StartCoroutine(GenerateFromCenter());
I also tried with the string name

#

and it just doesn't generate

heady iris
#

did you do return null

#

instead of yield return null

static matrix
#

I did yield return null

#

I put it inside of the for loop

#
 IEnumerator GenerateFromCenter()
    {
        for (int x = -2; x < 3; x++)
        {
            for (int z = -2; z < 3; z++)
            {
                bool Occupied = false;
                foreach (Chunk c in Chunks)
                {
                    if (c.coords.X == x + Center.X && c.coords.Z == z + Center.Z)
                    {
                        Occupied = true;
                    }
                }
                if (!Occupied)
                {
                    GenerateChunk(new Coords(x + Center.X, 0, z + Center.Z));
                }



            }
            yield return null;
        }

    }

fervent furnace
#

i dont know whether unity putting everything on its threads
but can we test it with running a cpu intensive job and divide it to different tasks to see the different?
maybe iterate 10000000 and 4 tasks with 2500000 iterations

heady iris
#

most things are single-threaded.

static matrix
#

but anyways should I reposition the Yield Return?

heady iris
#

it seems fine

#

is the game object that starts the coroutine getting destroyed, maybe?

static matrix
#

nope

#

It doesn't even call once it seems

#

let me throw in a debug.log

#

its just not called

#
public void Start()
    {
        LastChunk = ChunkForLevel[Random.Range(0, ChunkForLevel.Count)];
        Center = new Coords(0, 0, 0);
        for (int x = -2; x < 3; x++)
        {
            for (int z = -2; z < 3; z++)
            {

                GenerateChunk(new Coords(x, 0, z), true);


            }
        }
        Playerstats = GameObject.Find("Player").GetComponent<PlayerStats>();
        Playerstats.LevelStats = this;


        InvokeRepeating("CheckDespawn", 1, 1);
        StartCoroutine(GenerateFromCenter());
    }
#

(ignore the find use im going to change it)

#

oh wait

#

its getting called once

#

but then isn't called again?

leaden ice
#

Where'd you put the log

static matrix
#

in the function

leaden ice
#

Which

static matrix
#

GenerateFromCenter

leaden ice
#

You're only running it once

static matrix
#

its a coroutine, do I need to keep calling it?

leaden ice
#

I don't think you'd expect to run it more than once

leaden ice
static matrix
#

I do need to, to keep generating the world around the player as they move

leaden ice
#

The code is not structured properly if that's what you want

static matrix
#

I hate it when people do this

#

do I just call teh coroutine again? or do I need to to recurse within?

leaden ice
#

If that's what you want you will need a loop

#

I don't recommend recursion

#

Or you can just use Update

static matrix
#

ok so keep calling it

leaden ice
#

No just put a loop in it

#

To repeat the code

static matrix
#

ok

#

will that still wait frames

leaden ice
#

If you put a yield

static matrix
#

ok

#

that might have worked im not 100% sure

#

ill test more in depth later

merry tree
#

so if ghost collisions should only be a

merry tree
# heady iris https://docs.unity3d.com/Manual/ContinuousCollisionDetection.html

I had the problem with every collison detection mode
but this https://forum.unity.com/threads/unnecessary-collisions-created-at-collider-edges-results-in-bodies-jumping.837715/#post-5541316 seems to have fixed it
thanky you anyway
without the proper words, I found in the artical I would have never found it

sweet perch
#

does anyone know why audio isnt playing at all in the editor in certain scenes? it works fine on one but doesnt play at all on another

static matrix
#

is there an audio listener?

errant elbow
#

always works for me

rugged storm
#

I know about animation parameters and using them with condition but are you able to pass them/variables into an animation? Like say change the animation's duration?

sweet perch
errant elbow
#

damn unity

#

does anyone know how can i knockback enemy if i'm using A*?

rigid island
#

How to keep track of uploaded data / downloaded data from UnityWebRequests or any other networking request?

cold parrot
rigid island
cold parrot
rigid island
grizzled vine
#

So, I'm attempting to find the closest point (Based on distance) to the player, where it is a valid line of sight and on the same height as the player. (Topdown with multiple layers). Currently, my code works, but I feel as if its not optimized? And there might be a better way to handle things? Thoughts?

#
public static Vector3 FindPathingLocation(NavMeshAgent inAgent, AITargetSystem inAITargetSystem, float inStoppingDistance) {

        List<Vector3> stoppingOptions = new List<Vector3>();
        float currentStoppingDistance = inStoppingDistance;


        //Find a matching point within the desired stopping distance that is both at the same height, same distance, and in LOS.
        for (int i = 0; i < 360; i++) {
            Vector3 pos = AIUtils.CalculatePosition(inAgent, inAITargetSystem.GetCurrentTarget().position, currentStoppingDistance, i);
            if (inAITargetSystem.isInLineOfSightAtThisPosition(pos))
                stoppingOptions.Add(pos);
        }

        //If none were found, go further away to a maximum distance or until some are found at one distance.
        //Was also thinking about going closer as well.
        while (stoppingOptions.Count == 0 && currentStoppingDistance <= 50f) {
            Debug.Log("This shouldn't be getting hit");
            for (int i = 0; i < 360; i++) {
                Vector3 pos = AIUtils.CalculatePosition(inAgent, inAITargetSystem.GetCurrentTarget().position, inStoppingDistance, i);
                if (inAITargetSystem.isInLineOfSightAtThisPosition(pos))
                    stoppingOptions.Add(pos);
            }

            currentStoppingDistance *= 2f;
        }

        //Go through the built list, and find the closest point.
        if (stoppingOptions.Count > 0) {
            Vector3 closest = Vector3.positiveInfinity;
            float closestDistance = Mathf.Infinity;
            foreach (var item in stoppingOptions) {
                float distance = Vector3.Distance(item, inAgent.transform.position);
                if (distance < closestDistance) {
                    closest = item;
                    closestDistance = distance;
                }
            }

            return closest;
        }

        return inAgent.transform.position;
    }
#

(The reason I bring up performance is because I've noticed a slight hit in the profiler. But nothing too crazy. I know I could change i++ to like i + 2 or something similar, as the sphere doesn't need to be super tight.)

cold parrot
#

what does closest point based on distance even mean

#

what do you actually want to find?

grizzled vine
# cold parrot feels very wasteful depending on what all these methods do

isInLineOfSightAtThisPosition just checks to see if the enemy would be in the line of sight or not to the player.
CalculatePosition just does a bit of an offset on the position based on the enemys aiming height.

The overall goal is when an enemy is down below, I want them to wander to the closest point and NOT do the above which is what they were doing, among other things.

gaunt blade
#

Hey quick question, does anyone know if there's a way to create custom polygons given a set of coordinates for the vertices?

gaunt blade
#

how so? I'm planning to use a modified version of voronoi diagrams to create maps, but part of the reason why is because it creates parts that are irregular in size and shape, so I need to be able to create each part individually based on the locations of the vertices/edges for those parts that are calculated beforehand.

errant island
#

guys i need help

cold parrot
errant island
#

im creating an FPS game and i want to put a local CO-OP system on it.

wide terrace
errant island
gaunt blade
# cold parrot idk what you actually need from that bit of info, if you mean you want to create...

I have data that contains information about a set of vertices and edges that conceptually describes what the polygons should look like. I'm asking how to create those polygons from that data.

To be even more specific, the process involves generating a fixed amount of points randomly within a fixed dimension of width*height, then connecting those points to create triangles. Then those triangles are further expanded upon by drawing additional points at the centroid of each triangle, and connecting all those new points together with more edges to create the vertices and edges of the parts that need to actually be created

#

It results in something that looks like this

gaunt blade
#

Yes.

#

Correct.

cold parrot
#

the black triangles are the delaunay triangulation of the voronoi points

gaunt blade
#

Yes, correct, and then I use the second set of data to draw a "smoother" set of polygons that give what I feel would be a better shape for the type of map I'm designing

#

Since I'd rather not use the triangles directly.

cold parrot
#

sure

gaunt blade
#

But I don't know how to generate the polygons based on the vertice/edge info

errant island
cold parrot
#

so you have all the triangle data (vertices and triangle ID they belong to) and you dont know how to make a mesh from that?

gaunt blade
#

Well, like in that picture, I have 4 sets of data. The points of the red dots, and the black lines that connect them are two sets of data, and then the blue dots and the white lines that connect them are the other 2 sets of data. With those 4 sets of data I want to generate a part that is the same shape as the ones made from the white lines and blue dots.

cold parrot
#

ic

gaunt blade
#

The idea being that I'll later use an algorithm to determine how to modify the height of those parts to create the terrain

cold parrot
#

so the while polygons are all convex, so you don't need a fancy algorithm

gaunt blade
#

Yeah, nothing fancy. The shapes are pretty simple.

cold parrot
#

presumably you can identify which blue coordinates belong to which voronoi cell?

gaunt blade
#

Yeah, each blue dot is located at the centroid of a single vornoi cell, so you know which one belongs to which.

cold parrot
#

ok

#

idk what is non-obvious about how to do it... you iterate the cells, make a mesh for each cell, then iterate the vertices of the cell where you construct a fan o triangles from those vertices, write all that to the meshes' vert/tri arrays and your're done

#

you may have to do some gymnastics with the winding order of the triangles but thats the only complicated bit

#

like this

gaunt blade
#

I'm confused by your explanation. Would generating a bunch of triangles by going through and using 2 blue dots and 1 red dot as vertices until you've gone through every blue dot around a particular red dot, and then combining all those triangles into a mesh work?

cold parrot
#

theoretically triangles can share vertices, depends on what you want to do with the mesh if thats a good idea or not

gaunt blade
#

So somtehing like this

cold parrot
#

i would imagine you want the cells to have triangels with shared vertices but the cells dont share vertices with neighbours

cold parrot
#

so long as your shape is convex and has only 1 inner vertex, its all trivial

#

if its not, you could just generate the delaunay triangulation for your blue points (turn them into red points)

#

why do you want that center vertex anyway?

gaunt blade
#

I don't, I've never created custom meshes before, I have no idea how to do it I'm trying to figure it out right now.

#

I only care about the blue points and the shape that they make

cold parrot
#

if you take a look at the Mesh API it should be quite obvious how

#

you have a list of vertices and a list of indices into that list of vertices that defines the triangles

#

every group of 3 vertex indices describes one triangle

#

the ordering of the 3 indices defines which way the triangle is facing (winding order)

gaunt blade
#

So for instance, a triangle array for this would look like (1, 2, 3, 1, 3, 4, 1, 4, 5, 1, 5, 6, 1, 6, 7, 1, 7, 8, 1, 8, 2)

#

given each number is the position of the vertice

#

And so you'd pass (1, 2, 3, 1, 3, 4, 1, 4, 5, 1, 5, 6, 1, 6, 7, 1, 7, 8, 1, 8, 2) as the triangle list and (1, 2, 3, 4, 5, 6, 7, 8) as the vertice list, right?

#

Or am I mistaken about how that works

cold parrot
#

and the number is the index where that vec3 sits in the array

gaunt blade
#

? You mean that I save the position of vertices for each triangle as a vector3 value and then pass that vector3 value to the triangles list?

cold parrot
#

no

#

you add the vec3 for each vertex to a specific index in the mesh.vertices array

gaunt blade
#

Ooh I got what you mean. So each vertex is represented as a vec3 value to represent its position, then each "number" in my example would be that vec3 value reprsenting the position

#

Right?

cold parrot
# gaunt blade Right?
            var m = new Mesh();
            m.SetTriangles(new int[]
            {
                0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 6, 0, 6, 7, 0, 7, 1
            }, 0);
            m.SetVertices(new Vector3[]
            {
                new(0, 0, 0),
                new(1.0f, 0, 0.2f),
                new(0.1f, 0, 1.0f),
                new(-0.5f, 0, 0.5f),
                new(-1.0f, 0, -0.1f),
                new(-0.5f, 0, 1.0f),
                new(0.5f, 0, -1.0f),
                new(1.0f, 0, -0.2f),
            });
gaunt blade
#

Ooh, so the vertices array contains the vector3 values for the positions of those vertices, and then the triangles array are the indexes of those vertices in the vertices array

cold parrot
#

yes

gaunt blade
#

Gotcha gotcha

cold parrot
#

same with all the other data like vertex color and normals

gaunt blade
#

Understood, thank you for the help!

cold parrot
#

most common issue with making meshes manually and it looking totally broken is winding order or some mixup with the indices

gaunt blade
#

winding order?

cold parrot
#

google it

gaunt blade
#

I'll figure it out when I'm making the triangles ig

prisma plover
#

what do i have to do when unity itself produces memory leaks

heady iris
#

not much

#

unless this is actually causing major problems for you

#

intermittent warnings are not major problems

prisma plover
#

hmmm

prisma plover
#

oh

steady moat
#

Usually, making a delta between 2 state of your game is sufficient to find most Memory Leak.

#

Some can be found by looking for m_CachePtr=0 objects. It means that the managed object is still alive, but the native object is dead.

#

Then you have the whole unsafe memory leak, which I never dealt with so I would not know exactly how to help you.

prisma plover
#

i'll try

#

thank you

steady moat
#

Oh, and you need to profile a build.

#

If the issue is only in the Editor, do not worry about it, you probably have more than enough memory to deal with it.

prisma plover
#

this leak is a weird one

#

i havent wrote any script

#

happened in a fresh URP project with ECS packages installed

steady moat
#

You can report a bug.

#

And ignore the warning.

prisma plover
#

yeah i can ignore leak logs

#

but more weird is that its not happening in DOTS sample i downloaded

steady moat
#

Nothing we can do for you.

#

You gotta deal with it, or try to start from the DOTS sample.

prisma plover
#

oh yeah

#

you encouraged me to deal with memory leaks. thank you so much!

dawn nebula
#

If you were making a hitbox system for a bullet hell, aka you're expecting hundreds of (pooled) bullets...

#

Would you use Triggers to detect collisions.

#

Or Physics2D.OverlapCollider?

steady moat
#

To be honest, I am not really sure what is better between OverlapCollider or OnCollisionEnter/The new Event, but this something you can easily profile.

sharp acorn
#

Quick question: How can I render lines without a line renderer? I've made a neural network and I want to represent the weights, and for that, I need thousands of lines, each with a different color and width

#

And I wouldn't know where to start with line renderer

lean sail
#

You can use stuff like generating meshes or maybe even a shader, though line renderer would be way easier to learn for sure. You just plug in the points u want and the line renderer does the magic for u

#

if you cant learn line renderer, i doubt the harder solutions will help

steady moat
sharp acorn
#

It's almost impossible to do it with line renderer, trust me, i know how to use it

steady moat
#

There is also GL.LINES

sharp acorn
#

Again, thousands of lines each of a different color and width

sharp acorn
steady moat
#

And, Unity is NOT a program to present data.

lean sail
#

how would this be impossible with line renderer? you can make more than 1 line

#

if its just 2D or UI i guess u dont need line renderer

steady moat
sharp acorn
steady moat
#

Depending on your needs and where your application has for requirement, you might want to use IMGUI.

sharp acorn
sharp acorn
lean sail
#

if u had 1 line it would be 1 continous line anyways, But idk the exact use case or what you want these to look like

sage radish
#

hey im coding a simple game and i need to set up a delay when the player dies for a screen that will say you died than 5 seconds later rreturns to the menu this is my current death code
"""
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Obstacle")
{
deathThings.SetActive(true);
scoreRemove.SetActive(false);

    }
}

"""

lean sail
sage radish
#

ok

dawn nebula
steady moat
# dawn nebula Oh interesting that they created those collider overrides. Though I guess I'm as...

Not sure I understand, what is an hitbox priorities ? Composite hitbox are kinda straight forward though.

In 3D you have the concept of Compound Collider. https://docs.unity3d.com/Manual/CollidersOverview.html#:~:text=compound colliders.-,Compound colliders,-Compound colliders approximate
In 2D you have directly a component called Composite Collider. https://docs.unity3d.com/Manual/class-CompositeCollider2D.html

dawn nebula
steady moat
#

Using time, or doing 2 cast could be a way to do it.

dawn nebula
#

Why would it not make sense? In fighting games lots of moves are composed of many different hitboxes, each with varying effects/properties. When I get hit with this move, I don't take damage for each hitbox. I get damaged once, defined by which hitbox had the highest priority.

lean sail
#

in fighting games, u also have i frames

#

which specifically prevents u from getting hit again within a certain time limit

steady moat
heady iris
dawn nebula
#

I guess I can probably solve this by just having a "HitboxManager" that asks a bunch of hitboxes what they currently overlap.

#

And then handle all the priority/sorting logic there.

heady iris
#

I just sum up the results from all of the trigger messages

#

Each hitbox-hurtbox overlap is sent to the weapon in my game

#

The weapon keeps track of everything, and notifies the enemy of how much damage to take

proper pier
#

hey, I understand color is represent with a vector 4, but how is HDR color, (which also has intensity), represented? A vector5?

heady iris
#

no, HDR color is just four floats

#

notice how Color has float fields on it

#

any value higher than 1 is "HDR"

#

the intensity you see in the editor is just another way to represent it

#

you could either do

#

[100, 50, 30]

#

or

#

[1, 0.5, 0.3] with 100 intensity

proper pier
#

oh so intensity simply multiplies each value of color?

heady iris
#

yes

proper pier
#

isn't color maxed out at 255 though?

heady iris
#

the 0-255 range is often used to define colors because it's familiar

#

that range only really exists for colors where each channel is one byte

#

since you can store 256 different numbers in an 8-bit int

#

Color32 does this.

#

for the regular Color type, you might still see 0-255 because it shows up in so many other places

#

but the channels are stored as floats, where 1 is the brightest non-hdr value

#

so if you had, say, "50" in the red channel, it'd be 50/255=~0.2

proper pier
#

so wouldn't multiplying by intensity just result in color going torwards either white or black?

#

if you multiply by too much it just becomes white since there is a color cap?

heady iris
#

i forget how unity handles extremely intense light

#

eventually, on a real camera, it'll wind up turning white

#

because every part of the sensor is completely overwhelmed

lean sail
#

even setting the intensity to like 10 just becomes pretty much white sometimes

proper pier
#

ok thanks for your help lads

#

I dont know how everyone is so knowledgeable about everything lol

heady iris
proper pier
#

?

#

did you put it out of domain?

heady iris
#

i increased the intensity many times

lean sail
#

intensity on the UI goes to 10

heady iris
#

and yeah, look at this

#

with sufficiently high intensity, it just washes out to white

#

unless it's pure red

#

oops, beat me to it

#

the scale is exponential, so this is actually like e^10 or something

#

i forget what the base is

proper pier
#

where did you learn about that?

#

r u a photographer?

heady iris
#

ah, it looks like it's base 2 or something

heady iris
#

i use unity a lot

severe falcon
#

Im getting the error: Failed to find entry-points:
Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
and none of my scripts are loading

proper pier
#

nice lol, i was just wondering how you stumbled along the equation for how intensity is represented mathematiccaly

heady iris
#

A lot of stuff is exponential

#

sound, notably

#

decibels are logarithmic!

proper pier
#

interesting

heady iris
proper pier
#

if you're units are exponential does that make your exponential equations linear?

heady iris
#

taking the logarithm of an exponential function gives you something linear

#

log2(2^10) = 10

#

log2(2^11) = 11

#

that kinda thing

proper pier
heady iris
#

they match up with perception

#

if we measured sound just by looking at how much energy is transmitted, you'd need really really big numbers for loud sounds

#

decibels are a lot easier to work with

proper pier
#

Yeah that makes sense

heady iris
#

same thing for intensity in the HDR color picker

#

it matches up with perception, and it means you don't have to punch in an intensity of 1000 to get a very very bright color

#

anyway i am sick and need to sleep lol

#

later

proper pier
#

interesting how are ears and eyes perceive exponential increases as somewhat linear

hollow isle
#

how can I make a drop-drop list for my list of variables in the editor but be able to select multiple at a time (such as like in a culling mask for a camera)?

I'm doing this because I'm making an enemy spawner and I want the option of it spawning multiple different types of enemies

buoyant crane
hollow isle
#

ty

#
public enemyType enemyTypeVar;
[Flags] public enum enemyType
{
    None = 0,
    Basic_Default = 1<<0,
    Other = 1<<1,
    Marley = 1<<2,
    Tanner = 1<<3,
    Ginger = 1<<4
}

Am I doing something wrong?

lean sail
#

even if people might know the answer, show the actual error so no one has to guess what it is

hollow isle
#

oh right yeah im a little slow

lean sail
#

are u using System;?

hollow isle
#

didn't know I had to do that

#

it wasn't mentioned anywhere in the link they sent lol

#

thanks

lean sail
#

if that was the issue, its probably because its included by default so they mightve forgot

#

also, googling that exact issue really wouldve given u the answer

dense cloud
#

Coded a simple breakout game without a tutorial, but need help understanding using a
static rigidbody + box collider 2d vs box collider 2d only,
when a moving gameobject collides with a static gameobject.
What is the actual use of the static body type?

I'm familiar on how basic collision involving static object works in unity,
one gameobject needs to have a rigidbody + any collider type (ball) and the other with any type of collider (wall)

#

I checked SO, and someone said it's not necessary since more components attached = more memory needing to run?

steady moat
#

Physics is different.

gaunt wren
#

Not sure if it's against the rules to bump posts but it has been a few days and I tried the suggestion one gave me which didn't work sadly so hoping to hear from others. Would this issue be better posted in the code-advanced channel?

dense cloud
#

is this right?

steady moat
dense cloud
#

hmm I'm not familiar with that let me go and read that up

steady moat
#

Static is not a single toggle.

#

If you pay attention, you gonna see that you can toggle different things in the static toggle

dense cloud
#

oh yea you're right

#

aye thanks for the breakdown & explaination

steady moat
#

In fact, I am not even sure to understand your issue.

#

You are speaking of "Clone Object" which would be the First Person Render vs the Third Person Render ?

#

Why are you not able to synchronise both Animator ?

mortal breach
#

private void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            float interactRange = 2f;
            Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange);
            foreach (Collider collider in colliderArray) {
                Debug.Log(collider);
            }
        }
    }

Im trying to list all the objects that my player is colliding with when creating that Physics Sphere, but it seems that nothing is colliding and i dont know why, objects in the scene have box colliding too

gaunt wren
# steady moat Not sure what method is used in "Sebastian Lague's Portal". I would guess it is ...

yeah, so it's a camera rendering to render texture. The clone object I speak of is a clone Player's model that the others would see before the player steps through the exit portal. Once the player crosses the threshold of the entrance portal, they are teleported to the clone objects position and the clone is removed.
The Player model is normally culled from the main player camera however Portal Camera's can see it.

The problem is that when I'm about to move through a portal, you can see a bit of the third person model appear on the side your about to walk through since the Camera's aren't culling this model.

I'm mainly trying to figure out whats the best way to tackle it. The options I've mainly considered is to have another Camera Render the area without the player model in view or to have the animations match up with the first person view but each has their own pros and cons so I'm asking if others know of any other solutions I could attempt that I might be overlooking

cosmic rain
gaunt wren
#

That's a good idea since Valve's done a number of interviews on the technical side. From the ones I did watch, I don't recall them touching on the Camera rendering side or them facing anything similar but it was a while since i saw them

gaunt wren
#

I think...I figured it out by a random thought. I changed a bit of the Recursive render code to not render the specific layer at the last iteration of the loop and I surprised that works? Can't see the player clipping through the exit portal but the clone object is visible. Just need to sync up the animators now which Isn't a problem

dawn nebula
#

Back in early Unity days it was advised to pretty much never use GetComponent within one of the Update functions. That still apply or has the speed of that function been increased?

dawn nebula
#

Maybe check his stuff out?

gaunt wren
#

it is his codebase haha

dawn nebula
#

OH LOL

gaunt wren
#

his project doesn't take into acount player controllers that have animations so i was trying to figure how to stop the portals rendering the player's model in the exit portal which i figured out through luck i suppose

gaunt wren
lean sail
#

Theres just no reason to really get component every frame if you can cache the result, knowing that it's always there

#

Unless u do it an absurd amount, u wont see any lag. If you do it that many times for it to cause noticeable lag, you have other issues

dawn nebula
#

Ya there's a couple of "Unity no-nos" that got tossed around quite a bit.
Stuff like:

  • No GetComponent in Update loop.
  • Don't use Camera.main.
  • Use SquareMagnitude instead of distance.
#

I know the later two are kinda irrelevant nowadays.

lean sail
#

Camera.main I believe was changed long ago, that's what I heard at least.
Square magnitude just saves u a sqrt call, sometimes u do actually need the distance though which u cannot just replace with sqr magnitude

dawn nebula
lean sail
#

U really have to be doing it a lot for it to matter

#

Definitely use it if u can, but dont expect a single extra frame unless it's being called thousands of times

obsidian saddle
#

hey, I'm just writing some basic functions for my game and I'm curious about folks' thoughts on this. Is it generally acceptable to use the singleton pattern for "global" or one-of-a-kind processes in the game? (for example, a sound handler or even a menu with certain values that need to be accessed by other scripts)

#

I'm having to throw something together very quickly and the code is slightly spaghettified, and I'm wondering just how disliked singletons are to other programmers

dawn nebula
#

I think it's acceptable but not ideal.

#

If it's a small thing you need to do, seems fine.

lean sail
#

you can make it a scriptable object likely

#

sound system is like one of the common examples for SO

obsidian saddle
#

i see Lazy, those were pretty much my feelings as well

#

bawsi i'm talking about things that are more centralized by design

#

things that many different scripts have to access separate from one another

#

i'm not sure i see how SO's would help w that

dawn nebula
#

Managing state in any application can be difficult, games especially because their systems tend to be super intertwined.

#

Singletons provide an easy way for any part of the application to access some state.

#

But it can lead to some pretty rough coupling.

obsidian saddle
#

yeah, i can totally see that

tame spruce
#

Hello,

I want to create a UI menu that displays various items in their 3D form. Normally, with 1 items, I'd do a render texture. But I'll have 16+ items to display and creating 16 cameras seems like... The wrong thing to do.

I am experimenting with putting real 3D objects under a scroll-rect and layout-groups. It works (sort of) but because my camera is not Orthographic, I need to move the models slightly to make it look like they alighn on camera.

I also can't use Canvas Group to fade in and out these 3D Objects.

Is there another obvious way I don't know about? Is this how I should do it?

obsidian saddle
#

coupling is something my games always seem to have problems with, and it really hurts their expandability lol. fortunately this is like a one-week-or-so project so i don't care too much about its design, but i feel like i shouldn't rely so much on using singletons in this project

dawn nebula
#

If it's a small application that you need to push out and likely won't ever touch again, go for it. Who cares.

If it's a bigger, multi-month/year project then either be very careful with it or try a different architecture.

obsidian saddle
#

yep, that's kinda how i feel

#

well ty <3 i'm glad to get feedback

dawn nebula
#

Np. As for something to try other than Singletons, I'm a big fan of PubSub.

#

Things just send out events and if there happens to be listeners then they act.

tame spruce
#

If you don't mind me joining, how does that differ from observer pattern?

dawn nebula
#

It's a bit different in that instead of the Subject having a list of observers, and updating those observers when something happens, messages are sent to one big Hub object, and this Hub is tasked with sending those messages to the relevant observers.

tame spruce
#

Sounds neat, I'll take a deeper look. Thanks!

dawn nebula
#

It's neat because normal Observer patterns require that the Subject holds reference to its observers.

#

But with PubSub you don't.

#

You just have the hub.

#

And all communication runs through it.

turbid surge
bitter hound
#

I'm having a (most likely beginner-level) Git problem, can I ask about it here or is there a specific channel or server I could ask it in? It's not a Unity related Git problem.

#

In short, I get an authentication failed error when I try to publish a new repository from local PC, but if I first clone a new repo and then push the same files to the cloned repo, everything works.
I don't know what could cause this and I'm having trouble finding the right keywords to figure out the issue.

prime sinew
#

show the error

bitter hound
#

Using Github Desktop I get a generic list of suggestions, which seem irrelevant since the same github desktop client happily commits to other repos / to the same repo if I clone it first

Using VS Code's automatic publish tool, I also get an authentication error

Using command line, I believe the relevant line is

2023-06-04 12:55:19.144 [info] git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
#

Is it possibly related to capital letters in the project/folder name?

#

It successfully creates the new repository on github, but I can't publish / push the files there.
If I clone the newly created repo, I can then push to it

prime sinew
#

i'm not too sure, but does it allow you to enter a username and password?

bitter hound
#

It doesn't ask them, but it doesn't ask them either after I clone it, but works then

#

Does creating a new repo require a different confirmation from pushing to an existing repo?

prime sinew
#

i'm afraid i'm not sure. i usually wing it when it comes to git issues

bitter hound
#

Same. And google is usually quite helpful, but in this case I know it's an authentication issue, but I'm having trouble figuring out why it fails to authenticate the publishing of a new repo but not the other stuff

swift falcon
#

https://paste.ofcode.org/p6WSGGma9pzrN2Ti4dgCF3 line 50 and 51, how can I "select" object that is hitted by raycast, get its rigidbody, and when raycast isn't hitting that object, the object is still selected, until for example isGrabing == false

prime sinew
#

isnt this your hit object's rigidbody

swift falcon
#

that's the problem

bitter hound
#

what's the variable i for?

prime sinew
swift falcon
swift falcon
prime sinew
#

what object is this?

unkempt meadow
#

I don't see a performance section but what is this and how do I find out? I get a a big stutter and read.file is the culprit

bitter hound
swift falcon
prime sinew
lean sail
lean sail
#

Otherwise check permissions on github like if any auto permissions got setup

bitter hound
#

@swift falcon
the proper structure for it would be something like

bool canGrabNewObject;
void Update() {
   // stuff
   if(canGrabNewObject)
       GetClickedObject();
}

void GetClickedObject() {
   if(Physics.Raycast() etc) {
      stuff
   }
}

Also, the variable name i is usually used in for loops, I'd not use it outside of those, and especially not when it's used as if it was a boolean value.

#

having all the physics.raycast, directionobject checking etc stuff in the update function like that makes it more likely that some bug causes some unexpected behavior you don't want.

#

Any way, the actual thing you asked about is most likely

  GameObject clickedObject = hit.transform.gameObject;

However, you'd want to check that it's not null before doing stuff with it, since it could be removed or deleted after it was clicked, but before the other stuff happens

bitter hound
#

At first I thought it's something like "you have to set up ssh keys / security keys / something for each new repo you do" but that doesn't seem to be the case

swift falcon
lean sail
#

Can u try creating the repo on the website and just push anything to it, not even unity related stuff

bitter hound
#

@swift falconthen you need to make it so that the clickedObject variable is set to the object under the raycast in a specific case, and isn't updated every time the ray is cast

swift falcon
#

okay

bitter hound
swift falcon
#

I will try

lean sail
#

Oh I see where u wrote that

idle flax
#

Hey all, I have a quick question. I have a time system, which is a float that goes from 0-24. How do I trigger code every time a new hour starts?

bitter hound
#

@swift falcon

bool canGrabNewObject;
GameObject clickedObject;
void Update() {
   // check if I have a clickedObject
   // check if the game state is such that a new object can be grabbed, update variables if needed
   if(canGrabNewObject) GetCLickedObject();
   
   if(clickedObject != null && isGrabbing) {
      HandleGrabbedObject();
   }
   else {
      // stuff to do when nothing is grabbed
      clickedObject = null;
      canGrabNewObject = true;
   }
}

void GetClickedObject() {
   // do raycast stuff
   // if raycast was successfull, check the object
  // if the object is good, then
  clickedObject = hit.transform.gameObject;
  canGrabNewObject = true;
}

void HandleGrabbedObject() {
   // check stuff related to directionObject and clickedObject
   // etc
}
lean sail
idle flax
#

I use events, I just don't know how to call them when a new hour starts.

bitter hound
#

I'm not sure it's that much better tbh, but I like making functions with clear names to structure my code. This way, it's easier to keep track of what's happening where, and why.

lean sail
idle flax
lean sail
#

a float goes to a new int?

#

u mean when the value resets back to 0?

bitter hound
ruby fulcrum
#

what does the ^ operator do?

bitter hound
#

any way, it's not a huge problem, it's just annyoing I can't figure out the proper way to do it

lean sail
idle flax
ruby fulcrum
#

im trying to get the last instance of a list

lean sail
#

yes

ruby fulcrum
#

ohh

bitter hound
#

@idle flax float doesn't quite work like that, you can never be sure a float is exactly 2, 3, 4 etc
So basically you'll have to check that the float is larger than 3, 4, 5 etc one by one

ruby fulcrum
#

how does it work though

#

the ^ operator

idle flax
bitter hound
lean sail
ruby fulcrum
lean sail
ruby fulcrum
#

so basically if i do list[^] its the same as list[list.Count]

bitter hound
ruby fulcrum
#

ohhhh

lean sail
bitter hound
#

cool, I hadn't come across it before, thanks for the link

lean sail
#

i think they added this before pattern matching

ruby fulcrum
#

i see

lean sail
#

actually i have no clue when they added it i forgot

bitter hound
#

@idle flax
this is a silly way of doing it, but... you could store a rounded-down version of the number int previousHour = Math.floor(timeVar) and compare that to the current time rounded down. When they're different, hour changed.
if(previousHour != Math.floor(timeVar))

#

It's not elegant, but it only stores one extra variable and it only does a few mathematical operations each frame. There's a better way, but this is probably a "good enough" way.

idle flax
#

That's kinda smart lol, I'll do that thanks.

lean sail
#

you could also just check if timeVar is approximately == (int) timeVar

bitter hound
#

yes - but again, lag spikes

lean sail
#

oh but u need the previous hour too

#

maybe

bitter hound
#

if you never had lag spikes, you could do stuff like
if( timeVar - Math.floor(timeVar) < 0.05)

#

if the difference between the variable and its rounded-down version is small, the new hour just started

lean sail
bitter hound
#

But if it's ever possible for a lag spike to hit at that exact time, then the game might not recognize that the hour changed, so...