#archived-code-advanced

1 messages ยท Page 182 of 1

urban warren
#

As far as I know, gameobjects are simply there to provide the ability to render the UI and have no impact on positioning or anything else.

soft hawk
#

That is correct

#

There were other ways to solve the problem but I think this will streamline the process of making changes to the UI

urban warren
#

But, you are trying to force UITK to function like UGUI...?

#

I mean, if you really want that, I think you just need to position the rootelement over the parent rect

soft hawk
#

Yes probably not the intended use but it simplified the code quite a bit

undone coral
#

it's not a known issue from your pov. i get okay success with reporting via the tool, as long as you're on the absolute latest version of unity

wispy epoch
#

When i switch scenes and go back to the main menu, watching a rewarded ad seems to be causing this error where its saying my audio source is null. I've been able to trace through the code and it looks like for some reason the ad is being started twice, which may be the problem as you can see from these screenshots. Its showing here the ad starting func is called twice and one of the times the audio source is null for some reason. Any of you advanced devs understand this problem?

tribal pivot
#

Not without a lot more information. Can you add the gameobject and esp the instanceid to your log, to see if it comes from two separate gameobjects.

Do you start the add twice, or once and get the started callback twice

wispy epoch
wispy epoch
tribal pivot
#

Yes thats why i asked to log the gameobject and instanceid

wispy epoch
steel snow
#

for the job system i want to run a test on all my objects to see if they collide with some other object and collect all the contact points, but how do I get the jobs to write to single array with all the points without overwriting each other ?

granite viper
steel snow
#

ah interesting, will try it out

#

thanks

wispy epoch
#

Running out of things to try here. I have audio that i want playing in my post game scene at certain points so i have it set up in a coroutine with checkpoints. The coroutine does all the other logic just fine but its not playing the audio. I made sure the audio source components are configured correctly and can't find any way to make them play now at all. Even in start function.

split blaze
#

Usually when you include native dll into a C# project, you can step into the dll code while debugging(given that you generated the dll on the same machine, check link below).
I can't do that with Unity. Is there a way to do that ?

Links for reference:
https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-debug-managed-and-native-code?view=vs-2022

umbral trail
#

You would have to attach a debugger to the unity.exe process, afaik the unity debugger is actually running in an environment contained inside unity so doesn't know about native DLLs

#

I assume you'd be able to have both attached at the same time

#

can anyone tell me the difference between PrefabImporter and NativeFormatImporter for prefabs?

split blaze
umbral trail
#

then why are all my prefabs using NativeFormatImporter? ๐Ÿ™ƒ

#

adding them to addressables changed them to PrefabImporter, but there doesn't seem to be any notable change outside of that

split blaze
#

Maybe addressables are handled differently

umbral trail
#

actually it seems they're split between the two

#

I guess it doesn't matter

wispy epoch
# granite viper were they working before

So i was able to have working sound in the script on the very first or second time i tested one. This was when i was only have done implementing it. After that i cant get any sound at all to play from not just the script, but the scene too. I even put the sources on play on awake but still nothing

quasi fog
#

Hello, someone maybe knows what cause that behaviour of rigidbody? || Video in attachment ||

// Movement part
private void FixedUpdate()
{
  rb.AddRelativeForce(direction * speed); 
  rb.velocity = new Vector3(0, rb.velocity.y, 0);

  if (jump)
  {
    rb.AddRelativeForce(Vector3.up * jumpForce, ForceMode.Impulse);
    jump = false;
  }
}``` || When I use a cube as a player then I don't have that problem ||
#

Character is slowed than supposed to be, jumps lower and can fly

#

I think this can be something with colliders because when the prone collider is turned on then character move normally

regal olive
#

is the prone collider also cube?

quasi fog
#

I meant that cube with that script works good.

#

These are colliders:

#

This works like a slingshot

#

It looks like a ground gets part of addForce energy. ( That cubes don't have rigidbody )

orchid marsh
#

And two box colliders on one object is not normal.

split blaze
quasi fog
split blaze
#

comment that out to see the result. Best way ๐Ÿ˜„

quasi fog
#

Ok, now works XD || IDK why I have added this||

#

Thank you very much ๐Ÿ˜„

manic flare
#

should I be concerned about using this operation? I'm thinking high garbage collection issues cs IKillable[] killables = FindObjectsOfType<MonoBehaviour>().OfType<IKillable>().ToArray();

austere jewel
#

It will be horrifically slow

novel wing
#

Sounds like garbage hell

austere jewel
#

also, yes, it will create an array of every single object, and then discard it

#

so GC impact too

manic flare
#

ok assumed so, might ditch the interface all together for abstract then

austere jewel
#

Consider inverting the control and let killables register themselves in OnEnable or something

manic flare
#

I will look into this , thank you!

uneven crypt
#

Hi everyone ! I have a question about the ref keyword. Basicly, i'm creating a movable handle. I want this handle to, upon moving, update some values stored in a specific data class. But i want the handle to have a "hook" to that value rather than storing it, so if i modify that value outside of the handle, if the handle checks the value, it gets the value as it is in the data class. That said, i also have some other requirements. In the data, i want the actual float to be private, and access it from propreties, because sometimes i will need to use some "half values", so having a float half_x{get{return x / 2f;} set{x = value * 2f;} Then, an other requirement is to be able to setup my handle with a HandlePropreties class (so i can just create a new HandlePropreties, setup some important stuf but leave the rest to default, and pass it to my handle. But i need to have the ref to these float values into this HandlePropreties. Any pointers on this? Because i pretty much can't wrap my mind around it. Thank's ๐Ÿ™‚

wide carbon
#

guys
After upgrading to Unity 2021.2 it appears that WebGL builds now don't allow/include pointer_stringify(), replacing with
UTF8ToString() works.
what does it mean?

novel plinth
#

pretty sure pointer_stringify has been deprecated for a while now

#

yeah, utf8tostring would work

fervent sage
#

TMPro Input field large text amounts problem:

On android, I am trying to paste 20k words into an input field. It cuts it off around 16k, if I test the same in the editor on windows in android mode, it works but with a bunch of lag. Testing pasting into other text apps, keeps notes cuts off at another point.. EDIT: It pastes fine into word app.

Any ideas how to get pasting everything on Andoird working?

#

So its not the android paste system but a limit in Unity

novel plinth
#

either way, the amount of garbage to be collected is huge there still

fervent sage
fervent sage
novel plinth
#

yeah, .SetText will produce less allocation

fervent sage
#

Its just when manually pasting into the box

fervent sage
#

But still doesn't paste everything when manually pasting into the edit box that shows up

novel plinth
#

as Galaxy said, 20k is a ton!

fervent sage
#

so its a very big chapter

#

but has to handle things that size

novel plinth
#

you can just render it partially based on what displayed on screen

fervent sage
#

Sorry?

#

Rendering isn't a problem

#

its pasting into the editor box that pops up in Android for a input field

novel plinth
#

the idea is when pasting, you truncate what can be displayed at oonce on screen

fervent sage
#

huh what? it pastes way more than what can be displayed on screen

novel plinth
#

20k words is no joke, especially in c#

fervent sage
#

I paste in about 16k words where it cuts off I recon

novel plinth
#

while in inputField

#

it won't get shown at once anyway

#

but those 20k will still intact.. at the back...

#

behind the scene

fervent sage
#

after pasting, I programatically take what is in the input field for processing

#

when taking, it with string ... = ...text

#

it does not have the cut off parts

#

but I know processing can handle it because I can programatically take from clipboard with string ... = clipboard
and it takes everything with no cut

#

its only when I use the inputfield as an intermediary and manually paste it where it cuts off

#

The input field itself is cutting off the text

novel plinth
#

๐Ÿ˜ƒ what I was saying basically, what's in the inputField is just for representation shown on screen, won't be rendered at once... you need to handle those 20k strings yourself (OUTSIDE those inputField)

fervent sage
novel plinth
#

caching or holding 20k strings in memory would still be bad anyway, you need to come up with something else..

fervent sage
novel plinth
fervent sage
#

well yeah but saving on phone

novel plinth
#

doesn't matter, json works practically anywhere

fervent sage
novel plinth
#

you can get those partially/sequetially as mentioned couple of times above, show what needed to be shown on screen, and just that

#

20k is humongous ... like seriously

mystic bough
#

Someone know how i can remove Plastic SCM from my project?

orchid hinge
#

delete it?

mystic bough
#

I am trying but it is alike an antivirus and hinders me wherever it can. I end up breaking my project.

#

Guess i should just start a new project and copy paste my game over to it.

orchid hinge
#

Hi im trying to get floats from a list and write it to a text file, I need to be able to access them later I havent found a tutorial on this.

mystic bough
#

You could be using a foreach loop on your list and then writeline and readline to write/read to a file. If you google writeline and readline you can see how it can be done.

orchid hinge
#

I know how to use a for loop that isnt the problem I have no idea how to use writeline and readline the problem is that there are so many guides but always only separately on only writeline or readline or on creating a file, I havent found one that would be for all of these at once

#

brb in 30 mins

mystic bough
#

You should probably be using them separately. Make a Load() and Save() and use read/write to do what you need in them.

orchid hinge
#
System.IO.File.AppendAllText(yourPath, System.String.Format("{0}", myfloat));
#

I found this however idk how I would automatically assign the path to "yourpath"(in the appendAllText) after creating a the file

orchid hinge
#

**solved

sweet pine
#

Hi, I want to assign a texture2d to a material specular map but it simply doesn't work
but when I open material only in unity editor it gets updated...!

 Material material = this.GetComponent<Renderer>().sharedMaterial;
 material.SetTexture("_SpecGlossMap", LoadExternalTexture(@"C:\textures\specular.jpg"));
mental orbit
#
 public void PlaceTile(tileclass tile, int x, int y)
    {
        GameObject newTile = new GameObject();

        float chunkCoord = (Mathf.Round(x / chunksize) * chunksize);
        chunkCoord /= chunksize;
        newTile.transform.parent = worldChunks[(int)chunkCoord].transform;

        newTile.AddComponent<SpriteRenderer>();
        if (!tile.BackgroundElement)
        {
            newTile.AddComponent<BoxCollider2D>();
            newTile.GetComponent<BoxCollider2D>().size = Vector2.one;
            newTile.tag = "ground";
            //the script for spawning the block edge goes here
        }

no mater what i try i cant get this to work
i just wanna add a new sprite as a child object every time a tile is generated and set its layer to -1

sly grove
#

-1 is not a valid layer

#

but I don't see any attempt to set a layer in here at all

#

so what exactly "isn't working"?

mental orbit
#
public void PlaceTile(tileclass tile, int x, int y)
    {
        GameObject newTile = new GameObject();

        float chunkCoord = (Mathf.Round(x / chunksize) * chunksize);
        chunkCoord /= chunksize;
        newTile.transform.parent = worldChunks[(int)chunkCoord].transform;

        newTile.AddComponent<SpriteRenderer>();
        if (!tile.BackgroundElement)
        {
            newTile.AddComponent<BoxCollider2D>();
            newTile.GetComponent<BoxCollider2D>().size = Vector2.one;
            newTile.tag = "ground";
            //the script for spawning the block edge goes here
            newTile.GetComponent<SpriteRenderer>();
            Sprite NewSprite = (Sprite)Instantiate(BlockEdge, newTile.transform.position, transform.rotation);
            NewSprite.transform.parent = newTile;
        }

heres the new script, last two lines dont work like they should

sly grove
#

what is BlockEdge?

mental orbit
#

blockedge is a sprite that im trying to place behind the generated tile

#

im attempting to parent it to the generated tile and then set it to be behind it (or set the tile to be in front)

sly grove
#

Sprites are basically just image assets

mental orbit
#

literally just a cosmetic picture

sly grove
#

they are not objects you can put in the game world

mental orbit
#

that would make sense

sly grove
mental orbit
#

yeah

sly grove
#

You want to be doing this:

SpriteRenderer sr = newTile.AddComponent<SpriteRenderer>();
sr.sprite = BlockEdge;```
#

