#archived-code-general

1 messages · Page 259 of 1

terse quarry
#

wait lol

#

how do i do the underlined part and not the common mistake :d

leaden ice
#

if you want to destroy the GameObject, pass the GameObject in

terse quarry
#

How do I pass an instance of the class that the script is attached to

leaden ice
#

this is the instance of the class that the code is currently running on

terse quarry
#

Then how do i destroy the object and not just the script

#

but from the script that the object is attached to

leaden ice
#

If you want to get a reference to the GameObject the script is attached to, that would just be this.gameObject or just gameObject (you don't need the this)

jaunty sundial
#

ok ive been racking my brain at this for a while im trying to traverse a graph essentially which is my list<list<int>> and im trying to make it start in a random place and assign that to 0 and then adjacent tiles which are the ones to the left and right and above and below it it will randomly choose to go to one of them and assign it 1 then do this so on until roomCount is reached

    {
        new List<int> {-1, -1, -1},
        new List<int> {-1, -1, -1},
        new List<int> {-1, -1, -1}
    };

    public List<List<bool>> roomsVisited = new List<List<bool>>
    {
        new List<bool> {false, false, false},
        new List<bool> {false, false, false},
        new List<bool> {false, false, false}
    };

    public List<List<bool>> roomsValid = new List<List<bool>>
    {
        new List<bool> {false, false, false},
        new List<bool> {false, false, false},
        new List<bool> {false, false, false}
    };

    // Start is called before the first frame update```
#
    {
        roomCount = Random.Range(3, 7);
        for(int i = 0; i < roomCount; i++)
        {
            horizontalChoice = Random.Range(0, 3);
            verticalChoice = Random.Range(0, 3);
            if (i > 0)
            {
                while(roomsValid[verticalChoice][horizontalChoice])
                {
                    while (roomsVisited[verticalChoice][horizontalChoice] == true)
                    {
                        while (horizontalChoice != leftCheck && horizontalChoice != rightCheck)
                        {
                            horizontalChoice = Random.Range(0, 3);
                        }

                        while (verticalChoice != upCheck && verticalChoice != downCheck)
                        {
                            verticalChoice = Random.Range(0, 3);
                        }
                    }
                }
            }
            upCheck = verticalChoice - 1;
            downCheck = verticalChoice + 1;
            leftCheck = horizontalChoice - 1;
            rightCheck = horizontalChoice + 1;

            for(int a = 0; a < 3; a++)
            {
                for (int b = 0; b < 3; b++)
                {
                    roomsValid[a][b] = false;
                }
            }

            if (upCheck > -1)
            {
                roomsValid[upCheck][horizontalChoice] = true;
            }
            else if (downCheck < 3)
            {
                roomsValid[downCheck][horizontalChoice] = true;
            }
            else if (leftCheck > -1)
            {
                roomsVisited[verticalChoice][leftCheck] = true;
            }
            else if (rightCheck < 3)
            {
                roomsVisited[verticalChoice][rightCheck] = true;
            }
            roomMatrix[verticalChoice][horizontalChoice] = i;
        }```
hard viper
#

is this a graph on a grid?

jaunty sundial
#

i guess yeah

hard viper
#

is it a directed graph

jaunty sundial
#

yeah it should go from start to finish

hard viper
#

uh, but are the edges directed

#

like two positions might have one-way travel between them

jaunty sundial
#

all the positions will be one way travel

hard viper
#

and what sort of graph traversal do you need

#

are you just adding vertices to graph?

jaunty sundial
#

Yes

#

Im trying to make a graph not traverse one

hard viper
#

if you are trying to search, you should use a graph.
if you are trying to create a graph on a grid that satisfies specific constraints, you want the wavefunction collapse algorithm

#

and this does not sound like a directed graph

#

you are building outward, but that does not make the graph a directed graph

#

also, don’t do all this in a Start() call

#

make an actual class to handle this. a POCO

dusk apex
clever bridge
#

Hi, I have a line of code where I want to aim a hose and spray a target, is this right?

hose.transform.eulerAngles = new Vector3(0, 0, Vector2.Angle(hose.transform.position, target.transform.position));

quaint rock
#

no calculating angle between 2 positional vectors makes no sense

clever bridge
#

i want the hose to point at the target

quaint rock
#

i would do something like

var direction = target.transform.position - hose.transform.position;
hose.transform.rotation = Quaternion.LookRotation(direction.normalized, Vector3.up);
clever bridge
#

it's 2d, is vector3.up the right thing? I want to rotate the z

quaint rock
#

ah i was assuming this is 3d

#

for 2d i would be tempted to just manually do the math

var AngleRad = Mathf.Atan2(target.transform.position.y - hose.transform.position.y, target.transform.position.x - hose.transform.position.x);
var AngleDeg = Mathf.Rad2Deg * AngleRad;
hose.transform.rotation = Quaternion.Euler(0, 0, AngleDeg);
cinder fractal
#

hi im using this line of code:
lastProp.GetComponent<Rigidbody>().AddForce((propPos.transform.position - lastProp.transform.position) * 45, ForceMode.Acceleration);
to move my prop to its destination it works but in like 1 in 5 times it just starts floating around its destination how do i fix that?

quaint rock
#

the multiply it by 45 will not be consistient since the length of the vector will often be much larger then 1 unless you normalize it first

cinder fractal
quaint rock
#

yes though dest is a bad name for it, since its not a position in space its a directional vector

cinder fractal
quaint rock
#

assuming it greatly overshoots, because the velocity does not get smaller as it approaches the target

#

it could be scaled down based on distance to target

cinder fractal
#

maybe the problem is my if statement
private void FixedUpdate()
{
if(itemHeld)
{
if (lastProp.transform.position != propPos.transform.position)
{
Vector3 dir = propPos.transform.position - lastProp.transform.position;
lastProp.GetComponent<Rigidbody>().AddForce(dir.normalized * 45, ForceMode.Acceleration);
}
else
{
lastProp.GetComponent<Rigidbody>().velocity = Vector3.zero;
}
}
}

cinder fractal
lunar python
#

should my State be ScriptableObjects or just classes?

quaint rock
lunar python
#

wait it depends on the context?

#

basically my State class is an abstract state for controlling Player's State, AI's/Enemy States, and some Objects' State

lean sail
#

and you would have to create a new instance for each object anyways

lunar python
#

okay I found an article on that, so im just asking whether I should change my approach

quaint rock
lean sail
#

theres a ton of ways to implement it, a State can be anything. as long as its easy for you to use then use it

lunar python
#

does referencing StateMachine in States cause problems in the future or is it having some unnecessary computational burden on the game?

quaint rock
#

would say depends on implementation you got, you are getting maybes since state machines are just a lose programming pattern that can be used for many many things and implemented in many ways

lean sail
#

its just a matter of storing a reference

lunar python
#

Im even referencing player's controller in one of the State's derivatives. Maybe I should just let the states have their neccessary variables instead of passing in all of them

lean sail
#

relaly not sure what the point of this state is, but yea this state has way too much control over what happens. The whole stateMachine.SetNextState(new SlimeIdle()); part needs to go. This is gonna stop you from making reusable states

lunar python
#

Im citing player's position in the State and constantly updating it every frame. So if I have 1 million entities in the world would that be ridiculous?

lean sail
#

if you have 1 million entities in your game, your game wont even run

#

this code is definitely a mess, why is OnEnter calling BaseUpdate

lunar python
lean sail
#

my enemies are simple enough that i dont even care about transitions. If they can enter a state, they enter the one with the highest priority

lunar python
#

do we have priority_queue in C# or some sorts

#

or do I have to recode it

lean sail
#

there is, but thats not what i was referring to. I assign each state a number and then just check which one has the highest number

lunar python
#

let's say I want to make a horde of enemy acts differently. Having priority queue so an enemy would go and be the defense line. Others notice some of their teamates are defenders, they change their priority to ranged attack

#

would be cool

lean sail
#

a priority queue wouldnt really affect what happens here, the enemies in this case would need a sense of their team. You could pass this as a parameter to each state, then they lookup what role is lacking

#

Actually this wouldnt really happen inside the state machine, being ranged/melee/whatever would be the states. An enemy controller script would be looking that information up, and then requesting a state transition

silver crescent
lunar python
#

oh ye

#

i forgot to move that to the SlimeMovementBase

#

but it is going to be depracated soon with better management

dusk apex
lunar python
#

does anyone know how RainWorld AI works

vagrant blade
#

There are talks on youtube that cover the concept of it, which is probably the best you're going to get:
https://www.youtube.com/watch?v=6Ji2q3WQE78

Sign up to Milanote for free with no time-limit: https://milanote.com/thatguyglen

This Rain World documentary details the development of indie 2D pixel art survival platformer Rain World and goes behind the scenes of its creation. Discover more about developer Videocult and its two founders, Joar Jakobsson and James Primate. The very first prot...

▶ Play video
wicked scroll
wicked scroll
clever bridge
#

Hi, I have some code to point a hose at a target point, but it's not quite doing it right, I have a player moving back and forth, their scale x is 1 or -1, when it's -1, the aim is off a bit and I don't know why

        var AngleDeg = Mathf.Rad2Deg * AngleRad * tank.transform.localScale.x;
        hose.transform.rotation = Quaternion.Euler(0, 0, AngleDeg);```
frosty snow
#

how does the view model system differ from the entity component system

cosmic rain
#

One separates visuals logic and business logic. The other separates data and behavior.

They're kind of in different realms entirely.

frosty snow
#

which would be easier for saving and restoring data / application state ?

cosmic rain
#

Like a save system?

frosty snow
#

yea

#

im trying to make a hot-reload system

#

and i would like it to be easy for people to implement hot-reload compatibility

without for example, needing to make every class they use/make annotated with serializable annotations and such

cosmic rain
#

Then maybe ECS? It should make it easier to save/load the data as is.

#

Honestly, I'm not sure how view model pattern even is relevant in this context.

frosty snow
#

the view model pattern basically just ummm operates on read-only data right?

#

(the actual data is writable outside the model but read-only inside the model)

pale plover
#

Hi, I'm writing a server that I'd like to use to perform a number of simulations quickly, independent of frame rate (the server wouldn't be rendering anything). Is it as easy as putting the code in FixedUpdate? I'm having a difficult time googling an answer, and I tried using GPT, but it said to use async/await. I thought async would still run synchronously if there is no await. If anyone could point me in the right direction, I would appreciate it.

frosty snow
#

Physics.step and multiple Physics Scenes (i think)

mellow sigil
#

If you just want to run a simulation and get the result, you don't need to put it anywhere. Just run the simulation.

pale plover
#

I feel dumb, thank you. I had a feeling I was making it more complicated than it needed to be

frosty snow
#

do note that this depends on what you require

#

for example, if you need to simulate physics temporarily (eg, for predicions and such) then a second physics scene must be used

if you need to adjust the physics speed (how many times fixed update is called) then Time.fixedDeltaTime and Time.maximumDeltaTime can be used to achive that, the lower its value the faster the simulation will run

pale plover
#

thank you, again. Appreciate it

cosmic rain
frosty snow
#

how so ?

cosmic rain
#

Because it's irrelevant. The main concept is separation of business logic from presentation.

frosty snow
#

eg

Label {
    public string text => data().text();
    // or a more effiecent binding that updates the text variable and causes a redraw when ever data.text changes
    ...
}
cosmic rain
#

This is just a property that retrieves a value from the data. I don't see how it's alone is relevant to a design pattern.

#

Typically in Model view you'd have 2 classes that perform the model and the view role. The model class is responsible only for the business logic, while the view is responsible for the presentation logic. The interactions between them and their specific implementation doesn't really matter.

#

There are all sorts of variations like MVC and MVVM, but the general idea is separation of logic from presentation.

cosmic rain
#

Data binding is not necessarily related to MV.

silver crescent
main turret
#

Does anyone use Firebase there ? I wonder that Is this method is necessary ?
I try to not use this line but other functions related to Firebase working properly.

mossy snow
#

well based on the docs, if you don't call it firebase might just not work for some users. Why do you want to skip it? Seems like a weird decision

knotty sun
main turret
#

Thanks all !!

deft timber
#

I'm saving data through BinaryFormatter, and I get such error when im trying to save a List of scriptable objects.

SerializationException: Type 'UnityEngine.ScriptableObject' in Assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

#

i have marked it as serializable

#

so im not sure what's wrong

quartz folio
deft timber
#

or am I trying to serialize something, that just cant be?

deft timber
deft timber
quartz folio
#

and do they inherit from ScriptableObject

deft timber
#
[System.Serializable]
public class PlayerDeckUnitSlot
{
    [Header("Settings")]
    public UnitData assignedUnit;
    public bool isAssigned = false;
}
#

no

quartz folio
#

They have a UnitData in them.

#

Which does, which is the problem

deft timber
#

so there is no way to save the scriptable objects at all?

#

cannot change the architecture for it that far into development

#

I guess I can make some kind of workaround of it, since i have serializable Dictionary<enum, UnitData>

#

so i can save the enum, then map it to proper UnitData, then set it to the loaded list

#

found by Unity Staff member

south violet
#

Can I get same random values using Random.InitState(seed) on different computers? I generate some data on one computer and Id like another computer to generate exactly the same data. I tried to find answers on google so hard, but I feel like some ppl think its possible and some its not

#

I did try it, but didnt work

rigid island
#

indeed, if "its not working" something is wrong with how you're generating

south violet
#

It seems it doesnt always work. I generated data twice with the same seed on one PC and data were exactly the same, but when I tried to generate on different PC and compare then data from these two PCs, they werent equal

rigid island
#

break down the problem into smaller issues to solve

dawn nebula
crystal fulcrum
knotty sun
dawn nebula
#

Right?

knotty sun
#

I just roll my own Random, it's not that hard

dawn nebula
#

How very programmer of you.

knotty sun
#

that's me, old, old school

dawn nebula
#

I can see the value of a Static random class, but I think I would have preferred like...

#

Random.Default.Range(...);

#

Instead.

#

Like some default static instance was always available, but nothing was stopping you from instantiating another.

knotty sun
dawn nebula
#

why is that?

knotty sun
#

not random enough, way too much chance of it being manipulated

dawn nebula
#

huh

quaint rock
dawn nebula
#

Ya I'm aware. We talked about that. Was just ruminating on how it's a shame you can't have multiple instances of Unity's Random implementation.

fiery path
#

Hey guys, I have an issue where when a level reloads, when the player tries to aim, I get missing reference errors. Ive looked about online but issues tend to be personalised. The thing with my debugging is the references still seem to be there in play mode meaning the script should be able to access it

(for e.g line 125 LeanTween.scale(crosshairDot, new Vector2(1f, 1f), .2f) .setOnComplete(() => Crosshair());, the script still has this game object within the inspector, this is the same for the animator)

Any help?

quaint rock
lunar python
quaint rock
fiery path
# lunar python did you destroy any object on reload?

not that i am aware of, i have a trigger where when the player falls it simply reloads the scene (delay for a fade animation) private IEnumerator OpenLevel(float waitTime, string level) { yield return new WaitForSeconds(waitTime); SceneManager.LoadScene(level); }
Its weird as everything else works and those references are still present in inspector

#

and the original crosshair() function still plays upon start to make it appear in the first place

#

meaning... it exists

dawn nebula
#

But... ya.

#

Bit awkward.

lunar python
#

maybe get someone experienced in a call would be quick fix

fiery path
rigid island
tawny elkBOT
lunar python
#

do you use drag and drop or GetComponent<>

fiery path
lunar python
#

hmm thats kinda buggy

fiery path
#

still learning

rigid island
#

no

fiery path
#

also aware the manager can be a lot more optimised

lunar python
#

no but i just don't like idea

fiery path
#

yeah thats fair

rigid island
#

put this before line 125 Debug.Log(crosshairDot, gameObject)

#

also you should probably fix your other errors so your console isn't spammed with errors

fiery path
#

is it to do with the ui manager instance

rigid island
#

dont clip screeeshot of error, show the whole stack trace

rigid island
fiery path
#

1 of each

rigid island
#

looks like you're trying to use functions on destroyed animator component

rigid island
#

how many did it print

fiery path
#

the animator it is referring to is still there in inspector which is the confusing part to my head tho

fiery path
lunar python
#

also remember to apply to prefab

rigid island
lunar python
#

did you destroy the gameobject and instantiate a prefab without the applied changes?

fiery path
#

i am unsure but it is fixed

    {
        if (_animator != null)
        {
            myCamera.Priority += camPriority;
            uiManager.CrosshairAimed();
            _animator.SetBool("isAim", true);
        }
    }

    private void StopAimPlayer()
    {
        if (_animator != null)
        {
            myCamera.Priority -= camPriority;
            uiManager.ResetCrosshair();
            _animator.SetBool("isAim", false);
        }
    }``` 
I added a null check but now it works fine
#

might have been a prefab issue

#

really dont know

#

thank you tho guys

lunar python
#

also check for script execution order

#

as some objects may load in before others

#

so make custom Start so the dependencies gets loaded in first

rigid island
fiery path
#

im aware

#

is referencing my ui manager within awake an issue

rigid island
lunar python
#

remove the null

#

and check again

#

might cause future headache if we patch things like that

fiery path
#

im not spawning the prefab with the animator at any point

rigid island
fiery path
#

or to my knowledge destroying it

fiery path
#

uiManager.ResetCrosshair();

#

for example

rigid island
lunar python
#

give full code

fiery path
#

so this seems to be the main script causing the issue

#

the interesting thing is the same animator is being used by the player controller script

#

and the movement animations play fine, no null error

#
        _animator.SetFloat("side", sideValue);```
#

seems to only be aiming

#

again, only when reloaded

rigid island
#

your sub to those inputs look wrong

sage plaza
#

hello, I have encountered a problem can you help. My for loop returns 7 times and my value always returns 7 times 1 or 7 times 0 when I restart the project for example: 1 1 1 1 1 1 1 1 1. What I want is that my test value returns 1 or 0 7 times example: 1 0 1 1 0 1 1 1 1 0 like this. here

public void ValuesRandom() { for (int i = 0; i < damagedParts.Count; i++) { test = Random.Range(0, 2); } }

fiery path
hard viper
#

i’ve been having issues setting an animated tile back to its initial start frame. I’ve been trying Tilemap.SetAnimationTime(), but when I do, I see the tile flicker, but still end in the wrong frame.
Advice?

lunar python
#

idk what is InputAction

rigid island
hard viper
rigid island
#

wel diff values but same variable

sage plaza
lunar python
#

if test is string or array do test[i] where i is index

rigid island
#

that wont work

sage plaza
#

test is int

lunar python
#

what

sage plaza
#

I'll tell you what I'm trying to do.

rigid island
lunar python
#

oh

rigid island
lunar python
#

so string is immutable in c#?

rigid island
#

correct

sage plaza
#

I have car parts and I am trying to determine whether they are damaged or not, so I used bool and I will determine whether it is damaged or undamaged with random, this is the code I wrote.

`bool testbool;
int test;
public void ValuesRandom()
{
for (int i = 0; i < damagedParts.Count; i++)
{
test = Random.Range(0, 2);
}

    for (int i = 0; i < damagedParts.Count; i++)
    {
        if (test == 0)
            testbool = true;
        else if (test == 1)
            testbool = false;

        damagedParts[i] = testbool;
    }
}`
tawny elkBOT
lunar python
rigid island
#

just set damaged directly on the parts during the loop

sage plaza
#

yeah

rigid island
#

you dont need this int assigment at all

lunar python
#

you need an array which is a series of numbers to store multiple numbers

rigid island
#

nah you dont even need that

#

if the parts are already in array they should just have an isDamaged bool

lunar python
#

yes but we need him to know how code works

rigid island
rigid island
#

they need to learn how to iterate through their carparts and assign the value depending on a random number

lunar python
#

I think he is thinking that the 2 for loops are executed at same time

sage plaza
#

im junior dev this is my case a actually

lunar python
#

code executes from top to bottom

rigid island
#

the logic is somewhat valid but not for 7 times

rigid island
#

again also doing 2 loops for that is unecessary

sage plaza
#

yeah i know im just testing

rigid island
lunar python
#

anyway this should move to begginner

lunar python
#

dont give him code teach him

sage plaza
rigid island
sage plaza
#

Actually, I'm not very new, I just said yes to avoid beating around the bush.

rigid island
#

you're def missing some basics on how the code is working

lunar python
#

anyway I have 2 collider in the same object. How do I GetComponent<>() to one specific

rigid island
#

you don't , you use the inspector

#

if the collider types are different then you find the specific type

lunar python
#

what if my future enemy has a random number of child objects with colliders

#

how do I control it

rigid island
#

you put them in an array of Colliders and you can loop through them

#

GetComponents is also a thing

lunar python
#

okay nice

sage latch
#

You could also create a component on the enemy that keeps track of one of them. Then make a public getter

rigid island
#

yeah also an option

lunar python
#

why cant we have name for colliders

#

would be nicer

hard viper
#

yeah, you need to use a monobehaviour to link them to specific variables for that

#

I’m trying to make a system where a front of ice/heat can propagate through a large tilemap of water/ice, affecting the nearest neighbor over time. Any suggestion on how to best represent/do this?

lunar python
#

Also do we have some way of having code hierarchy in inspector

hard viper
#

inspector for a given script shows different fields depending on the order of attributes you give.

lunar python
#

I mean by script hierarcy like in go dot

hard viper
#

example:
[Header(“Heading”)]
[SerializeField] private int jumpHeight;
public Collider2D playerCollider;
[field:Header(“Next section”)]
[field:SerializeField] public int autoProperty {get; private set;}

fervent furnace
#

cellular automaton

hard viper
rigid island
hard viper
#

you can set a gameobject as a child of another gameobject

#

if that is what you mean

#

so I might have my player gameobject with a collider and player movement etc. Then a child gameobject might be a sword it is holding, which has its own collider and sword script.

#

but multiple components within the same gameobject are basically not sorted with any hierarchy

#

Godot enforces more hierarchy in that regard

#

Unity has a hierarchy of gameobjects, which contain scripts. Unity does not have a hierarchy of scripts.

hard viper
lunar python
#

ye

lethal lintel
#

I have a general concept question for a project I'm doing but not sure where to start.
I want to convert a video into a image sequence.
From that video sequence convert it to a sprite sheet.
Then apply that sprite sheet to a character
I know I can do this outside of Unity, but I want this entire process to work within my Unity Game.

Anyone got any ideas?

hard viper
fervent furnace
#

https://www.youtube.com/watch?v=5Ka3tbbT-9E
i have no idea why this vidoes appeared in my youtube home page but you can have a look

Download and play with this simulation here: https://tinyurl.com/43dzu9r5

Java Repository: https://tinyurl.com/88ndcdez
C++ Port Repository (In Progress): https://tinyurl.com/a246r6pp

Links:
All the old Java Applets: https://androdome.com/Sand/
Exploring the Tech of Noita: https://www.youtube.com/watch?v=prXuyMCgbTc&t=322s
Conways Game of Life...

▶ Play video
fervent furnace
#

i think you can apply energy for each cell and simulate the transfer of energy in each tick

hard viper
#

i’ll take a look at the vid later, when I have a break. In my case, I’m thinking about making the delay time a float.

#

one note is that it isn’t a state function. If I have water in contact with ice, the result is different if I’m propagating a freezing wave outward, of thawing wave

#

actually, I have an idea to use a separate grid. ty tina

lucid tulip
#

Hey everyone, just working on optimising some code right now. I've found a section that updates a sprite every frame, however often it's just setting it back to the same sprite. I presume this has a performance cost associated with it, so I'm trying to figure out how to best improve this. Currently the code is as follows

sprite1
sprite2

if sprite != sprite1 && other condition
  sprite = sprite1
else if sprite != sprite2
  sprite = sprite2

Is there an even more performant way of doing this check? Obviously I'm comparing sprites, and I'm unsure if it just uses the memory address to check if the references are the same or if it's doing something heavier. I considered checking the name or the hash. What do you think?

somber nacelle
#

I presume this has a performance cost associated with it
have you profiled it to see if there actually is a performance cost worth worrying about?

lucid tulip
#

Well there is noticeable lag caused by this system on device, however I can't see anything particular in editor unfortunately. Because of this I'm working through the code just to see what could be causing potential issues with it

#

I should note that I'm shooting in the dark here because the profiler isn't providing any useful information about my situation

#

Or more likely I'm missing something

#

Also is it even worth getting the hash? I've just realised I could just as well use a bool

rigid island
lucid tulip
rigid island
#

send them a dev build and you can also setup a remote profiling by IP connect

lucid tulip
#

just an int check if level >= level threshold

lunar python
#

setting sprites isn't that costly

#

you can use switch instead but that would be premature optimization

lucid tulip
#

It was being set in the update loop, so I figured it's definitely doing more than it needs to

lunar python
#

an animation can even change sprites tens of time per second

lucid tulip
#

true

lunar python
#

anyway how is that even costly

#

can I see full code?

lucid tulip
#

Unfortunately I can't show the code. I don't reckon that is the issue anyway, I just wanted to know if/how much a difference it would make

#

I'm looking at some previous commits to see if anything jumps out at me. My biggest issue is not being able to replicate any performance issues on my end...

leaden ice
lucid tulip
wraith spear
#

How does LogAssert.Expect() work with the Unity.Logging package?
The following code fails:

LogAssert.Expect(LogType.Log, "All allies are defeated");
combatLoop.EndOfTurn(); // runs Unity.Logging.Log.Info("All allies are defeated");

While this succeeds:

LogAssert.Expect(LogType.Log, "All allies are defeated");
Debug.Log("All allies are defeated");

#

I don't see this case mentioned in the Docs, and Google hasn't been helpful either.
In both cases, I see a Log appear in the Console

leaden ice
wraith spear
# leaden ice What does the success of failure message say? Are you sure it's not failing for ...

Fairly certain. The message is Expected log did not appear: [Log] All allies are defeated.
The only difference is the way it's logged (Debug.Log vs Log.Info). And I do see the Log.Info message in the Console, so I know it does get hit:

All allies are defeated
Logger:Log(LoggingLevel, String) (at Assets/Scripts/Logger.cs:29)
Battle.<AlliesAreDefeated>d__13:MoveNext() (at Assets/Scripts/Battle/CombatLoop.cs:159)

It does get called from an IEnumerator (CombatLoop start the Coroutine). Does that matter?

#

And the messages are identical; I've copy-pasted them over

leaden ice
wraith spear
# leaden ice What is Log.Info. Isn't LogAssert.Except expecting Debug.Log calls specifically?

It's from the Unity.Logging package. Full method call is Unity.Logging.Log.Info(string message);
And I don't know for sure if it is expecting *onl Debug.Log. The official documentation says:

"LogAssert lets you expect Unity log messages that would otherwise cause the test to fail. A test fails if Unity logs a message other than a regular log or warning message. Use LogAssert to check for an expected message in the log so that the test does not fail when Unity logs the message.

Use LogAssert.Expect before running the code under test, as the check for expected logs runs at the end of each frame.

A test also reports a failure, if an expected message does not appear, or if Unity does not log any regular log or warning messages."

#

I would expect it to work with the Unity.Logging package, but it seems like it doesn't

leaden ice
wraith spear
#

Difference in message:
Log.Info:

All allies are defeated
Logger:Log(LoggingLevel, String) (at Assets/Scripts/Logger.cs:29)
Battle.<AlliesAreDefeated>d__13:MoveNext() (at Assets/Scripts/Battle/CombatLoop.cs:159)

Debug.Log

All allies are defeated
UnityEngine.Debug:Log (object)
Tests.Battle.CombatLoopTests/<Allies_Are_Defeated_Triggers_When_All_Allies_Are_Defeated>d__0:MoveNext () (at Assets/Play Tests/Battle/CombatLoopTests.cs:32)
UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)

leaden ice
#

I guess you have your answer then?

wraith spear
#

I can't really change the Logging in my game to Debug.Log. However, I would very much like to test whether messages appear in the Logging

wraith spear
leaden ice
#

gotcha I think I'm finally caught up on your original question 😆

wraith spear
#

Npnp

#

Ah, maybe Unity.Logging has its own Test package, I'll have a look

#

Yeah, found the answer:

It’s not natively supported by the Test Framework, a workaround is to use the WriteTo.UnityDebugLog sink at the cost of a negative performance impact.

Thanks for the help regardless, Praetor

winged tiger
#

hey i need to deserialize json formatted string into classes, but there is like 5 diffrent classes. How do I determine witch class to use? Every class has a "type" key (string)
thanks

quaint rock
winged tiger
#

wait

#

can I use something like

public class Base{
  public string Type;
}

public class A : Base{
  public float test;
}
[...]
quaint rock
#

you could, but you would still need to do things twice

#

first get base, figure out what type is, then choose your final type for the 2nd pass

winged tiger
#

ah yeah

quaint rock
#

which json lib were you using?

neon plank
#

What means when NavMeshAgent.isOnNavMesh is true, but NavMeshAgent.navMeshOwner is false?

deft dagger
#

hey i need help with lighting...
whenever i try to build my game the lighting in the build is shutdown
how do i fix it ?

lucid tulip
#

Are you using baked lighting?

deft dagger
lucid tulip
#

You have realtime lighting and baked lighting. Baked lighting "bakes" the lighting data into the scene's textures. Realtime lighting allows for moving lights. If you're not bothered about performance you can make sure your lights are set to real time, otherwise go to Window>Lighting and bake the lighting into the scene

deft dagger
#

thanks

severe creek
#

hey i have script to move a navmesh agent to a position. Is it possible to assign multiple navMehAgents to one variable?

leaden ice
#

For example you can have a List<NavMeshAgent> to store as many agents as you want.

severe creek
#

i know that those exist but how do i change a navmeshagent into a navMeshAgent array?

leaden ice
#

you put a NavMeshAgent into an array

#

along with other agents

rose fulcrum
#

@hexed pecan COMPLETELY forgot to tell you both thank you. Turns out I just added a wrong script with a similar name to the component and not the script that inherits from IInteractable. smh.

severe creek
west lotus
#

List<NavMeshAgent> agents;

leaden ice
severe creek
west lotus
#

You can

leaden ice
#

once you have a reference to a specific agent you can call functions on it

#

you would need to get the specific agent you want out of the list and do what you want with it

#

If you want to do something to all of them, you can use a loop to iterate over all of them and do the same thing to each

severe creek
#

thanks

clever bridge
#

Hi, I have some code to point a hose at a target point, but it's not quite doing it right, I have a player moving back and forth, their scale x is 1 or -1, when it's -1, the aim is off a bit and I don't know why

var AngleDeg = Mathf.Rad2Deg * AngleRad * tank.transform.localScale.x;
hose.transform.rotation = Quaternion.Euler(0, 0, AngleDeg);```
past hare
#

for unity netcode i have three two different ui, one for the gameMaster and one for each player,

im unsure how to give players their own seprate ui because their uis keep overlaping

past hare
#

thanks

rapid stump
#

Hey! I'm trying to make a button open my SettingsPanel, but when I attach my script to the buttons "OnClick" event I don't see my Open and Close functions in the function drop down menu.
What could be causing this?

mellow sigil
#

You need to attach a gameobject that has this script as a component, not the script itself

rapid stump
#

OH, thank you so much lol

scarlet viper
#

any idea how can i code a script that will always keep a folder opened in assets inspector window? (not the inspector, just the unity's file window)

#

maybe if theres a callback whenever you click on files

#

then i could check if its opened there, if not then open

#

idk if theres even api to do this

hexed oak
#

like keep a specific folder open?

scarlet viper
#

ye like they close sometimes

#

for example keep this always open (so that its children are visible in the folder tree)

orchid finch
#

Is there any suggestions on how to make multiple objects move as one until a specific action is done and then make only some of the objects start moving seperatly?

hexed oak
#

parent them all under one gameobject, then when specific action is done swap some to a different parent

orchid finch
#

Should have specified that objects are physics based or will work either way?

lean sail
orchid finch
#

that can be broken down

west lotus
#

Keep the rigidbodies on the pieces kinematic then when they are hit set them to non kinematic and detach them from the parent

#

That would be the simplest option. Now if we are talking actual demolition there a bunch more work to be done on clustering, separation, structural integrity and so on.

#

Ie if you don’t want floating pieces

lean sail
# orchid finch that can be broken down

Broken like piece by piece? Or damage any piece of a wall and then it all breaks?
What Uri said above works for piece by piece. If you want to destroy the whole thing I'd just have it as one object and replace the whole wall with a destroyed version when it should break

orchid finch
#

broken into like cubes/parts

orchid finch
#

ig it will work in a way kind of

jaunty sundial
#

why when you change a cinemachines follow target in code it will stay like that but if u change it in an animation it doesnt work

steep herald
#

Say I have something like this

[Serializable]
public class Wave
{
    [SerializeField]
    private float duration = 60f;
    [SerializeField]
    private float cutOff = 0.3f;
    [SerializeField]
    private int maxValue = 10;
    [SerializeField]
    [Range(0.1f, 10f)]
    private float noiseScale = 1f;

}

Then, in another class, I serialize a list of the "Wave" above. When I add a new instance to the list via the inspector, it's added with default values rather than the ones defined above / the standard behaviour when adding components.

How can I make sure new instances are added with the values defined in the class?

timid depot
#

hey, when I slow down game scale Time.timeScale = 0.1f; whole game is snapping, can I somehow change physics update interval?

#

it's not smooth at all

#

fixed, found it in project settings > time

warm night
#

Hey, I have a little problem. I have a hex grid system, with a pathfinding system. My list of tiles for a path is given correctly. I wanna add some directional arrows to show the path on the tiles. the arrow is just a sprite renderer (it's in 3D). I tried everything to rotate the arrow at index N to the tile at N+1, but it never works, does anyone could help me please? 🙂

strange yacht
#

Hi, could you provide your current code for the arrow rotation

warm night
#

Sure, I'll give you that

#

I tried this

 public void ShowArrowTowards(Tile tile)
 {
     Vector3 direction = (tile.transform.position - transform.position).normalized;
     this.displayInformationRenderer.sprite = arrowSprite;

     if (direction != Vector3.zero)
     {
         float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

         angle -= 90f; 
         displayInformationRenderer.transform.rotation = Quaternion.Euler(0f, 0f, angle);
     }
 }
#

I also tried transform.Rotate(); transform.LookAt(); transform.eulerAngles = new Vector3(..)

#

I never found a solution on internet lmao

strange yacht
#

and what are you seeing ? no rotation or incorrect rotation ?

warm night
#

Incorrect rotation, let me show you what that code gives me

#

the arrows are... really facing up. However, if i took one in the scene, and just set rotation to (0f, 0f) on x and y, and manually change the z value, it rotates well, so that's why I tried to do

Quaternion.Euler(0f, 0f, angle);
#

This is the rotation given by the inspector

#

idk why it gives me this, but... yeah

strange yacht
#

and on the picture you set the arrows to indicate toward which direction ?

dusk apex
#

Maybe set the local rotation if you want the inspector to match?

warm night
#

Each arrow has to indicate towards the next tile, i tried to raycast to see the path, and it goes well, but not the rotation

quartz folio
#

Don't look at the inspector and assume it's going to be the same value you set it code. Euler angles derived from quaternions can be different representations of the same orientation

dusk apex
#

Else print the rotation in euler and ignore the inspector value

warm night
#

Okay i see

warm night
dusk apex
#

I don't think you'll get what you want but maybe it'll be a bit more understandable from the inspector relative to location rotation.

warm night
#

fact yup, now we can see flat arrows, but as u said, they're not facing to the next tile

#

that's completely weird, because I'm taking Atan2 of the direction, so it has to get the good value tbh

dusk apex
#

Log the result and values to see if they're what you're expecting.

#

Were you feeding arc tan directions?

warm night
#

I'm doing some raycasting and printing values, but to be honest for the first arrow, it has to be approximatively 120 in Z axis, but it returns me 90

dusk apex
#

Ah nevermind

warm night
#

The raycast of the direction is correct, as u can see

dusk apex
#

Was the direction vector as expected for each?

warm night
#

yeah

dusk apex
#

You should be able to visually confirm

warm night
#

the direction is as expected yeah

dusk apex
#

So the resulting angle isn't?

warm night
#

yeah

#

that's the problem, and a weird one

#

maybe i'm not using the Mathf.Atan2 correctly, i'm not kinda good at math

dusk apex
#

The value would be in radians. Is that what you're expecting?

warm night
#

Yeah, but i''m converting it in degrees

#

using Mathf.Rad2Deg

dusk apex
#

Ah, I'm on mobile. The screen is small.

warm night
#

sorry :/

#

i just saw something on a website which tells me that it can be caused by the values passed in mathf.atan2

dusk apex
#

Can you log the direction vector and the resulting angle?

warm night
#

They're using Mathf.Atan2(-direction.y, direction.x) instead of Mathf.Atan2(direction.y, direction.x), i'm gonna use that

#

sure

dusk apex
#

Showing us the console log, if possible.

warm night
#

yeah yeah np

#

I tried to put -direction.y to try as well

#

and just so you know, i just do angle -= 90f, as well so if u want the real result of Atan2, you'll have to add 90

dusk apex
#

So y is zero

#

Maybe you're wanting z/x?

warm night
#

oooooh

#

that's smart

dusk apex
#

arctan(z, x)

warm night
#

let me try,

somber nacelle
#

also if you just want the sprite's Y axis to point at the position, just assign its transform.up to the direction. no need for the atan2

somber nacelle
#

displayInformationRenderer.transform.up = direction

warm night
#

now we have something interesting

#

I'm gonna try your thing instead @somber nacelle

#

tbh i didn't even know that we can change transform.up

#

that's weird

dusk apex
#

There seems to be a pattern UnityChanHuh

warm night
somber nacelle
#

show the current code

warm night
#

or invert, i'm gonna try all possibilities

#
public void ShowArrowTowards(Tile tile)
{
    Vector3 direction = (tile.transform.position - transform.position).normalized;
    this.displayInformationRenderer.sprite = arrowSprite;

    Debug.DrawLine(GetDisplayRenderer().position, tile.GetDisplayRenderer().position, Color.red);

    if (direction != Vector3.zero)
    {
         float angle = Mathf.Atan2(direction.z, direction.x) * Mathf.Rad2Deg;
         angle -= 90f;
         Debug.Log("direction vector = " + direction + " | angle = " + angle);
         displayInformationRenderer.transform.localRotation = Quaternion.Euler(0f, 0f, angle);
       // displayInformationRenderer.transform.up = direction;
    }
}
#

That code is for the first screenshot

#

And if you want the code for the 2nd one, just inverse the comment and code in the if statement lmao

#

i tried -direction.z, direction.x and i got this, i think if i delete the -=90f, it could work

#

it works !!!! let's go thank you guys

#

it tooks me a few hours to come here because i thought i could resolve it xD

kind panther
#

hi guys

#

i have a bit of a problem

#

im making a minecraft inv system and its pretty much a copy

#

but theres a problem on the right click

#

dammit

#

how do i upload a small vid showing whats off

cosmic rain
unborn flame
copper imp
#

hello there!
i got a problem with reading a json file
its especially about this part

{
  "possibleMoves": [
    ["E4", "E5"],
    ["A2", "A3", "A4"],
    ["B2", "B3", "B4"],
    ["C2", "C3", "C4"],
    ["D2", "D3", "D4", "E3"],
    ["F2", "F3", "F4", "E3"],
    ["G2", "G3", "G4"],
    ["H2", "H3", "H4"],
    ["B1", "A3", "C3"],
    ["D1", "E2", "F3", "G4", "H5"],
    ["E1", "E2"],
    ["F1", "E2", "D3", "C4", "B5", "A6"],
    ["G1", "E2", "F3", "H3"]
  ]
}

the class im trying to get it into looks like this

[Serializable]
public class ChessData
{
    public string date;
    public string result;
    public string site;
    public string white;
    public string moveSuggestion;
    public List<List<string>> possibleMoves = new List<List<string>>();
    public string promoteTo;
    public string black;
    public string history;
    public string @event;
    public List<OccurredPosition> occurredPositions;
    public string FEN;
}

it doesnt throw any errors but just cant read the content, does anyone know how to get it working?
if i try it with logs it give me 13 empty lists

somber nacelle
somber nacelle
copper imp
#

is there a way arround that?
or only possibility to adjust the format of the JSON?

warm night
somber nacelle
copper imp
#

i think i might just go with not having nested lists then, ty for fast answer

warm night
#

Np

hard viper
#

how many people use giant switch case blocks for logic?

#

i try to avoid that as much as I can, and use delegates, but I feel like I should just use switch case more liberally

latent latch
#

usually up to 5 then I break it more into sub-types / sub-states

quaint rock
#

like what it switching on?

#

if its just a enum, and its getting big you can just pass functions around directly, or use a interface type

hard viper
#

when I say giant switch case blocks, I mean 20+. It doesn’t depend. You do this, or you don’t.

cosmic rain
#

What are you gonna do with that information though?😅

quaint rock
#

20 is still in the it depends region it really depends on what its for

#

what you are switching on and why

#

like if its a switch over enums, and the enums are only used for choosing what logic to run

#

would just pass functions directly in that case, or a object that has overriden methods

#

really most questions like this come down to use what works for you in the moment, and if you start feeling a lot of friction doing that figure out why and come up with a new approach

hard viper
#

reading the room

lean sail
#

If you're looking for justification to keep your current method, maybe start look at redesigning.
Out of like 100 scripts I have, I think I used a switch once on an enum with 5 options. Having to do this often sounds like a design issue

hard viper
#

my personal limit on switch case blocks is 6

#

but i see some people writing some giant goddamn switch case blocks, and I want to know how common of a practice it is

lunar python
#

you dont write giant switch cases

#

learn how loops work

hard viper
#

how does a loop replace a switch case, my man

lunar python
#

a loop with conditional ifs and an array of constants

lean sail
#

What on earth..

lunar python
#

if the conditions have a pattern better code that way

hard viper
#

maybe help me out. I have this code:
switch (cardType) {
case “PotOfGreed”: hand.size += 2; break;
case “Cow” : milk++; break;
case “Corn”: player.health++; break;

}

#

how does this turn into a loop

lunar python
#

you dont code it that way

hard viper
#

no. you said to learn how loops work

lunar python
#

use an integace

#

interface

hard viper
#

no. you said to learn how loops work. Now you teach how loops fix this issue

lunar python
#

these dont have any patterns

hard viper
#

i was working with a guy the other day with a switch-case block with >120 cases

lunar python
#

that would be hard to read

hard viper
#

trying to get him to something not cursed. and I want to know how common that practice is

lunar python
#

i dont think anyone would want to go through all of that

hard viper
#

yet here we are

#

it exists

#

and it is exactly as cursed as papa always said

lunar python
#

just interface ICardEffects and executeEffects()

hard viper
#

I tried to guide him towards that, but he’s on GDScript, which lacks interface support.

#

So that is not an option

lunar python
#

you could try abstract classes

hard viper
#

that’s what I was leaning towards.

#

anyway, point being, I want to know if there are any more degenerates out there

#

writing giant switch case blocks

lunar python
#

yes my friend bruteforced 100 if else to solve a problem for kindergartens that only requires 5 lines

lean sail
#

Even with the interfaces or abstract class, you lose out on some ease of setting things up in inspector. Now you have to do some custom editor stuff

hard viper
#

i think the core question is to tie a specific enum to a particular function

lunar python
#

I mean if its card effect, it only affect one of the two player right?

hard viper
#

i already sketched out a solution for him a while back

#

abstract class was my main recommendation

#

he did not like the idea of defining 120 different classes

lunar python
#

Action is a useful class

#

you can add functions to existing functions

hard viper
#

you still need a way to tie the delegate to the key/enum

lunar python
#

repeated actions on cards can be reduced to AddCard(), FindCard(), DestroyCard(), BanishCard()

#

most yugioh effects can be reduced to about 20-30 functions

#

they summon bunch of stuffs and do random things

lean sail
#

only thing that matters is how this affects the users experience

lunar python
#

why must we have key and enum

#

like Dictionary?

unborn flame
somber nacelle
#

you're still not bothering to use a layermask like i suggested before so your OverlapPoint is likely just detecting the npc object instead of the room object

rain minnow
somber nacelle
unborn flame
somber nacelle
#

Yes

unborn flame
#

ok let me try agin

hard viper
nimble cairn
#

Hi guys I have a moving platform and I want the player to move alongside the platform.

To achieve this, I parent/unparent the player to the platform.

However, and here's my question: When the platform is moving (XYZ) the character controller and camera are rather "janky" and dont' move/flow smoothly they instead jitter with the platform.

Anything I should consider when trying to achieve a smooth look for this?

cosmic rain
nimble cairn
#

Spring joints

cosmic rain
#

moving the platform

nimble cairn
#

I was thinking, add the velocity of the object to the controller.Move() method

#

Spring Joints

cosmic rain
nimble cairn
#

Thanks, due to the volatile nature of the spring joint bridge, I think this coupled with setting the parent of the player to the bridge itself

#

would solve the issue

west lotus
#

You dont parent when you set the velocity

nimble cairn
#

Oh, really?

west lotus
#

Have a externalVelocity variable in your character. Then in your update resolve it and add it to your move after you have calculated player input. Then add the end of the frame 0 it out.

#

This away any number of objects can add do this external velocity during the frame

nimble cairn
#

Sweet as, sounds like a plan

#

@west lotus Works like a charm, thanks!

cunning escarp
#

How would I go about copying the angular velocity and velocity of one rb2d to another? I can use addforce for the velocity but with addtorque the pivot point is different

dusk apex
#

first.velocity = second.velocity
first.angularVelocity = second.angularVelocity

simple ruin
#

Is it bad to have a ton of serialized fields in something like a title screen

lean sail
lunar python
#

Is using AIModules preferred or should I build my own AI algorithms

#

just asking for your general preferences

west lotus
lunar python
#

like built in packages from Unity to support AI

#

I would like to build more lively AI like in RainWorld

merry harness
#

is there a way to work around enum's lack of compatablility with inheritance?

lunar python
#

just dont use Enum then

merry harness
#

alr

simple ruin
west lotus
west lotus
# simple ruin loose coupling?

For example the game has a OnHealthChanged event that broadcasts the new value. The ui healthbar subscribes to that event via a component and updates its text or image or what ever.

merry harness
#

would trying to instantiate multiple enemy prefabs with one object name for an enemy class break the game?

#

i don't know if there is functionality to generate new names if it wont work

fervent furnace
#

gameobjects can have same name

twilit scaffold
#

What the heck naming convention is this? Vector3 m_Movement; it is in an official Unity Tutorial

#

Oh, it goes on to 'explain' the reasoning behind it. well, i won't be using that one :/ i get it, but a bit too much clarification for me. I will do Vector3 _movement though

#

if any of you more experienced people think i Should be following that convention, please let me know

fervent furnace
#

you dont need to follow any naming convention for you own personal project

twilit scaffold
#

indeed

west lotus
# twilit scaffold What the heck naming convention is this? `Vector3 m_Movement;` it is in an offi...

Hungarian notation is an identifier naming convention in computer programming in which the name of a variable or function indicates its intention or kind, or in some dialects, its type. The original Hungarian notation uses only intention or kind in its naming convention and is sometimes called Apps Hungarian as it became popular in the Microsoft...

twilit scaffold
lunar python
#

hungarian notation is actually kinda useful

#

in projects with multiple people of course

twilit scaffold
#

makes sense. hmm ok, i will consider trying to develop the habit, for when i Do work with others

lunar python
#

well you shouldn't adopt it in a lot of cases

twilit scaffold
#

yeah, i do see a lot of disadvantages, even listed in the wiki

west lotus
quartz folio
#

The C# coding conventions are pinned to this channel

lunar python
#

I just used it because competitive programming used to be single letters variable then we had to work in teams

twilit scaffold
#

I have a terrible habit of forgetting pinned messages exist :/ thanks

#

single letter variables would drive me insane UnityChanLoom

merry harness
#

could someone help explain what went wrong here?

#

it dosen't seem like anything was wrong with my code

#

i was using scriptable objects

knotty sun
#

your ide should be full of red ink

merry harness
#

everything seems valid

knotty sun
#

screenshot your ide with one of those scripts open

merry harness
knotty sun
#

so you are missing a using just like the errors tell you

merry harness
#

which one would it be though?

knotty sun
merry harness
#

using System?

#

didnt work

knotty sun
#

yes

#

is your IDE configured? screenshot the complete ide window

merry harness
analog axle
#

how are you actually supposed to parent a child ghost entity to a parent ghost entity in dots netcode? adding a parent component to the child and setting it after instantiation causes the parent component to not make it to the other side

knotty sun
merry harness
#

visual studios

knotty sun
#

open the Solution Explorer tab and screenshot again

#

are you trying to build in the ide?

merry harness
#

yeah ive compiled code in games before with this ide

#

solution explorer tab?

knotty sun
#

but Unity doesn't work like that, it takes care of compilation

knotty sun
merry harness
#

i dont see it anywhere

knotty sun
#

View->Solution Explorer

merry harness
knotty sun
#

Solution

#

use some common sense, please

merry harness
#

and now?

knotty sun
#

screenshot the ide again

merry harness
knotty sun
#

which OS is this, coz that does not look right at all

merry harness
#

mac

knotty sun
#

how do you open a script?

merry harness
#

double clicking the file

knotty sun
#

ok, close your ide and in unity right click in Project view and then open c# project

#

your Solution Explorer should look something like this

merry harness
#

im getting more ledgible error messages

knotty sun
#

so you have script errors, fix them

cosmic rain
#

Is VS even available on Mac?🤔

fervent furnace
#

yes

#

but idk how the ui looks like in mac...

merry harness
lunar python
#

save all the files

cosmic rain
merry harness
lunar python
#

did you save all the changes?

merry harness
#

been saved

cosmic rain
# merry harness ye

What IDE is that? If the same errors don't appear in unity, then the ide is not configured correctly.

merry harness
#

visual studios

#

it worked normally before

cosmic rain
#

Then something broke. I've no clue how to configure the ide on Mac, so, can't really confirm if you did it right.🤔

mellow sigil
#

VS for Mac is practically a completely different program from VS for Windows and it doesn't work very well with Unity. And MS is killing it, it's end-of-lifing this year. Practically the viable options on Mac are VSCode or Rider

merry harness
simple ruin
#

how do you get to this scene with a remove button

#

i only see this import and redownload shit

wide dock
#

You've only downloaded the package, but didn't include it into the project

simple ruin
#

I'm sorry for being so fucking mad but it's like 1 am and I've been debugging for 5 fucking hours

lean sail
#

i think you cannot remove stuff from that page. I remember having to hide it from the asset store website

wide dock
#

I don't think he wants to hide the package from the package manager

simple ruin
#

I want to delete the package that I guarantee you I've imported into the code

#

Because the very files are there, and I tried to delete the steam VR files but there's residue shit in program files and whatnot

lean sail
#

then delete it from the assets folder

simple ruin
#

And it's breaking the damn project

simple ruin
lean sail
#

program files 🤔

simple ruin
#

Again sorry for being so mad but I would really love to sleep for my damn 8 ams

#

Why unity gotta be so damn STUPID sometimes

wide dock
# simple ruin

Probably a wild guess, but did you try accessing it from Packages: In Project ?

wide dock
#

Package Manager, top left, second option, change to In Project

simple ruin
#

Oh bruh

analog axle
#

oh someone already replied

#

XD

quartz vessel
#

i want to convert a face picture into 3d model with body , just like Readyplayerme . however i want more realistic textures of the body and face

amber haven
#

I'm using visual studio code, and did an update to an extension, really no clue which it was, and suddenly all of my code predictions are gone. How do I fix this?

cosmic rain
cosmic rain
#

Oh, vsc. My bad. Thought it was vs.

amber haven
#

It works for a split second and I can see everything in the correct color then it just disapears..

cosmic rain
#

The best I can suggest is check the config guide again:
!ide

tawny elkBOT
cosmic rain
#

Could be the C# plugin

amber haven
#

It was that last time so ima go to an old version

#

and try

#

I did but I think it broke mid way through version change..

#

going back a month changed nothin

#

I've been coding for at least 5-6 years on many different software but nothing has brought me closer to quitting than stupid vsc breaking every time I update literally anything.

amber haven
# tawny elk

This doesnt help, the vsc page just explains how to set your editor as vsc which Ive done.

#

why cant i have nice things

#

thx for trying to help tho

fervent furnace
#

Just wait
My vsc didn’t work at first (after the new extension published) and one day it came back

amber haven
#

thats good

lone blade
#

I am playing around with 360 videos, just need one cubemap video to test... and no idea where to get a sample. The Unity Interactive 360 sample project no longer exists on the asset store...

cold egret
#
  • I'm making a renderer wrapper that allows to add and remove transforms to render meshes at via underlying implementations. The transforms are going to enter and leave in a large loads at once, and will be slowly removed in between. What would be the best data sctructure to accomplish this? Approximate numbers are 8-24k transforms at once
cold egret
#
  • That's what i'm going for rn. It's good for insertion but horrible at removing, especially when it needs to shift that many items
fervent furnace
#

does it ordered or not

cold egret
#
  • Ordering gives faster lookup, but i'm trying to figure my way around any need to lookup the presence of the transform before adding/removing it. In a nutshell, it doesn't matter for now
#
  • Most likely i'll figure it out
fervent furnace
#

8-24k is not large for maintaining an additional hash table for Transform
btw you dont need to shift the list, just replace it with the last one then pop the last

cold egret
#
  • I was talking about the built-in list. But yeah, i can work it around to remove items manually and not with its method
fervent furnace
#

so dont use built in method if it is not fast enough

iron oar
#

Hey, someone here who knows about unity ads?

They work 100% fine in the editor, but on mobile not. I narrowed down that the ads fail to load, but I dont know further. Anyone here that can help me? Thank you

elder zenith
#

If I cast IEnumerable<ClassNameHere> of a List<ClassNameHere> as (ClassNameHere), does it create a new instance of the class, or is the new variable still going to refer to the one in the list?

if i understand correctly IEnumarable<> stores the position of an instance inside a List. if that's the case what's the proper way to get the actual reference to the instance from it?

Edit: Nevermind, dumb mistake

deft dagger
#

hey i need help with unity relay, when i open another scene additivly, because the player is not moving, when i return to the game scene the player would have been disconnected because of inactivity
how do i fix it ?

vagrant blade
deft dagger
#

ok i will ask the same question in that channel

#

thanks

next salmon
#

Hey guys.
How can i make a good RIGIDBODY fps player controller, that can go up slopes and terrain?

I have a limitation have however:
-i need other forces to take effect on player, such as explosions and etc for rocket jumping, so i can NOT directly set velocity to player input.

#

Any good guides for this out there that go over how to handle slopes and terrain? When normally rb charachter controllers bump into slopes and then get launched off of them.

#

Remember, i need to have rocket jumping so I CANNOT CLAMP OR DIRECTLY SET THE VELOCITY ON ANY OF THE AXIS

vagrant blade
#

I'm sure you can find tutorials online for this. You have to add forces along the slope of the ground below the character, not directly forward like most people do.

hard viper
#

kinematic character controller plugin

next salmon
hard viper
#

i did?

next salmon
#

I said i want external forces to move my player around

hard viper
#

KCC respects collisions

#

do you mean you want to actually use .AddForce

#

which can be easily simulated on a kinematic body

next salmon
next salmon
#

Do i need to calculate the velocity and drag myself?

hard viper
#

the whole point of KCC is to make a kinematic RB move in 3D while respecting collisions vs static and kinematic rigidbodies

hard viper
#

but depending on 2D or 3D changes when the velocity += is evaluated.

next salmon
#

dosnt the fact that this is kinematic mean it can push physics objects of any mass without being slowed down?

hard viper
#

KCC is more like a custom physics solver

next salmon
#

But i dont want my 40kg player to be able to push a 1000kg rotating gate

hard viper
#

I made my own physics engine similar to KCC for 2D. It took me 3 months, and I’m already very comfortable with all the math. You do not want to make your own engine.

hard viper
#

just look at the main video for it

next salmon
#

So it will all be nornal? No weird interactions with physics objects? Its all be done beforehand?

#

I just need to implement addforce?

next salmon
#

Yooo this is amazing. It even has stairs and steps implemented

#

I wont need to clip stairs with slopes!

#

I cant believe its free

hard viper
#

KCC is like its own mini physics engine

#

it does require your own implementation. it’s like a separate rigidbody-like API

#

like you need to tell the KCC where to walk etc, but most of the slopes/stairs/collision/etc is what you are getting in the package.

#

it has a big document on how it works in detail

next salmon
#

Thank you 🙏

hard viper
#

👍

next salmon
#

I dont have to reimplement my own charachter controller for the fourth time!
Ive tried making charachter controllers with the built in component, kinematic rb's, and non kinematic rb's and ive never been able to make any of them work well.

hard viper
#

yeah, a lot of this stuff requires a custom solver

#

which is what KCC has

scarlet viper
#

whats the client equivalent for

if UNITY_SERVER
?

polar ocean
#

Hello guys. how are you?

mellow sigil
scarlet viper
#

makes sense

polar ocean
#

how to not destory object when owner out in photon fusion?

#

I would like to help senior guys..

scarlet viper
#

go ask in photon discord

polar ocean
#

where is photon discord?

scarlet viper
#

idk

polar ocean
#

@scarlet viper Could you invite em?

mellow sigil
rigid island
round violet
#

i got a var set to the type of a struct

i want to check if the var is set or still empty, but VS doesnt let me do a null check, why ?

mellow sigil
#

does "set to the type of a struct" mean that the variable's type is the struct or that it stores the GetType of a struct?

round violet
#
private myStruct varName;```
mellow sigil
#

Struct values can't be null

round violet
#

so the var holds a struct with the default values ?

#

also :
why cant struct in chsarp have default values ?

knotty sun
#

it can

fervent furnace
#

they (class members) have default value

round violet
#

yes, but I cant set a custom one

#

it will be the defautl chsarp one

#

int will be O

#

cant say its 5 "by default"

knotty sun
#

yes

round violet
#

why is that ?

#

if i remember correctly in cpp you can, what's the tech difference that allows cpp to do so

knotty sun
#

of course you can set a struct int member to have a default value of 5

fiery path
#

i had a null reference error i was tackling yesterday on the discord with the help of some others to which no conclusion was really indentified
in the end, I updated mt 'Version Control' package and the error just.. fixed?
anyone know why this may be the case?

round violet
rigid island
#

isnt that a newer c# feature?

fervent furnace
#

unity c# not supports you to do that

#

old version

round violet
#

ah okay

#

sad me

fervent furnace
#
public struct S{
  int x=5;//not support
}
knotty sun
mellow sigil
#

Ignoring that int is not a struct, being able to set the default values of built-in types would be handing you the world's biggest footgun

round violet
#

does this trick works in the c# version unity is using ?

public struct MyStruct
{
  int? myInt;

  public int MyInt { get { return myInt ?? 42; } set { myInt = value; } }
}
#

here the "default value" would be 42 until assigned

knotty sun
#

if (!myInt.HasValue())

round violet
#

what is HasValue here ?

#

a extra method ?

knotty sun
#

checking your nullable int

round violet
#

okay

knotty sun
#

really all int? is doing is adding another bool to the struct

round violet
#

a bool to the struct, or to the int var ?

knotty sun
#

to the int var but as the int var is part of the struct to that as well

round violet
#

okay

round violet
#

is this permited ?

knotty sun
#

yes

round violet
#
private myStruct? varName;```
knotty sun
#

then use HasValue to check if its not null

#

yes

round violet
#

okay great

#

ty

round violet
knotty sun
#

maybe, I always use HasValue

round violet
#

yes its better, i was just wondering

#

well ty for all

knotty sun
#

I believe == null will work

#

need to check the Nullable struct docs

round violet
#

well now VS tells me that I cant access my struct members

knotty sun
#

cast myStruct? to myStruct ?

round violet
#

had to use Value

#

i guess it needs to check if my var isnt null before getting its members

rigid island
fervent furnace
round violet
#

another question,

    private IEnumerator MainLoadAsyncScene(string choosenScene)
    {
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(choosenScene, LoadSceneMode.Additive);

        _isAsyncLoadingBigBackground = true;
        while (!asyncLoad.isDone)
        {
            yield return null;
        }
        _isAsyncLoadingBigBackground = false;
    }

    private void LoadAsyncScene(string choosenScene, LoadAsyncEndedDelegate sceneLoadCallback = null, int sceneLoadCallbackValue = 0)
    {

        StartCoroutine(MainLoadAsyncScene(choosenScene));
        // will this code only be executed when "MainLoadAsyncScene" ended the while loop ?
knotty sun
#

no, the first time yield return null is executed

rigid island
round violet
#

okay

#

could I run LoadAsyncScene as a IEnumerator

#

nah this wont solve my issue

#

how could I make LoadAsyncScene wait for MainLoadAsyncScene

#
    private IEnumerator MainLoadAsyncScene()
    {
        while (!asyncLoad.isDone)
        {
            yield return null;
        }
    }
// StartCoroutine(LoadAsyncScene());
    private IEnumerator LoadAsyncScene()
    {
        yield return StartCoroutine(MainLoadAsyncScene(choosenScene));

something like that I imagine

knotty sun
#

dont, pass your delegate to the coroutine and let that call it on completion

round violet
#

its not a delegate i call right after the load

#

sorry, the name is misleading

round violet
#

great, ty

knotty sun
#

this shit can get real complicated real fast, so take care

round violet
#

i'll do my best

knotty sun
#
private IEnumerator MainLoadAsyncScene(string choosenScene, Action<LoadAsyncEndedDelegate> callback, LoadAsyncEndedDelegate sceneLoadCallback)
    {
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(choosenScene, LoadSceneMode.Additive);

        _isAsyncLoadingBigBackground = true;
        while (!asyncLoad.isDone)
        {
            yield return null;
        }
        _isAsyncLoadingBigBackground = false;
        callback(sceneLoadCallback);
    }

    private void LoadAsyncScene(string choosenScene, LoadAsyncEndedDelegate sceneLoadCallback = null, int sceneLoadCallbackValue = 0)
    {

        StartCoroutine(MainLoadAsyncScene(choosenScene, LoadCallBack, sceneLoadCallback));
    }
    void LoadCallBack(LoadAsyncEndedDelegate sceneLoadCallback) {
         // Do Stuff
         sceneLoadCallback();
     }}

for example

round violet
#

i see

#

yeah it starts to get hard to read

knotty sun
#

and even harder to follow and debug

heady iris
#
public IEnumerator TopLevel() {
  yield return InnerCoroutine();
  Debug.Log("It is done");
}

IEnumerator InnerCoroutine() {
  while (Time.time < 10) {
    yield return null;
  }
}
round violet
#

tbh, since i only need this for 2 things, i just duplicated the following in 2 different fucntions

        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(choosenScene, LoadSceneMode.Additive);

        _isAsyncLoadingBigBackground = true;
        while (!asyncLoad.isDone)
        {
            yield return null;
        }
        _isAsyncLoadingBigBackground = false;
round violet
heady iris
#

When you yield an IEnumerator from a coroutine method, Unity will repeatedly call MoveNext() on the enumerator you yielded until it's exhausted

round violet
#

im returning the yield return of a inner coroutine

heady iris
#

then it'll go back to calling MoveNext() on the original enumerator

heady iris
#

This is a close recreation of how you'd usually write async code

#

which I think is a lot easier to parse than Callback Hell

round violet
#

is it because its already in a coroutine ?

heady iris
#

Hm, I'm actually not sure! I think the outcome will be the same..

#

StartCoroutine returns a Coroutine object

round violet
#

i'll keep my start method in case

heady iris
#

The StartCoroutine method returns upon the first yield return, however you can yield the result, which waits until the coroutine has finished execution. There is no guarantee coroutines end in the same order they started, even if they finish in the same frame.

#

now I need to check if yielding an IEnumerator does what I think it does

#

(i.e. the same thing as yielding a coroutine object)

#

excellent, it does

round violet
#

great

heady iris
#

I'm not sure if they're absolutely identical behind the scenes

#

there's certainly a huge difference if you don't yield the object

#
IEnumerator Foo() {
  StartCoroutine(Bar());
  Debug.Log("Hi");
}

IEnumerator Bar() {
  yield return new WaitForSeconds(1f);
  Debug.Log("Hi again");
}
#

This immediately prints "Hi", then prints "Hi again" after one second

#
IEnumerator Foo() {
  Bar();
  Debug.Log("Hi");
}

IEnumerator Bar() {
  yield return new WaitForSeconds(1f);
  Debug.Log("Hi again");
}
#

This prints "Hi" immediately and does nothing else

#
IEnumerator Foo() {
  yield return StartCoroutine(Bar());
  Debug.Log("Hi");
}

IEnumerator Bar() {
  yield return new WaitForSeconds(1f);
  Debug.Log("Hi again");
}
#

This prints "Hi again" after one second, followed immediately by "Hi"

round violet
#

for all examples, you are doing StartCoroutine(Foo()) right ?

heady iris
#

Correct.

#

If I just ran Foo(), then the outcomes would be...

heady iris
heady iris
round violet
heady iris
#

An IEnumerator-returning method executes until it hits a yield and then stops

#

If you don't call MoveNext() on the resulting IEnumerator object, it will do nothing more

#

because it's patiently waiting for you to ask for more values!

round violet
#

so using StartCoroutine makes it automatically call MoveNext ?

heady iris
#

I think it's useful to understand exactly how enumerators work. It takes away a lot of the "magic" from Unity coroutines.

heady iris
round violet
#

yes it is intersting

heady iris
#

When you call it, the IEnumerator is stuck into a list, and every frame (by default), every enumerator in the list gets MoveNext() called on it

heady iris
#

okay, yeah, it is on MonoBehaviour

heady iris
round violet
#

without starting a coroutine, when calling a IEnumertor, it will stop at the first yield return, and wont try again (thats when you use MoveNext)

heady iris
#
IEnumerator DoStuff() {
  while (true) {
    Debug.Log("Doing work");
    yield return null;
  }
}
#

This runs twice on the frame that you start it

round violet
#

thats why sometimes i was seeing some errors at MoveNext, i was wondering what was this method i didnt write

heady iris
#

It hits Debug.Log once as it starts executing

#

then it yields and DoStuff() returns an IEnumerator

#

then Unity calls MoveNext on it in the same frame

round violet
#

unity calls once MoveNext ?

heady iris
#

It calls MoveNext every frame, unless you yield something like WaitForSeconds

round violet
#

without starting a coroutine ?

#

im confused now

heady iris
#

no, I'm talking about when you run StartCoroutine(DoStuff())

#

also, uh oh, I'm double-checking and I might be wrong here 🫠

#

one moment

heady iris
#

I was expecting to see two "Doing work on 86" messages in the console.

#

(frame 86, that is)

#

The first message comes from where we actually called DoStuff(); the rest come from Unity's coroutine logic

round violet
#

okay ty

heady iris
#

...uh oh, am i wrong about something else here, too

round violet
#

now it way more clear

heady iris
#

today is a learning experience

round violet
#

:(

heady iris
#

Initially, the enumerator is positioned before the first element in the collection. You must call the MoveNext method to advance the enumerator to the first element of the collection before reading the value of Current; otherwise, Current is undefined.

Ooooooooooooooohhh

#

So I was wrong all along. When you run a method that returns IEnumerator, nothing happens.

#

StartCoroutine immediately calls MoveNext()

#

That's why I thought it ran up until the first yield statement.

#

Shoot. That's embarrassing

#

Well, at lesat I know now!

round violet
#

from memory, when i forget to add StartCoroutine, nothing happened.
thats why i thought it was weird

heady iris
round violet
#

so i have to keep my yield return StartCoroutine(...);

heady iris
#

the punchline: you can do it either way

#

you're yielding a value to Unity here

#

if it sees you yielding an IEnumerator, it will start working its way through that enumerator

#

if it sees you yielding a Coroutine, it will wait until that coroutine is done

heady iris
#

or if it's just equivalent to...

#
IEnumerator enumerator = InnerMethod();

while (enumerator.MoveNext())
  yield return enumerator.Current;
#

That's something worth looking into

round violet
#

i think it just extends when you arent calling a new coutine in a already executing ones

heady iris
#

...maybe in a separate project. i've just littered my game with random coroutine garbage, haha

round violet
#

"oh, more code to explore with MoveNext !"

heady iris
round violet
#

it the code works, dont check it

#

:)

heady iris
#

It'a a bit confusing because your original method never runs in the first place

#

The compiler generates a class that stores all of the local variables of the method.