(note you don't need to use GetComponent when you're doing AddComponent. AddComponent returns the created component.)

mental orbit
#

did it, nothing happens

sly grove
#

i mean.. .something happens

#

show what you tried

mental orbit
#
public void PlaceTile(tileclass tile, int x, int y)
    {
        GameObject newTile = new GameObject();

        float chunkCoord = (Mathf.Round(x / chunksize) * chunksize);
        chunkCoord /= chunksize;
        newTile.transform.parent = worldChunks[(int)chunkCoord].transform;

        newTile.AddComponent<SpriteRenderer>();
        if (!tile.BackgroundElement)
        {
            newTile.AddComponent<BoxCollider2D>();
            newTile.GetComponent<BoxCollider2D>().size = Vector2.one;
            newTile.tag = "ground";
            //the script for spawning the block edge goes here
            SpriteRenderer sr = newTile.GetComponent<SpriteRenderer>();
            sr.sprite = BlockEdge;
            Sprite NewSprite = (Sprite)Instantiate(BlockEdge, newTile.transform.position, transform.rotation);
            
        }
sly grove
#

your NewSprite line at the end is pointless though, and will cause a memory leak

mental orbit
mental orbit
#

all i want is to take my existing tile, right? and slap a child sprite on it that sits behind it

sly grove
#

right

#

so you create a new GameObject, give it a SpriteRenderer, assign the sprite to the sprite you want, and set it as a the child of the existing object

mental orbit
#

i do not want to replace the sprite of the tile in the editor

sly grove
#

all of which you are doing in that code

sly grove
mental orbit
#

clearly not because it looks the same

sly grove
mental orbit
#

can we vc? this is a bit much to explain over text

#

plus i can stream it

sly grove
#

show the new GameObjects created by your code

mental orbit
#

blockedge?

sly grove
#

WHich would be called "GameObject" or something, as you didn't give them names

sly grove
mental orbit
#

it dosent exist

#

nothing there

sly grove
#

did this code even run?

mental orbit
#

it has to

sly grove
#

use Debug.Log

#

to make sure it's running

mental orbit
#

if it didnt run it wouldnt have a hitbox

sly grove
#

If that code ran, it would be creating GameObjects

#

put the Debug.Log in

#

do you have some other code maybe that is giving the new objects names?

#

newTile.name = <something> somewhere??

mental orbit
sly grove
#

ok so you have other code you didn't share

#

that is naming the object?

mental orbit
#

yeah

sly grove
#

I'm just trying to understand your project here. I have a very limited lens into what's going on

#

you can see everything, I can only see what you share

mental orbit
#

newtile is acually not an object, just a port for several objects

sly grove
# mental orbit

ok so the code is working, as I guess BlockEdge is the limestone sprite?

mental orbit
#

no

sly grove
#

what is newTile then?

#

the 0, 1, 2, 3, 4, 5?

mental orbit
#

hard to explain, can i screen share?

sly grove
#

You can share screenshots

#

or videos

mental orbit
#

you can mute

#

its 200 ish lines of code, i dont know how to share that much

sly grove
#

But I dont need the code

#

I just want to know which objects are which in your hierachy

mental orbit
#

its limestone with the occasional ore

wispy epoch
#

How can i stop the game from automatically decreasing resolution of an object in the scene when i open a panel in front of it? My camera doesnt have dynamic resolution checked off so im confused why its doing it. using URP. It seems to only happen when i open up the settings panel in front of it and not for any of the other panels. This is confusing to me since i cant seem to find any difference in my code as to why that panel in particular would do this. what could be causing this? My only plausible theory is that the settings panel for some reason drops frame rate more than other panels and it causes resolution to drop, but it happens 100% of the time and only for that panel, and dynamic resolution isnt checked off so not sure how its choosing to do this. Any ideas?

sly grove
sly grove
#

And give it a SpriteRenderer too

mental orbit
sly grove
#

you don't

#

you make a GameObject with a SpriteRenderer

#

and assign the sprite as the sprite on the SpriteRenderer

#

see how the limestone object works? It has a SpriteRenderer with the sprite assigned.

mental orbit
#

i got it to spawn them, now i just gotta parent it so that it attaches to the block

sly grove
#

yep, you'realready doing all the similar stuff in your other code

#

setting the parent etc

#

just follow the pattern you had there

mental orbit
#

got it to work but its only visible in the editor

#

im almost there please help

dim zephyr
#

I am using state machine pattern and trying to escort player to jail after he's captured. Done that. Now I am stuck and I can't figure out how to return to initial (first) idle state. Here is a screenshot how I implemented a new state, but what would be the way to go back?

unkempt nova
#

This sort of thing is usually done via the FSM's transitions

#

So you probably want to make a new transition from this state to idle state if it's done patrolling, which you can set via a bool

dim zephyr
#

I do have a stack of states, but can't figure out how to transition player to idle state

#

and this is what I have so far, now i am creating new idle which I don't want, obviously

drifting galleon
#

there's also a typo in your code

dim zephyr
drifting galleon
#

.TransportToGaol

unkempt nova
#

If it's a stack, probably just want to push the idle state to it before pushing the patrol state, then when patrol is done pop it

shadow seal
#

Gaol is an old word for Jail

unkempt nova
#

Is this Jason Weimann's FSM?

drifting galleon
#

the more you know XD

dim zephyr
unkempt nova
#

Ah, ok

haughty pelican
#

so i have a maze and i generate shadow in it, but, the shadow woke up on the wrong side of the bed and decided to cast shadows all inside the maze instead of inside the walls (now i know why but dont know how to fix it/invert it). How could i make it so only the walls cast shadows?

undone coral
#

the game isn't automatically decreasing resolution of something. try to express what visual issue you're seeing is

undone coral
haughty pelican
undone coral
undone coral
undone coral
undone coral
#

if you want to use find objects of type

#

you can also see how event system finds interfaces performantly

undone coral
uneven crypt
# undone coral > Basicly, i'm creating a movable handle. why? what is your objective?

My objective is to edit the shape of the hull of a pirate ship using splines and runtime mesh generation. The ship has a "ShipData" class which holds stuff like width, length and other parameters of the hull. The ShipEditor is responsible for creating these handles and assigning to the handle which value it is responsible of modifying. The handles basicly behave like an arrow of the move tool gizmo.

undone coral
#

but in my opinion ref does not help you with any of them

#

from your description

uneven crypt
#

Yeah there are quite a lot since this editor is responsible to create the whole ship.

undone coral
#

it sounds like you want a ReactiveProperty from unirx

#

you want a way to make changes to a value privately / only permitted to make changes to the value from some places, and separately, to subscribe to changes to the value

#

you can use an IntReactiveProperty / FloatReactiveProperty to achieve this

#

for objects that need read only views, use IReadOnlyReactiveProperty<float> someValue => m_SomeValue, etc. etc.

#

google UniRx and read about it

uneven crypt
#

What i did since yesterday (and it works but it's not so clean) is creating a "ShipDataHook" that has two delegates that hold references to Get and Set methods in an other "ShipDataInteractor". So my ship editor creates a new ShipDataHook, assign the corrects methods from the ShipDataInteractor, and pass the ShipDataHook to the handle

undone coral
#

however, access checks are pretty meaningless in your own code, so don't overengineer it

undone coral
#

that is a bad idea

#

use ReactiveX for unity, which is UniRx

granite viper
#

why is that a bad idea? if you don't need the entire library of unirx

granite viper
undone coral
#

the solution sounds bad

#

use UniRx to implement the behavior "react to changes in a variable"

#

if you have collections of Vertex3 as your splines, read about ReactiveList

granite viper
#

why is it bad lol

undone coral
#

i don't really want to go into why someone's implementation of X, which i haven't seen, haven't asked to see and don't want to see, is inferior to the real thing people use

#

the user can go read the UniRx source code / ReactiveX to gain a greater understanding of the problem space

granite viper
#

yah but it works and they don't need the entire unirx ecosystem to get one thing working

undone coral
#

and why reactivex has been around for so long and has been adopted by so many people, like many libraries, becoming more mature in response to issues that are difficult to anticipate

granite viper
#

it's not like they're trying to make their own rx library

undone coral
granite viper
#

no, they're making a single get and set hook for a specific portion of their editor

undone coral
#

@uneven crypt i have offered my perspective. you'll love unirx and you should consider using it for your problem here

#

that said, you are trying to mix a lot of ideas of procedural modeling at potentially inappropriate levels of abstraction. for example, to modify the general width and height of a boat, i woudln't modify the underlying splines of some kind of surface (NURBS) model control-point-by-control point.

granite viper
undone coral
#

writing code involves adding many dependencies. it isn't that interesting to me, to go from 101 to 100 dependencies

#

since nobody has only 0 or 1, there isn't much to discuss

granite viper
#

ok then

undone coral
#

thank you for understanding

granite viper
#

uh huh

undone coral
#

lol

#

@uneven crypt so something like a lattice deformer* might make more sense for general sizing

haughty pelican
sweet pine
undone coral
#

seems like something was toggled and your scene setup got borked

haughty pelican
#

basically its doing this part shaded

#

when i need it to shade this part

undone coral
#

how have you originalyl succeeded in doing this?

#

you'd need some kind of lighting that is ambient in the "inside wall" region and not in the "ground" region

uneven crypt
#

Now, considering the lattice, it isn't really an option here. Basicly what i do is create spline control points based an a set of parameters, and using them to generate the hull. Witdth and length are just examples, in reality it's a bit more complex since it involves really tweaking the shape of the hull quite extensively. Now, that isn't really a problem in my case. I have dealt with that kind of modelling a lot in parametric softwares, here i just recreate them in Unity to let the player create the ship in real time rather than having different presets that they can chose from.

#

Thank-you for your insight ๐Ÿ™‚

kind gazelle
#

I'm having a hard time adding data to a List in a List in a class.

Manager:

public class MyManager : MonoBehaviour
{
    [SerializeField]
    List<MyData> myData;

    GameObject[] worldObj;

    public void SaveData() {
        foreach (GameObject sortedObj in worldObj)
        {
            //myData.Add(itemPosition.Add(sortedObj))
        }
        //OR
        //find object and save its position
        for (int i = 0; i < 5; i++) {
            //myData.Add(itemPosition.Add(worldObj[i]))
        }
        //IDK????
        JsonSaveManager.Save(myData);
    }
}

Data:

[Serializable]
public class MyData
{
    public bool firstTime = false;
    //public Vector3 itemPosition;
    public List<Vector3> itemPosition;
    public List<Vector3> objectColor;
}
granite viper
#

wut

#

what is saveData, you have nothing called that

kind gazelle
tough tulip
#

you can use foreach, or a simple for loop. it doesn't matter at all in the big picture.
the solution here is
i) you need to rename myData to saveData to fix the compilation error.
ii) instead of adding GameObject to a list which expects JsonSaveData, you need to fill in the data of JsonSaveData.
neater approach is to add a constructor to JsonSaveData which takes a GameObject, and then fill in the variables in class using that GameObject from the constructor itself. then add to list using new JsonSaveData(worldObj[i])

i hope you know to save json once you get the list ready :)

kind gazelle
tough tulip
kind gazelle
undone coral
#

a parametric modeling approach sounds cool

#

what if you delegate the model generation to a proper parametric modeling engine?

#

so that you're not recreating the whole thing

orchid hinge
maiden turtle
#

Is it possible to rebind the context pointer of a delegate?

#

My use case is caching MethodInfo and calling it for new objects of a class

#

So like

var deleg = Delegate.CreateDelegate(type, NO_CONTEXT, MethodInfo);
// store it

// Object creation
var obj = new T();
deleg.ContextPointer = obj;
// Call the instance method of the new instance
deleg(args);
final steeple
#

You can just create a delegate that takes a this object as its first argument

pseudo gulch
#

il2cpp back to breaking stuff again?

maiden turtle
#

I want to reuse the one that's cached

#

that's the whole point

final steeple
#

That's what a delegate with an explicit this allows you to do

#

Just use a delegate with the appropriate type as its first parameter and it should let you use CreateDelegate with it

maiden turtle
#

ah ok I'll try it, thanks

maiden turtle
#

yeah I got it from the description

zenith quarry
#

I don't need to worry about jit compiler in Editor when I use Il2ccp in build, right?

final steeple
#

The JIT is always used in the editor, yeah

#

In an IL2CPP build it won't occur

zenith quarry
#

thanks

amber spear
final steeple
#

Move it out so it's inside the class instead

humble leaf
#

Also, don't crosspost @amber spear

amber spear
#

ok sorry

#

got it thank you so much

naive harbor
#

Im trying to do something like this. top tile dungeon procedural generation. Yall think it would be a good idea to store the map inside of a 2d array?

olive lion
#

Hi, I wanted to ask regarding inheritance with constructors.

I've seen that you need to use base() in an inherited class, or just access the variable from the mother class directly, and wanted to know if there's a difference and if so which one would be better to use.

Class Group inherits class Set.

public class Group : Set
{
    private int value; 

    public Group(int value, float minSeqX, params Color[] color) : base(color)
    {
        this.value = value;
        this.minSeqX = minSeqX;
    }
.
.
.
}
sly grove
flint sage
#

You sure base. in cases where you override a method or constructor

#

It gives you control when (or even if) the base method is called

olive lion
#

I basically have those three parameters that I'm inputting, but minSeqX and color are variables of the mother class.

And I've seen there are two approaches to save the value of those variables.
One is either directly and the other is using base()

olive lion
flint sage
#

When you call base, it executes teh constructor of Set. Which might do additional calculation

sly grove
olive lion
#

Yeah

#

Which one is better to use? because setting them directly would make the code more comfortable to read.

flint sage
#

You might also want to hardcode the parameter color, e.g. public Group(int value, float minSeqX) : base(new Color[] { Color.Green })

sly grove
#

Even just for the sake of DRY principle it's best to call the base constructor usually

olive lion
#

And for primitive variables there shouldn't be any problems with direct setting right?

flint sage
sly grove
#

C# is not java, there are no primitives

olive lion
#

int, float, etc

flint sage
olive lion
#

Alright

flint sage
#

So sure, in your simple use case it doesn't really matter

olive lion
#

Got it. Thanks for the help

sly grove
#

I'd argue for code maintainability it matters always

#

imagine you wanted to add some validation or range enforcement code in the future

#

if you don't delegate everything to a common base constructor, you now have to find and make multiple changes to enforce such a thing

olive lion
#

Well as far as my game goes I'm pretty sure no range enforcement will be needed, it's just simple setting so I can compare distances that's all

lost knot
#

can anybody help with this

undone coral
undone coral
lost knot
olive lion
undone coral
#

what is the purpose of caching methodinfo and using delegates this way?

#

@maiden turtle when you have complex lifecycle of executing a function step by step over time, you can use a pattern like this:

                                                   // or whatever
                                                   // thing you want
                                                   // to signal
var continuePastStep1 = new UniTaskCompletionSource<int>();
async UniTaskVoid MyTask() {
  // bound via closure
  Debug.Log(context.value1);
  // manually control when to advance
  // your task
  var signaledToMeInt = await continuePastStep1;
}

// elsewhere
continuePastStep1.TrySetResult(5);
context.value1 = 10;
rain ice
#

[2d isometric tactics game]

i have 3 tilemaps (ground level, first level, second level) and in the image attached, debug sprites represent the center of those tiles at each level.

what would be the best way of detecting whether there is a tile ABOVE the current one when i'm initializing them in order to ignore it? for example, if there's a tile above (1, 4) i don't need to store this as the unit will never be able to move to it - i need the one above it

#

i was thinking raycasts? but does anyone have any other ideas

undone coral
rain ice
#

nope, i'm just working on my own game just using whatever tilemap tutorials/documentation i can find

#

unfortunately, most are art-centered which isn't very helpful

undone coral
#

okay

#

why are you using 3 separate tilemaps?

#

is your goal to get a character that can run and jump around this world?

#

what would be the best way of detecting whether there is a tile ABOVE the current one when i'm initializing them in order to ignore it?
you program it ๐Ÿ™‚

rain ice
#

yep that's correct, i would like a character to be able to jump up to the higher levels - like this

rain ice
#

unless i did a raycast from the camera

undone coral
# rain ice yep that's correct, i would like a character to be able to jump up to the higher...

there are two approaches.

  1. lay out your world in 3D and render it in 2D. advantages: real physics. disadvantages: requires dedicated asset / sophisticated knowledge around isometric rendering.

  2. lay out your world using a dedicated tilemap tool. advantages: many bespoke packages do this and intuitive level building. disadvantages: requires large amount of arcane engineering / use of an asset store package

undone coral
#

but since you didn't see that solution you should use an asset store package. not meant to be condescending.

rain ice
#

it's fine, i don't mind the blunt suggestion ๐Ÿ™‚

#

i'd prefer not to personally

#

i'll use that suggestion though with multiple dictionaries, thank you

maiden turtle
#

that instantiates a prefab, then calls Initialize() of a component with the stored arguments

undone coral
rain ice
maiden turtle
#

I just didn't want to encumber my objects with interface implementations

undone coral
maiden turtle
#

Instead, get the method by name at start

undone coral
#

@rain ice all it really does is give you a performant sprite material to render sprites facing the camera

#

the "snapping tool" and "depth sorting" are niceties

rain ice
undone coral
#

okay

#

but you're already on a bad path

rain ice
#

thanks though ๐Ÿ™‚

undone coral
#

if it's this early

#

you should definitely model your game in 3D

#

do you know what i mean by model?

#

this is coming from someone who ships isometric games with elevation

#

you're going to miss out on how much simpler it is to do things the way this asset suggests

#

because unity is already a 3d game engine.

#

you already have elevation, it is the y axis

#

and you already have a way of expressing the boundaries of a world and having a character run around in it, it's colliders

undone coral
rain ice
#

i'm aware of the pros of using a 3d approach, i just know it's definitely it's not necessary for what i want to achieve ๐Ÿ™‚

undone coral
#

hmm

undone coral
#

it's the opposite

#

you're trading the ease of using the tilemap editor

#

which basically lets you create a pretty picture, and not much else

#

for... a nonfunctioning game

#

the only way you can make an isometric game where the player can move behind things and also jump on top of things

#

i.e., 3d physics with an isometric camera

#

is to do 3d physics with an isometric camera, or author a very, very sophisticated simulation of 3d physics in 2d, which is way harder

#

consider people only do approach 2 in SNES games because they lacked 3d engines, not because it was a good idea

#

consider the tutorials you see are art based because using tilemaps is about giving you a pretty picture

#

this is the start of a good journey you will thrive ๐Ÿ™‚

rain ice
#

the player doesn't need to jump on top of things, they just need to appear as if they have done, like all retro 2d tactics games do

#

hence why i have determined the center position of each of my tiles to achieve this

#

physics isn't necessary in game like FFTA or tactics ogre

undone coral
#

okay so that's a different game

rain ice
#

but you don't seem familiar with them, so i can understand why you seem to keep pushing 3d when it's not necessary

undone coral
#

sorry i misinterpreted " character to be able to jump up to the higher levels"

#

the characters don't jump in final fantasy tactics

#

not in the sense that platformer game characters jump

#

you'll be able to build an final fantasy tactics game for sure

rain ice
#

no of course, my apologies - i should have made that clearer when i sent through the screenshot - i meant appear to ๐Ÿ™‚

undone coral
#

there are good assets for it

#

it's tricky. i like the dev logs for Into the Breach

proven hatch
#

anyone have any idea why collider.bounds.extends is returning Vector3.zero when my game object is de-activated despite my collider's size not actually changing? Is this intended behavior?

rain ice
undone coral
rain ice
#

i'll dig around and see if i can see it, sounds interesting anyway ๐Ÿ™‚

#

i solved my issue anyway by iterating through the tilemaps backwards and also storing the localTilePosition

#

that way, i can just check if the localTilePosition has already been added to the dict before trying to store the lower tiles

#

there may be a situation further down the line where i do need a reference still to ALL tiles, for the time being i can't think of one so this works

maiden turtle
undone coral
#

DI isn't useful in games so you won't find good stuff for unity using it

#

sorry

maiden turtle
#

what

#

why sorry?

proven hatch
maiden turtle
#

Well if you mean decentralized initialization via Start(), then you can be sure that dies not work

#

for first, it's a nightmare to synchronize

proven hatch
#

you can of course use Unity just for its rendering capabilities and create a pseudo-engine around it and utilize DI to your heart's desire..but you'll be re-writing a lot of built-in functionality that Unity provides for you like creating and destroying objects, referencing, etc

maiden turtle
#

for second, it's not testable

#

initializing via initialization events is also something that I have tried, but it's awkward and still not testable

proven hatch
# maiden turtle for second, it's not testable

(unit) testing has pretty limited value in the context of a game, you're limited to testing within the context of the mocked environment which never provides guarantees it will work in your actual game

maiden turtle
#

and making everything into a singleton is implicit context and even less testable and maintainable

proven hatch
#

^ I wouldn't worry too much about testing and maintenance if you're an individual dev or even working on a small team. The baggage that comes with a lot of the "best OOP practices" can cause such a slowdown in development pace that it can kill the project before it ever ships v1

maiden turtle
proven hatch
#

if you're testing in Unity in an isolated scene you're actually doing something closer to an integration test, which I agree does have more value than a unit test in the context of game development

maiden turtle
#

It's all global singletons and copy paste code all around

#

Heck, to be able to change text on buttons I had to refactor half the codebase

proven hatch
#

coupled with the compile time.. I find the dev experience quite frustrating

sand mural
#

is anyone around for a not so advanced but annoying issue?

fresh salmon
#

not so advanced
Posts in advanced channel anyway
Does not describe issue right away
=> Please see #854851968446365696 for question posting guidelines

sand mural
#

yeah because:

  1. If you see the other channels, the question management is non-existent
  2. what is advanced anyway - so vague
  3. Apologies I missed the "don't ask who is available rule"
urban warren
#

Am I just spacing out here, or in the profiler, should the sum of the children calls GC alloc equal the parent GC?

#

Never mind.... I just realized that 490 KB is 500KB which is 0.5 MB...

#

A facepalm moment right there haha

sand mural
#

I am making a grappling hook mechanic in a game with rotating camera ( on the fixed update ), I want to get the mouse position in 3D space to get the direction from the root towards the mouse but I keep getting random results

#
 Vector3 inputPositionInWorldCoordinate = new Vector3( Input.mousePosition.x, Input.mousePosition.y, ??? );
Vector3 worldPosition = Camera.main.ScreenToWorldPoint( inputPositionInWorldCoordinate );
direction = worldPosition - GunTip.position;
sly grove
sand mural
#

3D perspective, the camera is mostly rotated looking at the player directly, almost like side scrolling

sly grove
#

you'll want/need to be using a raycast here

sand mural
#

I thought about it but raycasting to what though

#

I dont want it to be a targeting practice hookshot rather shoot towards the mouse direction

#

and I don't think it's elegant to create a fake wall and use that for it as a solution

sly grove
#

using Plane.Raycast

#

(not a physics raycast)

spare pond
#

Zenject question. I have player go which contains RotateOrigin go.

How to rererence this RotateOrigin go into cinemachine vcam follow transform correctly?

Trying to bind RotateOrigin go with ZenjectBind component with id to bind it in installer but can't connect it properly

Player go gets spawned from installer

sand mural
rotund dagger
#

Trying to attach the same behaviour script to 30 different animation clips

#

How do I do that quickly?

zenith ginkgo
#

unless i've miss-read the question

#

+that is nice to look at

#

bar the names

sand mural
#

@sly grove worked! thanks

undone coral
#

do it

#

it will take you... 60s

rotund dagger
gray pulsar
lost dove
#

With the immediate mode GUI for Unity, how can I detect a certain key press in a text field and don't insert it into the text field's string? For example, I have a debug console that opens with the ` key, and I call GUI.FocusControl to a textfield when the console opens, but I want the console to close when ` is pressed again, but it inputs the ` into the text field and does not close

plucky laurel
#

dont forget to clear the profiler, i once spent lots of time profiling where im leaking gigabytes of mem lol

undone coral
#

you can edit out the character for the next frame

lost dove
#

This is the Immediate Mode GUI system

undone coral
#

edit it out of the text for the next frame

#

that's as good as it's going to get

cunning grove
#

I'm making a procedurally generated "dungeon" and I'm trying to figure out how to make paths that connect between the rooms. Each block is represented by a letter in a 2d char array. You have the smallest blocks, which are the center of the room, the medium blocks which are the outside of the room, and the large blocks which are the walls. I want to create paths that connect between them, but tbh I'm not sure how. I'm not asking anybody to do it for me, but does anybody at least having a starting or a general direction for me to follow? Thanks for the help.

brittle pumice
#

Wonder if someone has an example creating a controller from a clip and all the Parameters are set correctly.

#

Basically trying to replicate this via script

#

I found UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPathWithClip

#

But it doesnโ€™t set any parameters

maiden turtle
#

I have had a couple of goes on this thing before.

#

I don't even remember how it works, and I think it has bugs, but there you go

#

Here's another approach

maiden turtle
fervent sage
tribal pivot
brittle pumice
#

@tribal pivot I had a look at that before asking unfortunately I couldnโ€™t track it down. What Iโ€™m trying to do is access the animated custom properties form the FBX

final steeple
#

You should be able to access those from the ModelImporter

#

(ModelImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(model))

brittle pumice
#

Iโ€™ve been playing w that but no luck

#

Not sure what Iโ€™m missing

final steeple
brittle pumice
#

Thanks @final steeple let me try that

regal olive
# cunning grove I'm making a procedurally generated "dungeon" and I'm trying to figure out how t...

This is a problem with a lot of different solutions, with various pros and cons. I haven't done so much "geometric" proc gen, but I guess you could use A* or another pathfinding algorithm to find paths between room (or to the nearest path on the way there). You'd probably have different rules than A* as corridors should not always follow a shortest path.
In any case, look up the A* pathfinding algorithm and similar for a primer. Additionally, the developers of Cave of Qud have several good GDC talks on the high level techniques they use for map generation (most are on youtube I believe), they can be a good source of inspiration. There's also a lot of tutorials online for cave generation using marching cubes, I'm sure some must offer solutions to the problem of connecting the generated chambers.

spare pond
#

Zenject. How to inject follow transform of cinemachinevirtualcamera component?

I have transform in prefab which i want to bind into cinemachine follow transform

cunning grove
desert oyster
#
TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
info.IsAmbiguousTime(new DateTime(2021, 10, 31, 2, 0, 0));

unity 2019.4.15f returns false
unity 2019.4.38f returns true
How is it possible that applying unity LTS patch there are differences in interpreting DateTime which is core .NET functionality?

devout orbit
#
public void ListenToUpdatedGameEvent<TGameEventData>(Action<GameEvent<TGameEventData>> callback) where TGameEventData : GameEventData
{
    var gamesEvents = GetGameEvents<TGameEventData>();

    foreach (var gameEvent in gamesEvents)
    {
        gameEvent.GameEventUpdated += callback;
    }
}```

Does anyone know how to do this ? I want to use my callback as subscribe action for my event.
But I have a feeling this is not possible
maiden turtle
#

I'm a bit lost. I instantiate a scriptable obiect in editor and I want to save it to disk. It there a way to save it using the ScriptableObject, without messing with SerializedObject

#

?

#

Like automatically take the current values of ScriptableObjects and apply them to the data stored on disk

maiden turtle
#

I don't understand the idea

devout orbit
# maiden turtle please elaborate

In the parameter I'm adding a callback, that needs to be invoked when gameEvent.GameEventUpdated gets invoked.
But the callback never gets invoked even tho gameEvent.GameEventUpdated gets called.

#

I assume you can't directly subscribe to a event with a unity action

maiden turtle
#

what's GameEventUpdated?

devout orbit
#

A event Action

maiden turtle
#

c# event?

devout orbit
#

Yea

#

Public event Action GameEventUpdated

maiden turtle
#

I don't know when you call that event

devout orbit
#

Well that calling of the event is fine, it's just the subscribed callback does not get fired ๐Ÿ˜›

maiden turtle
#

You might be removing it in another callback

#

although

#

Yeah, I'm pretty sure you can't remove while iterating the delegate chain, it breaks it

#

If you need to remove too, you probably need to roll out your own thing, or UnityEvent I think buffers adds and removes

sage radish
devout orbit
#

It is defined as that

#

But I didnt type it all out

#

Just trying to figure out, why my callback does not get invoked

sage radish
#

If it's compiling and there's no error then there's no issue with this

#

The problem lies somewhere else. Either this method isn't being run or you're subscribing to an event that isn't being invoked or the callback is being run without you being aware of it.

split blaze
#

When you implement ILogger, do you need to implement ILogHandler also?

undone coral
#

there's no value in implementing ILogger / ILogHandler because it doesn't do anything for Debug.Log

#

you'd have to ping Unity Pro support to ask why it's so valueless

undone coral
undone coral
undone coral
undone coral
# split blaze Nope

use a dedicated logging library based on the proper dotnet logging infrastructure. ZLogger is one for Unity

undone coral
#

@desert oyster what is your objective? what is this code for?

split blaze
desert oyster
#

my code is for calculating sun position based on the geo location and time

undone coral
desert oyster
#

I was just asking why is it the case that updaing unity to newer LTS changes the behaviour of core .NET functionality

undone coral
#

i suppose if you don't want changes, don't update

#

ambiguous daylight savings time corner cases seem low ROI, as does upgrading Unity point releases

desert oyster
#

Unfortunately I had to update because of another bug

undone coral
#

yeah that sucks

#

fortunately daylight savings times issues are low ROI

desert oyster
#

yea its not a big deal for me, just was wondering why my tests was failing

#

without tests I wouldnt even notice it

undone coral
#

yeah you're in a good place

raw lily
#

I've been searching online without luck, what platforms would using .Net 4.x with Unity, instead of the default, break?

fierce wind
#

I Get this Error A lot lately How can I fix it:
Copying assembly from 'Temp/Assembly-CSharp.dll' to 'Library/ScriptAssemblies/Assembly-CSharp.dll' failed. Detailed error: Sharing violation on path

fresh salmon
#

Don't cross post

#

Seems like you have a dangling handle to the file, restart Unity/your computer

fierce wind
#

by restart you mean close and open unity?

fresh salmon
#

Yes

fierce wind
#

did it but its just happen after short time

fresh salmon
#

Restart your computer

fierce wind
#

ok thank you

spare elbow
#

I have about 20 objects the player can choose from in the UI so i have to spawn them at runtime

#

i want to be able to refer to them by their number while spawning them

#

would it be better to put them all in a [SerializeField] Gamebject[] list variable

#

or somehow load them from a specific file path of where they are?

#

im worried the first option might take too much memory

#

cuz its a mobile game

sly grove
#

Most likely it's fine

#

especially since the player's going to spawning probably many of these things?

#

The prefabs themselves is a relatively small amount of memory compared to the spawned ones

obtuse magnet
#

i wanna make a game like scratch where you can basically make your own scripts using a scratch like interface, how can i go about this? i did a bit of research and i was thinking i could use the realtime c# compiler from this video https://youtu.be/dY6jR52fFWo and then when there is a certain block i would append the text or something like that, but still need some direction, please help ๐Ÿ˜„ idk how much harder this would be, but it would also be amazing if it had some interface like game builder garage for the switch, OR bolt for unity (the visual scripting tool)

Attempting to create a little game where programming is the core mechanic.

Links:
Compile C# at runtime: https://github.com/SebLague/Runtime-CSharp-Test
Project source (warning, total mess!): https://github.com/SebLague/Coding-Game
CRT effect - https://www.shadertoy.com/view/Ms23DR

If you'd like to support the creation of more programming vide...

โ–ถ Play video
unkempt nova
#

I bought an asset to do it for me. It's a huge pain

obtuse magnet
#

which asset?

unkempt nova
#

Lemme try and find it, always have a hard time finding it again

obtuse magnet
#

okay

unkempt nova
sly grove
#

oh god it's Scratch

obtuse magnet
#

okay

unkempt nova
#

What they wanted haha

sly grove
#

oh wow they literally did ask for scratch

#

nice haha

obtuse magnet
#

wait does anyone actually know how i would be able to make it tho

#

without assets

sly grove
#

I mean it's not... super simple. But when you boil it down you'd basically define a data structure for a "Block", and you'd just end up with a List<Block> that you iterate over and execute the "command" for each block, in sequence

obtuse magnet
#

i was thinking that

#

on run

#

it would compile it into c#

#

and then run that

#

something like that

#

list is good tho thank you

granite viper
#

runtime C# compilation is not possible on AOT platforms like ios, fyi

#

I think osx is also AOT?

#

correct me if I'm wrong

#

it's not really that slow to have a block structure

#

c# codegen is not exactly easy to get prod-ready

#

lots of sandboxing security issues, etc

obtuse magnet
#

osx?

granite viper
#

macos

obtuse magnet
#

oh

#

and

#

aot?

granite viper
#

ahead-of-time

#

apple platforms don't allow JIT

obtuse magnet
#

oh

#

i saw

#

a unity project tho

#

you dont have to install a thing on pc

#

it is in the project

granite viper
#

I never said you did?

obtuse magnet
#

ik but

granite viper
#

can you like

#

type

#

in complete sentences

obtuse magnet
#

i

#

do no think

granite viper
#

pls

obtuse magnet
#

i know

#

okay

#

would it work if it was online?

#

like a webpage

#

using github pages

granite viper
#

hm, I don't think webgl supports jit either

#

now that you mention it

obtuse magnet
#

oh

#

what would you recommend then?

granite viper
#

just do the block solution suggested above -- dynamically put together a chain of blocks that each execute a command

#

if you architect it right it should be pretty fast

obtuse magnet
#

what about ifs repeats... etc

granite viper
#

speed is the only reason you'd worry about generating code in runtime

#

what about them?

obtuse magnet
#

how would i create them

granite viper
#

that's a larger question

#

basic idea is to create a basic abstract Block class with an abstract Execute method, then create a bunch of inputs, outputs, etc.

obtuse magnet
#

okay

austere jewel
maiden turtle
#

Reread the initial question too please

flint sage
#

AssetDatabase.CreateAsset

#

Or SetDirty + Saveassets

final steeple
#

There's also an individual AssetDatabase.SaveAsset method

flint sage
#

Only since 2020.3.16f1 apparently

final steeple
#

yeah it's relatively new

flint sage
#

Thanks, didn't know about (mostly because I've been stuck in 2019.4 for aaages)

final steeple
#

there's also an API for serializing/deserializing objects outside of the assets folder

#

I use it to store cache data for some custom lightmapping stuff we do at work

flint sage
#

That's been there in UnityEditorInternal for a long time though

final steeple
#

Yeah, but it can be used to "forcefully" save an asset

flint sage
#

Did they move it to AssetDatabase or is it still in unityEditorInternal?

final steeple
#

It's still in UnityEditorInternal

flint sage
#

๐Ÿ‘

final steeple
#

Since you can force binary serialization for performance too

flint sage
#

I've used it in the past for configs/library data

final steeple
#

So there's gigabytes of data in here, but it results in lightmap bakes taking a few minutes instead of a few hours if you just move a light

flint sage
#

But now that ScriptableSingleton is properly supported, I don't really need it that much

final steeple
#

I originally tried using ScriptableSingleton yeah but it's not good enough for this use case

#

Since if you have all of that data in a single asset, you have to load all of it at once

#

Those folders contain thousands of individual lightmap textures, they're stored separately so they only have to be loaded when they're needed

flint sage
#

If it's gigabytes of data then it doesn't make sense at all

#

So, is that completely custom lightmapping or how does it work?

#

You generate textures that unity supports and then let unity handle rendering? Or do you also have custom shaders?

final steeple
#

It's a special lightmapping system built on top of the normal one, so we can control brightness, color, etc of lights at runtime

#

With almost no perf impact

flint sage
#

How does that work if lightmaps generally have multiple lights in each texture? Or do you encode a lightId in the texture somehow?

final steeple
#

all of that is baked lighting

#

it's a rather complicated process

#

but it's worth it

#

it works very similarly to how games like Quake or Thief handled lightmapping, but with a few improvements

#

The result is that we can basically control every light without needing dynamic lights

flint sage
#

So I guess disksize of those textures is a lot higher than the normal unity lightmapping right?

final steeple
#

They can actually be smaller sometimes

#

I did a lot of trickery to keep sizes down and avoid storing unnecessary data

flint sage
#

๐Ÿค”

#

You gotta give something ๐Ÿ˜›

final steeple
#

hahahaha

#

We're thinking of maybe doing an article on how it works and releasing the code someday

#

Wanna enjoy being one of the few games doing it for now though picardy

#

Or moreso a library that had to be written in order to implement the system

#

The light probes stuff isn't actually being used currently, still experimenting with it

flint sage
#

Is renderer the mesh or the light source?

final steeple
#

the mesh

#

MeshRenderer specifically

#

it can also be a Terrain

flint sage
#

Yeah I noticed that

#

I can figure out how you're mapping renderers to their lightmaps but not how you map lights to renderers/lightmaps ๐Ÿค”

#

Which would be required somehow right..?

#

Or is that data already stored somewhere else and you can just jank it out of there

final steeple
#

This is actually how Unity maps them

#

None of the actual code related to our lightmapping system is in here

#

This is a library that reverse engineers the LightingDataAsset and other things

#

Which is used by that lightmapping system

flint sage
#

๐Ÿ™„

#

I thought you were throwing me a bone

final steeple
#

I am, without this code it's pretty difficult to do lol

#

The key to what the actual lightmap stuff does is in the name: composited GI

flint sage
#

Ok

#

I should get back to work really

#

Thanks!

final steeple
#

np

#

Eventually we'll reveal the secretsโ„ข๏ธ

flint sage
#

Let me now once you do, interesting stuff even though I know very little about rendering and lightmapping

livid kraken
final steeple
#

lmao

#

I've considered writing something like that to speed up the process actually

#

but when I implemented a cache, it ended up reducing bake times enough for me to not bother

livid kraken
#

Like a spatial aware cache ? Where you dont rebake the whole scene for moving 1 light or object ?

#

My studio will pay good money for that hah

final steeple
#

Where you dont rebake the whole scene for moving 1 light or object ?
Yes
Like a spatial aware cache ?
Not quite

#

It stores information on each renderer and light, and it uses that to determine which lights and renderers are "dirty" and need to be rebaked

#

Each light has a list of renderers that it touches, so if the light is dirty, all renderers affected by it are also dirty

#

It's very specialized for our system though, but it could totally be repurposed for normal bakes

livid kraken
#

Aha. And you then you reconstruct the whole lightmap at build time or ?

final steeple
#

That's part of the process yeah

#

Though it happens at bake time, rather than build time

#

The scene is modified so that only objects that should be baked are actually baked, then we process the data and write it out to the LightingDataAsset, and then restore the scene to the state it was in at the start

livid kraken
#

How do you handle bounces to renderers that the lightt doesnt touch ? I assume "touching" means a renderer is within its range

final steeple
#

A few ways

#

Being within range is the main check, and we have a setting where you can artificially increase the range of a light to account for bounce lighting

#

But you can also inspect the LightingDataAsset to see which lights affected which renderers

#

You check which lights belong to which lightmaps, then check which renderers are assigned to that lightmap

#

It's not perfect but it gets you 99% of the way there, which is good enough for testing and development purposes, you always want to do a fresh bake for an actual production build anyway

livid kraken
#

I see. Sounds like something we would licence later this year when we enter production on a big project

final steeple
#

We might consider it once things are further along

#

The game it's being used in (Gloomwood) is entering early access later this year

#

From our own tests, the whole system has very little to no measurable performance impact, it's a locked 60fps on Steam Deck

#

Which honestly surprised me, even though I was the one that wrote it lol

livid kraken
#

Sounds nice

maiden turtle
#

Is there a way to get ith material of a meshRenderer without making a copy of the array of materials?

#

Like meshRenderer.materials[i], but without allocating the array for the materials

final steeple
#

Nope

#

You can't even get the number of materials without allocating

#

(There's an API for that, but it's private)

maiden turtle
#

That works too tho, let me check the source code

final steeple
#

I'm not aware of any internal method to avoid an alloc there, unfortunately

#

In theory you could access the internal C++ object to get the PPtrs to the materials, and then use Resources.InstanceIDToObject, but that's going into super hacky territory

maiden turtle
#
[FreeFunction(Name = "RendererScripting::GetMaterialArray", HasExplicitThis = true)] extern private Material[] GetMaterialArray();
#

yeah, it all calls into native code

final steeple
#

Yup, the layout isn't visible to managed

sage radish
#

Well, you still need to allocate the list at least once. Don't think you can get the material at an index without getting them all first.

maiden turtle
#

Yeah, that works fine, thanks

final steeple
#

Right, I forgot those existed

sage radish
#

But they don't have SetMaterials/SetSharedMaterials for some reason

final steeple
#

It's a weirdly incomplete API

#

Lots of cases like that in Unity

#

It's theoretically possible to use array APIs without allocating via some evil tricks

#

But they're not what you would want to use in production lol

#

And will only work on Mono

fiery horizon
#
    {
        UnityWebRequest request = UnityWebRequest.Get(uri);
        request.certificateHandler = new TSLCustomCertificate();
        yield return request.SendWebRequest ();
        if (request.isNetworkError)
            {
                Debug.Log("Something went wrong, and returned error: " + request.error);
            }
        else
            {
                // Show results as text
                Debug.Log(request.downloadHandler.text);
            }
    }```

Unity doesnt use my custom certificate handler, why?
tough tulip
final steeple
#

Nope, we don't use SRP

tough tulip
#

not your specific project. but just interested to know how hdrp performs on a steam deck
its not available in my country unfortunately and none of my tester have it

final steeple
#

Yeah we just haven't done any tests with it since none of our games use it

sharp rune
#

code general is active so ill post this here

#

I need some help with performance optimization..
So basically I noticed that this one script takes a lot of my performance.. and the part of the script is this one:

Collider[] colliders = Physics.OverlapSphere(this.transform.position, targetRangeDistance);
collidersSorted = colliders.OrderBy((d) => (-(d.transform.position - transform.position).sqrMagnitude)).ToArray();
for (int c = 0; c < collidersSorted.Length; c++)
{
   if (collidersSorted[c].transform.gameObject.GetComponentInParent<MissileController>() != null && gameObject.activeSelf == true)
   {             
           targetToHit = collidersSorted[c].transform.parent.parent.gameObject;
   }
}

it basically searches for colliders with the component MissileController and sets them to some public GameObject. Its prob because that first line finds like 300 colliders and sorts them all but i'm not sure. Any ideas how I can make this more efficient?

flint sage
#

I don't even know why you;re sorting that array

#

And why you're doing ToArray afterwards

sharp rune
sharp rune
#

yea i do..

novel plinth
#

you can just var colliderInIenumerable = without ToArray, then do foreach after

spark meadow
#

this will reduce the amount of colliders you find and sort before applying

#

also just for fun change gameobject.activeself == true to just gamobject.activeinheiracry

sharp rune
#

ik ill do all of that

#

but

#

wouldnt this one: gameobject.activeinheiracry only work in the editor?

spark meadow
#

no it will work during runtime

sharp rune
#

ok lmao..

spark meadow
#

if the object is a child of a parent object and the child is enabled but the parent is not then the object is still active even though its parent is not. so activeSelf will return true when in fact due to the parent being not active its not active. cheers ๐Ÿ˜„

sharp rune
#

wait so this here should be 11?

#

or am I doing something absolutely wrong

wispy lion
sharp rune
#

yea I rly don't know how they work..

sharp rune
flint sage
#

It's called bitshifting

#

And bit masks

sharp rune
#

ok I found something

#

thx

#

thanks to everyone here this drastically improved the performance

hazy epoch
#

Looking for a bit of a jumping off point here. Say you have a player character that sits in a gunner box. They have a weapon on the right and left of their box, and the weapons can rotate independently of the box's rotation. Without casting an infinite Raycast (that looks for some object way out in the distance to aim at), how could one go about making the weapon point towards the same space in world space as the crosshairs?

The use case is if the player fires the weapon and there's no target in front, I want the projectile to at least fire off into the distance with the trajectory that matches the crosshairs (keep in mind the weapon is offset from the actual crosshairs by quite a bit).

granite viper
#

@hazy epoch get a point that is x amount of distance in front of the camera, and have the guns lookat that

#

this is a common solution to that kind of problem -- just pick a max focus distance that feels good to you and clamp the focus that far

#

otherwise the "infinite limit" would just have your guns copying the camera rotation

#

if that makes sense

#

there's no correct answer, it's just whatever looks ok

#

I'm assuming that when you're over an object the guns focus on the raycast hit point

hazy epoch
#

Got it. I knew there was some generally accepted practice to achieve this "effect". I just couldn't think o fit.

granite viper
#

tf2 does this for their projectile weapons

#

as a reference

hazy epoch
#

tf2?

granite viper
#

team fortress 2

#

there's a certain distance that gives diminishing returns for how much it looks like they're aiming at where the crosshair is hovering

undone coral
granite viper
#

if they're really far apart from the camera that distance will be probably be larger than if it were close

undone coral
fiery horizon
timber flame
#

In voxel games, removing a voxel is easy. When clicking on a voxel, screen space point/world point can convert to voxel index. Then, remove it from the corresponding element of the array.
My question is about removing buildings from a map.
Building models are not cubic completely but we can consider a cube surrounding that building. Also, buildings are larger than one voxel, cool.
I came up with two approaches to remove a building from the array.
1- when a player clicks on a building, I get the corresponding voxel then move to left bottom on the array until id in that current element of the array differ from building ID
2- when adding a building, keep left bottom voxel index in that building object. So, when removing, we can access stored left bottom voxel index in the building script directly.
What is your approach?

#

Example,
Building with ID 10 occupies elements
(1,0,1)
1,0,2,..
They are all 10 in 3d array.
They should be set to 0 when removing that building

The first approach does not work because similar buildings can be adjacent, so they are not distinguishable just by moving on elements of array to reach left bottom element with same type ID.
I have to assign an instance id to each building instance and create a dictionary with instance ID key and left bottom voxel index as a value.
Building 1, type ID: 10, instance id: 9000, pos:(12, 2,50)
9000=>(12, 2,50)
By selecting that building, I will have instance ID, then can get the voxel index/pos. The building size is known, finally the corresponding elements can be removed in the array.
Do you know another way?

undone coral
#

when you say instance id, you mean your own instance ids, and not unity's, right?

#

are you using a pre-existing voxel engine

wispy epoch
#

Need help implementing in app purchases. I've heard its best practice to implement IAP from code but I cant find a tutorial online anywhere because all that comes up is codeless in app purchasing implementation. Can anyone point me in the right direction on this?

crude juniper
#

Hello guys, there is a full tutorial from 0 to deployment of a unity multiplayer?

shadow seal
#

0 as in you've made a singleplayer game and released it?

#

Or 0 as in welcome to Unity?

shadow seal
#

If it's the latter option, don't even bother with multiplayer

proven thorn
#

two questions:

  1. what's currently the "best" (most robust) singleton implementation that works with fast reload (no domain reload), handles multiple threads (ideally DOTS too), and ideally can auto-instantiate on start?

  2. what's the best data structure to store a list of weak references to objects I need to iterate over on every frame, and remove those that aren't valid anymore?

midnight violet
#

Are you talking about a simple list here with "weak references" ? @proven thorn

wispy epoch
fierce crown
#

Blittable types? Trying to pass a float[] into a computeBuffer and running into issues. Docs say that primitive arrays are okay but it's throwing an error

solid elm
#

*its ovveride in place of virtual

wispy epoch
#

Im trying to use a function from another class in my in app purchases manager. When i use it on initial start up it works fine but when i switch scenes and come back, i get errors. THe initial error was because i had it as a public game object i linked in the editor. I thought of correcting this by using GameObject.Find() in the start function of my IAPmanager. This works in that im able to make the call to the other script on that object, but i get an error "value cannot be null" on the audio source within that function. Im sure this is a common problem so how do i best solve it?

#

I dont want to reimpliment this function into my IAPmanager script because it makes an api call that i want in only one script per scene to avoid issues. if that makes sense.

flint sage
#

And lot more texture samples

wispy epoch
#

if my class is in doNotDestroyOnLoad, then how can I call a function from another class in it?

wispy epoch
#

I am creating an In app purchases singleton as unity recommends. I followed the steps laid out. How do I call a method from a different script in the scene in this type of singleton object. It works fine but not on reload of the scene. any references to other objects in the scene are lost and I cant get them again even if I use gameObject.find()

deep ivy
spark meadow
#

srry i misunderstood does the objects in your singleton lose reference or in other scripts?

#

if your singleton save the scene name currently loaded and check ever 1 second for the saved name to not equal the current name and run a func that grabs the references and update your ref to saved scene name with the new current scene name

wispy epoch
#

I have tried on awake and start i can try on enable. I've had problems with other scripts saying the audio source is null when called from the singleton so i just ended up implementing those functions into the singleton class. Problem still exists that it loses scene references when changing scenes the reloading back into it

#

I was thinking that on enable wouldn't work because the singleton is never made inactive in the doNotDestroyOnLoad set of items so I didnt think it'd ever be hit

spark meadow
#
    private string saveScenename;
    // Start is called before the first frame update
    void OnEnable()
    {
        saveScenename = SceneManager.GetActiveScene().name
        Invoke("WaitForSceneChange", 1);
    }

    private void WaitForSceneName() 
    {
        if (string.Compare(saveScenename, SceneManager.GetActiveScene().name) == 1) 
        {
            saveScenename = SceneManager.GetActiveScene().name;
            UpdateReferencesFromNewScene();
        }
    }

    private void UpdateReferencesFromNewScene()
    {
        // find your objects here.
    }
green rock
#

Does anyone know why screen point to ray doesn't cover the whole screen when you change aspect ratio?

#

But with Full HD 1920x1080 it does

serene sparrow
#

This is really advanced topic for people who knows about it, i need help.
Changing scenes stops Tasks/Async even if the object is don't destroy on load what the cause of it?

lunar lantern
#

hi, are there any good boids/flocking library out there suitable for building simple RTS unit group movement ?

wispy terrace
#

What you guys think is the best pathfinding algorithm for a tile-based tower defense?

flint sage
#

pregenerated paths?

proven thorn
# midnight violet Are you talking about a simple list here with "weak references" ? <@149302430927...

well I know list exists, but removing from a list is O(n), and you can't remove while iterating either, so not really sure how you'd do a linear time zero allocation "delete some elements" ... seems having a HashSet<WeakRef<T>>, iterate over it and store "marked for delete in List<WeakRef<T>> and then iterate over the list and remove it from the hashset is the "fastest trivial solution", but that still seems pretty terrible both performance and memory-wise

seems almost trivial to do it in linear time by storing empty slots and shifting "kept" elements to the left, but I'd rather use a solution that won't have me write unit tests for a custom algorithm, I'm sure I'm not the first person that wants this

brittle pumice
#

Wondering if someone could help me

#

Is there a way to execute a method on a script when it is dragged into the project folder

brittle pumice
#

Kind of like [RuntimeInitilizeOnLoadMetod] but for when a script is compiled

plucky laurel
#

as for the question i have a custom array wrapper that does exactly what you want

#

the trick is simple - if order is of no concern - store the index in the element itself, and instead of shifting on remove, you swap the removed element with the tail

#

name is arbitrary, didnt give it any thought

somber swift
plucky laurel
hoary mango
#

Hey, I'm having trouble with stuttering when trying to make my player's pet follow him. How can I make him go to the target location smoothly? It's either lagging behind when the speed's too low, or stuttering when the speed to high. I know I'm supposed to use fixed update for that stuff, but it seems to be creating more problem than anything else, there's less stuttering when decreasing the physics timestep, but I guess performance might suffer from it.
Ideally, I just want the pet to be always at a certain distance from the player.

dapper shuttle
#

Is there a way to dispose NativeSlice<byte>?

sage radish
dapper shuttle
#

but maybe whole possilbe

sage radish
#

But the original native array still exists and now part of it is disposed. In theory, the NativeSlice could keep a reference to the original NativeArray just so it can dispose it, but it doesn't. It only has a reference to the start of the slice, it doesn't know where the array actually starts.

#

So you're stuck with keeping a reference to the original NativeArray yourself and dispose it directly

plucky laurel
#

isnt a slice just a pointer offset struct?

sage radish
#

Yes, but it doesn't store the pointer and the offset, it computes pointer + offset in its constructor and stores that

final steeple
#

Specifically, a slice is a pointer and a length

dapper shuttle
#

what if I make the variable as

NativeSlice<byte>? ns;

and when I want to dispose it just say
ns = null

what would you expect?

final steeple
#

(Also a stride, in Unity)

dapper shuttle
final steeple
#

Contrary to the .NET Span<T>, which does not support strided slices

final steeple
#

For example, if you had an array of Vector3s

#

You could use stride to get a slice that only refers to the X components

final steeple
#

Normally the stride is just sizeof(T)

#

But in the example above, it would be a NativeSlice<float> with a stride of sizeof(Vector3)

#

It's handy when you're dealing with vertex buffers

sage radish
final steeple
#

NativeSlice<byte>? can be null

agile yoke
#

No, note the ?

#

It would just not dispose the original array / list correctly

final steeple
#

There's little reason to have a nullable slice, yeah

#

Better to just use an empty slice there

sage radish
#

You shouldn't be in a scenario where references to the original NativeArray get lost and you only have a NativeSlice.

#

You're creating the NativeSlice at some point, so you must have a reference to the original array at some point.

final steeple
#

Yeah, the slice isn't generally what you would want to "keep"

#

You can create sub-arrays, but those can't store stride

#

This reminds me, now that Unity supports .NET Standard 2.1 I should look at porting my StrideSpan<T> to it

dapper shuttle
#

Thanks to @sage radish @final steeple@agile yoke@plucky laurel

I understood what NativeSlice means now ๐Ÿ™‚

I am just trying to make an wrapper which deals with NativeSlice<byte>
and I just can't see or touch the origianl array

but when some errors occur it says
"A Native Collection has not been disposed, resulting in a memory leak. Enable Full StackTraces to get more details."

now I understand that I can't dispose the slice so I must not make any error in this methods....

final steeple
#

Yeah, the code that creates the array is considered the "owner" and is responsible for disposing it

#

A slice is like handing out a "rental" over part of the array

wispy epoch
#

Its been like 10 hours so im gonna ask again. Anybody know the best way to call methods from scripts on other objects in a scene when using a singleton? I lose the references to other game objects whenever i reload into the scene

sly grove
#

A common pattern is for scene level objects to register and unregister themselves with the singleton in Awake and Ondestroy

azure hinge
#

Hey guys! How should addressable changes be tracked with VCS like Git, Perforce, etc? I've marked a lot of prefabs as addressables but the fellow developers don't see them as addressable when pulling
I've noticed those are not stored on the prefabs themselves..

wispy epoch
sly grove
#

Register(this)

plucky laurel
#

anyone has some workflow for indicating that virtual overrides should have their base call skipped?

#

i dont know of anything in the language to help with it, but someone probably has a nice trick

azure hinge
plucky laurel
#

more clearly - i need to indicate for programmers, in which cases the base call is mandatory, in which it must/can be omitted

sly grove
#

I think any pattern where the base call is mandatory is an anti pattern

#

Restructure it so that's not the case

plucky laurel
#

you realize you are opinionating?

sly grove
#

Yes

azure hinge
#

for me it would make sense calling the base method if it's some kind of setup. For example:

#
    
    int value1 = 0;

    virtual void Setup() 
    {
        value1 = something;
    }
}

class B : A {
    
    int value2 = 0;

    override void Setup() {
        base.Setup();

        value2 = 5;
    }
}```
plucky laurel
#

yes, the issue is that other people on the project can create all kinds of bugs and have very confusing scenarios when there is no clearn indication of when to call the base and when can you omit it

#

its something that should have been solved on the language specs level long ago, because there is no middle ground between virtuals and abstracts

sly grove
#

There's no way to fuck it up

plucky laurel
#

you cant apply it everywhere

sly grove
#

The base stuff happens and the virtual part is "extra"

plucky laurel
#

its a good sandboxing practice but its not a "cure it all"

azure hinge
#

I like that approach, but it wouldn't work if the Child class doesn't wanna do the printing..

plucky laurel
#

if i could/wanted to apply it globally to the whole codebase, sandboxing each and every case everywhere, i could establish a "no base rule" or something

#

it just wont work in many cases, where you expect to traverse the call chain and pass results

azure hinge
plucky laurel
#

how to clearly and explicitly indicate it

#

wild idea - analyzer and attribute

azure hinge
wispy epoch
#

Okay so void Register(GameObject this)
{
//But what goes here? Is there supposed to be a series of if statements or something? I need to "register" 3 audio sources, a script, and 2 game objects for this singleton

}
@sly grove

spark meadow
#

plus where did i use gameobject find

somber swift
spark meadow
wispy epoch
spark meadow
#

thats what you would do not what i would do. Thanks for playing

wispy epoch
spark meadow
#

i know a lot

wispy epoch
plucky laurel
wispy epoch
#

Right I'd much prefer actual help. So anyway, i was just told instead of trying to find references in a singleton, i can have the singleton's script contain a method for registering the objects, but my question is how would i determine which object is which when calling that method? Just a series of if statements?

And how do i call the method from other game objects on awake? Do i need to set a reference to the singleton in code using gameobject.find() for those scripts? Then call the function

tough tulip
#

if you're working on a sdk, then comments are the obvious way to go. if this is for your private project, you could create an attribute and write tests for the pull request. but its going to be very time taking

plucky laurel
#

what about analyzer?

#

im thinking it over, but need hands on tests. worried about compilation performance

#

on the other hand, its a good way to generate a bunch of errors for all virtcalls

#

for the speedy refactor

sly grove
#

For example keep a list of audio sources you need to know about

plucky laurel
#

the problem is keeping the singleton alive? or registering its subjects?

wispy epoch
sly grove
#

I think their singleton is holding references from the initial scene and they're trying to figure out how to not keep those broken references

#

So I'm just saying to have them register and unregister themselves instead

wispy epoch
#

singleton stays alive but loses references to objects in the scene it needed. So Praetor recommended instead inputting the references from the other objects

plucky laurel
#

use OnEnable/OnDisable

#

MyClass.instance.Register(this)

wispy epoch
plucky laurel
#

or Start/OnDestroy

sly grove
wispy epoch
# plucky laurel or Start/OnDestroy

i did Awake and didnt do anything for onDestroy or anything. is that a problem? shouldnt it lose all references to them anyway when they're destroyed

plucky laurel
#

it doesnt work like that

#

the references will still be in a collection, they will be invalid, but still there

wispy epoch
wispy epoch
plucky laurel
#

List<GameObject> list = new..;

#

list.Add(new GameObject());
list.Add(new GameObject());
list.Add(new GameObject());
list.Add(new GameObject());

#

you destroy all of them