#archived-code-advanced
1 messages ยท Page 182 of 1
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
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
Yes probably not the intended use but it simplified the code quite a bit
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
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?
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
I start the ad one time and everything works swimmingly when i start the ad on first load of the menu scene, but if i play a game then go back, the ad is called twice which i think is the reason why its saying the audio source is null
I've just had a thought. Maybe its because the ads listener is like double initialized from first load and i have to disable the first listener somehow
Yes thats why i asked to log the gameobject and instanceid
Added this and it fixed it. thanks
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 ?
this might apply to your use case https://gamedev.stackexchange.com/questions/198692/how-to-return-an-unknown-amount-of-data-from-a-parallel-job-c-jobs-burst
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.
were they working before
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
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?
Tried it, didn't work ๐ฆ
One is for prefab another is for everything else I suppose.
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
That one is for Unity ๐
Maybe addressables are handled differently
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
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
is the prone collider also cube?
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 )
Cube works good with 100 speed and character barely move with 150
Perhaps you're using the default physics material that's got some friction.
And two box colliders on one object is not normal.
Why are you setting the x and z velocity to zero ?
I don't know now - I have to remember ๐
comment that out to see the result. Best way ๐
should I be concerned about using this operation? I'm thinking high garbage collection issues cs IKillable[] killables = FindObjectsOfType<MonoBehaviour>().OfType<IKillable>().ToArray();
It will be horrifically slow
Sounds like garbage hell
also, yes, it will create an array of every single object, and then discard it
so GC impact too
ok assumed so, might ditch the interface all together for abstract then
Consider inverting the control and let killables register themselves in OnEnable or something
I will look into this , thank you!
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 ๐
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?
pretty sure pointer_stringify has been deprecated for a while now
yeah, utf8tostring would work
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
if you still insists on doing so, proly use .SetText instead of the good ole text for assignment
either way, the amount of garbage to be collected is huge there still
Its not programatically, its when I edit the input field, and paste into the edit box that shows up
I just tested programatically, it works like a charm,
yeah, .SetText will produce less allocation
Its just when manually pasting into the box
Ok can try that, but it works without it
But still doesn't paste everything when manually pasting into the edit box that shows up
as Galaxy said, 20k is a ton!
I'm pasting a story to be read.
so its a very big chapter
but has to handle things that size
you can just render it partially based on what displayed on screen
Sorry?
Rendering isn't a problem
its pasting into the editor box that pops up in Android for a input field
the idea is when pasting, you truncate what can be displayed at oonce on screen
huh what? it pastes way more than what can be displayed on screen
20k words is no joke, especially in c#
I paste in about 16k words where it cuts off I recon
yes, you can(virtually) truncate the text shown at once
while in inputField
it won't get shown at once anyway
but those 20k will still intact.. at the back...
behind the scene
They are not
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
๐ 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)
So input field has some artificial character limit placed on it?
caching or holding 20k strings in memory would still be bad anyway, you need to come up with something else..
if I need them you mean I have to do shit like saving to file etc?
json would be enough
well yeah but saving on phone
doesn't matter, json works practically anywhere
I'm confused what you mean here too, if I am caching json into a runtime variable its the same as doing a string? its a single string with 20k words, making it into a json isn't going to do anything
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
Someone know how i can remove Plastic SCM from my project?
delete it?
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.
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.
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.
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
You should probably be using them separately. Make a Load() and Save() and use read/write to do what you need in them.
Could u please help me with the basics for example if I create a file how do I then edit it / write content to it? if u would be able to make an example it would be hugely appreciated
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
**solved
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"));
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
-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"?
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
again, please explain "how they should work" and how they are actually working
what is BlockEdge?
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)
wdym by a sprite?
Sprites are basically just image assets
literally just a cosmetic picture
they are not objects you can put in the game world
that would make sense
so is it decalred like Sprite BlockEdge?
yeah
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.)
did it, nothing happens
literally nothing happens, the world generates as normal with no outlines
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);
}
"nothing happens" is definitely not true. if you look at the newly created object's SpriteRenderer, its sprite will be assigned to BlockEdge
your NewSprite line at the end is pointless though, and will cause a memory leak
that cant happen because im adding a new sprite as a child of an existing tile
what can't happen
all i want is to take my existing tile, right? and slap a child sprite on it that sits behind it
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
i do not want to replace the sprite of the tile in the editor
all of which you are doing in that code
who said anythign about this
clearly not because it looks the same
show the hiearchy and inspectors of the objects after this code runs
this is the limestone things
show the new GameObjects created by your code
blockedge?
WHich would be called "GameObject" or something, as you didn't give them names
GameObject newTile = new GameObject(); this creates a new GameObject. Show that object in the hierarchy
did this code even run?
it has to
if it didnt run it wouldnt have a hitbox
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??
yeah
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
newtile is acually not an object, just a port for several objects
ok so the code is working, as I guess BlockEdge is the limestone sprite?
no
hard to explain, can i screen share?
But I dont need the code
I just want to know which objects are which in your hierachy
its limestone with the occasional ore
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?
Then limestone is the new tile object
If you want another sprite as a child of that you need to create another GameObject
And give it a SpriteRenderer too
how do i convert a sprite into a gameobject?
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.
i got it to spawn them, now i just gotta parent it so that it attaches to the block
yep, you'realready doing all the similar stuff in your other code
setting the parent etc
just follow the pattern you had there
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?
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
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
there's also a typo in your code
what is it? ๐
.TransportToGaol
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
Gaol is an old word for Jail
Is this Jason Weimann's FSM?
the more you know XD
alright, gonna try it out. Not sure if its Weimann's FSM. Followed my professor and now "figure out yourself"
Ah, ok
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?
is this urp 2d lighting?
are you saying that something in UGUI doesn't look right? maybe send a screenshot
the game isn't automatically decreasing resolution of something. try to express what visual issue you're seeing is
#archived-code-general it could be many issues. shared material is usually not what you should be modifying. also, load external texture is authored by you or unity?
yes
you can remove plastic from your project by deleting its hidden folders and disabling unity collaborate
you can't render 20k words in a single input field performantly in unity on android. try reading the clipboard separately or show only the last e.g. 500 characters in the input field
Basicly, i'm creating a movable handle.
why? what is your objective?
query an abstract class instead
if you want to use find objects of type
you can also see how event system finds interfaces performantly
i think the material for the ground has to be unlit right?
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.
it sounds like there are many pieces of this puzzle
but in my opinion ref does not help you with any of them
from your description
Yeah there are quite a lot since this editor is responsible to create the whole ship.
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.
if you are asking in #archived-code-advanced you will know how to use interfaces correctly this way
google UniRx and read about it
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
however, access checks are pretty meaningless in your own code, so don't overengineer it
you are recreating reactive properties from unirx i.e. from reactivex
that is a bad idea
use ReactiveX for unity, which is UniRx
why is that a bad idea? if you don't need the entire library of unirx
I don't see a huge issue with that solution, seems pretty clean to me
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
why is it bad lol
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
yah but it works and they don't need the entire unirx ecosystem to get one thing working
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
it's not like they're trying to make their own rx library
the user is right now authoring their own bad rx library
no, they're making a single get and set hook for a specific portion of their editor
i don't personally find comparisons of size compelling when talking about useful code. after all, unity is quite heavyweight, and adding unirx when measured in an absolute sense against the whole application including unity is a rounding error
@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.
adding external dependencies have more weight than merely their size
i don't really credit adding dependencies as an interesting or substantive line of discussion.
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
ok then
thank you for understanding
uh huh
lol
@uneven crypt so something like a lattice deformer* might make more sense for general sizing
nope, that isnt the issue here
I figured it out, It's because that shader uses boolean and custom editor set the boolean, so it can be color and slider OR a texture. I created my own shader and it worked.
yeah seems weird
seems like something was toggled and your scene setup got borked
no, if there is a gap in the side walls it works, fine, its bc its making the inside of the walls the surface which actually should be the walls
basically its doing this part shaded
when i need it to shade this part
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
Okay, thank-you, reading about UniRX since i have a bit of trouble to understand exactly what it is ๐
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 ๐
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;
}
Oops fixed it
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 :)
oh my bad i meant to say
Add.itemPosition = worldObj[i].transform.position;
either way it wont work because i need to tell it to go inside myData[index] > itemPosition[index]
i dont know what you want to do, but i think you're struggling with the syntax in here. you'd have better luck in #archived-code-general or #๐ปโcode-beginner since there are people very talented there to help with problems like this. im sorry i dont even understand the problem jere
Thanks ill try my luck over there.
okay sweet
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
People in beginner said IO was hard lol anyways I solved it.
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);
You can just create a delegate that takes a this object as its first argument
how?
I want to reuse the one that's cached
that's the whole point
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
ah ok I'll try it, thanks
C#/VB/F# compiler playground.
yeah I got it from the description
I don't need to worry about jit compiler in Editor when I use Il2ccp in build, right?
thanks
Need Help #๐ปโcode-beginner message
You wrote your function inside another function
Move it out so it's inside the class instead
Also, don't crosspost @amber spear
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?
I think it's a good start
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;
}
.
.
.
}
Not really understanding your question. What are you wanting to compare this code with exactly?
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
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()
I'm not sure I follow
When you call base, it executes teh constructor of Set. Which might do additional calculation
this part : base(color) means "Call the constructor on the parent class that takes one Color[] parameter"
The other thing you're doing is just setting fields directly
Yeah
Which one is better to use? because setting them directly would make the code more comfortable to read.
You might also want to hardcode the parameter color, e.g. public Group(int value, float minSeqX) : base(new Color[] { Color.Green })
generally you will want to call the base constructor, because it may do additional things you're not aware of to set the object up properly. But it really depends on the particular case at hand and whether you want those things to happen or not.
Even just for the sake of DRY principle it's best to call the base constructor usually
And for primitive variables there shouldn't be any problems with direct setting right?
You might want to reconsider your design if you don't want those things to happen, as it likely shouldn't be inheriting in those cases
"primitive variables"?
C# is not java, there are no primitives
int, float, etc
Again, no matter the type, the base constructor might do additional calculation like enforcing a range
Alright
So sure, in your simple use case it doesn't really matter
Got it. Thanks for the help
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
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
the problem is that when you spawn in (this only happens in the apk, not the unity test) you are floating in the air and your hands are like falling
can anybody help with this
okay that's good
VR projects are hard to setup. i suggest https://github.com/Unity-Technologies/XR-Interaction-Toolkit-Examples
oh dont worry i solved it by putting an xr origin as floor and setting the grass to floor
what are you making here?
what is your objective?
It was handled already but thanks anyways
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;
[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
are you working from a tutorial for 2.5d games like this?
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
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 ๐
yep that's correct, i would like a character to be able to jump up to the higher levels - like this
lol, of course :p my question was more so the method of detecting them - currently my tiles at the same positions have no difference in z so i don't think my initial thinking of using raycasts would work
unless i did a raycast from the camera
there are two approaches.
-
lay out your world in 3D and render it in 2D. advantages: real physics. disadvantages: requires dedicated asset / sophisticated knowledge around isometric rendering.
-
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
the #archived-code-advanced perspective would be you ought to be able to "look up" between different dictionaries the tiles located at a coordinate x z
but since you didn't see that solution you should use an asset store package. not meant to be condescending.
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
Dependency injection in a generic factory object
that instantiates a prefab, then calls Initialize() of a component with the stored arguments
this is what i used @rain ice which is approach #1 https://assetstore.unity.com/packages/tools/sprite-management/isometric-toolkit-33032
interesting, and that provided out of the box ways of handling situations like mine above?
I just didn't want to encumber my objects with interface implementations
hmm. one consideration is you're only going to have the insight as to what "Approach #1" that i wrote really means by buying this asset and seeing how simple it is
Instead, get the method by name at start
@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
i see. i'll keep it in mind, but i'm not really too keen on purchasing a package immediately when i've only just started working on this project
thanks though ๐
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
hmm... and pre-existing DI packages do not suit you?
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 ๐
hmm
this sounds like the answer of someone with no experience
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 ๐
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
okay so that's a different game
but you don't seem familiar with them, so i can understand why you seem to keep pushing 3d when it's not necessary
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
no of course, my apologies - i should have made that clearer when i sent through the screenshot - i meant appear to ๐
there's a lot of stuff to do with this kind of game
there are good assets for it
it's tricky. i like the dev logs for Into the Breach
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?
cool thanks, i'll take a look! can i find them on youtube? or are they blogposts
maybe i'm hallucinating. they gave an interview once about these details. big lua game.
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
They do, I think, I have not tried integrating them
it's tricky.
DI isn't useful in games so you won't find good stuff for unity using it
sorry
I believe he means specifically with idiomatic Unity
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
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
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
(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
and making everything into a singleton is implicit context and even less testable and maintainable
^ 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
Yes it does. Not necessarily unit testing specifically, at least the ability to test limited functionality in an isolated scene
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
I'm refactoring a pretty big legacy code base right now, and it's such a fk mess. I'm splitting stuff up just for the sake of being able to understand the problem
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
I think it's just an unfortunate consequence of writing a game engine with idiomatic C# OOP, there's no good way to solve the problem of needing to introduce more files and more classes to implement more functionality
coupled with the compile time.. I find the dev experience quite frustrating
yeah that's horrible
is anyone around for a not so advanced but annoying issue?
not so advanced
Posts in advanced channel anyway
Does not describe issue right away
=> Please see #854851968446365696 for question posting guidelines
yeah because:
- If you see the other channels, the question management is non-existent
- what is advanced anyway - so vague
- Apologies I missed the "don't ask who is available rule"
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
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;
2d game? 3d game? Perspective camera? Orthographic camera?
3D perspective, the camera is mostly rotated looking at the player directly, almost like side scrolling
you'll want/need to be using a raycast here
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
raycasting to the plane of the game world
using Plane.Raycast
(not a physics raycast)
See the very bottom of this page: https://help.vertx.xyz/programming/specifics/screentoworldpoint
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
never used this, i ll read up on it thanks
Trying to attach the same behaviour script to 30 different animation clips
How do I do that quickly?
AnimatorOverrideController?
unless i've miss-read the question
+that is nice to look at
bar the names
@sly grove worked! thanks
lol
Yup. Figured.
also, if the allocation happens in the parent rather than in any of the children the sum wouldn't be equal to the parent's value. Same as with the total vs self columns.
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
dont forget to clear the profiler, i once spent lots of time profiling where im leaking gigabytes of mem lol
immediate mode GUI?
you can edit out the character for the next frame
Yes, like cs void OnGUI() { if (GUILayout.Button("Press Me")) Debug.Log("Hello!"); }
This is the Immediate Mode GUI system
i know doot
edit it out of the text for the next frame
that's as good as it's going to get
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.
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
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
sorry, I think I didn't ping you by mistake
No idea what you need from this description
https://github.com/Unity-Technologies/UnityCsReference/ Maybe you can find it in the reference source?
@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
You should be able to access those from the ModelImporter
(ModelImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(model))
They appear to be stored in https://docs.unity3d.com/ScriptReference/ModelImporter-extraUserProperties.html
Thanks @final steeple let me try that
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.
Zenject. How to inject follow transform of cinemachinevirtualcamera component?
I have transform in prefab which i want to bind into cinemachine follow transform
thanks! Those are some things I'll have to look into
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?
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
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
please elaborate
I don't understand the idea
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
what's GameEventUpdated?
A event Action
I don't know when you call that event
Well that calling of the event is fine, it's just the subscribed callback does not get fired ๐
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
This shouldn't be compiling if GameEventUpdated is defined as Action. Action is not the same as Action<GameEvent<TGameEventData>>
It is defined as that
But I didnt type it all out
Just trying to figure out, why my callback does not get invoked
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.
When you implement ILogger, do you need to implement ILogHandler also?
what's your objective? didn't we discuss using ZLogger?
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
it would appear you have to implement it all to do something useful. it seems poorly thought out
use ReactiveX if you want to publish/subscribe events. UniRx is the Unity implementation
Nope
What do you mean?
yes, it's the AssetDatabase methods
use a dedicated logging library based on the proper dotnet logging infrastructure. ZLogger is one for Unity
unity's DateTime and related are incomplete on some platforms and versions
@desert oyster what is your objective? what is this code for?
Rn, my interests are into custom console, more specifically to open the solution, then the file where the log came from and focusing on the line number given.
my code is for calculating sun position based on the geo location and time
okay so why do you care about ambiguous daylight savings times corner cases
I was just asking why is it the case that updaing unity to newer LTS changes the behaviour of core .NET functionality
i suppose in the same way that updating a .net point release can result in changes to time functions
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
Unfortunately I had to update because of another bug
yea its not a big deal for me, just was wondering why my tests was failing
without tests I wouldnt even notice it
tests 
yeah you're in a good place
I've been searching online without luck, what platforms would using .Net 4.x with Unity, instead of the default, break?
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
Don't cross post
Seems like you have a dangling handle to the file, restart Unity/your computer
by restart you mean close and open unity?
Yes
did it but its just happen after short time
Restart your computer
ok thank you
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
Start here
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
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...
I bought an asset to do it for me. It's a huge pain
which asset?
Lemme try and find it, always have a hard time finding it again
okay
Ah, this is it. Looks like there's a v2 out now https://assetstore.unity.com/packages/templates/systems/blocks-engine-2-201602
oh god it's Scratch
okay
What they wanted haha
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
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
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
osx?
macos
oh
i saw
a unity project tho
you dont have to install a thing on pc
it is in the project
I never said you did?
ik but
pls
i know
okay
would it work if it was online?
like a webpage
using github pages
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
what about ifs repeats... etc
speed is the only reason you'd worry about generating code in runtime
what about them?
how would i create them
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.
okay
There is no job posting on this server. If you have a question, ask it, otherwise there are links in #๐โcode-of-conduct to the forums.
which one?
Reread the initial question too please
There's also an individual AssetDatabase.SaveAsset method
yeah it's relatively new
Thanks, didn't know about (mostly because I've been stuck in 2019.4 for aaages)
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
That's been there in UnityEditorInternal for a long time though
Yeah, but it can be used to "forcefully" save an asset
Did they move it to AssetDatabase or is it still in unityEditorInternal?
It's still in UnityEditorInternal
It's pretty handy
๐
Since you can force binary serialization for performance too
I've used it in the past for configs/library data
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
But now that ScriptableSingleton is properly supported, I don't really need it that much
That's pretty impressive
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
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?
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
How does that work if lightmaps generally have multiple lights in each texture? Or do you encode a lightId in the texture somehow?
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
Really useful for doing stuff like this: https://www.youtube.com/watch?v=IEMRn763khE
The city is full of various machines and devices that you can use to your advantage. Find ways to cut the power to buildings and street lamps to make sneaking around easier or shut down security defenses.
Wishlist at https://store.steampowered.com/app/1150760/Gloomwood/
So I guess disksize of those textures is a lot higher than the normal unity lightmapping right?
They can actually be smaller sometimes
I did a lot of trickery to keep sizes down and avoid storing unnecessary data
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 
This is part of the code involved: https://github.com/NewBloodInteractive/com.newblood.lighting-internals
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
Is renderer the mesh or the light source?
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
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
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
Let me now once you do, interesting stuff even though I know very little about rendering and lightmapping
This might be the key to my dream of making a network distributed baker in unitt lmao ๐คฃ
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
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
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
Aha. And you then you reconstruct the whole lightmap at build time or ?
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
Then https://github.com/NewBloodInteractive/com.newblood.lighting-internals/blob/master/Editor/LightingData/ScriptableLightingData.cs#L142 gets called to update the lightmap indices and other values
How do you handle bounces to renderers that the lightt doesnt touch ? I assume "touching" means a renderer is within its range
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
I see. Sounds like something we would licence later this year when we enter production on a big project
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
Sounds nice
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
Nope
You can't even get the number of materials without allocating
(There's an API for that, but it's private)
That works too tho, let me check the source code
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
[FreeFunction(Name = "RendererScripting::GetMaterialArray", HasExplicitThis = true)] extern private Material[] GetMaterialArray();
yeah, it all calls into native code
Yup, the layout isn't visible to managed
Yes, there's GetMaterials and GetSharedMaterials which will fill a List<Material> that you provide.
https://docs.unity3d.com/ScriptReference/Renderer.GetSharedMaterials.html
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.
Yeah, that works fine, thanks
Right, I forgot those existed
But they don't have SetMaterials/SetSharedMaterials for some reason
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
{
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?
STOP crossposting #854851968446365696
have you ever tried a simple hdrp project on steam deck?
Nope, we don't use SRP
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
Yeah we just haven't done any tests with it since none of our games use it
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?
I don't even know why you;re sorting that array
And why you're doing ToArray afterwards
i need them sorted from closest to farthest
idk tbh I think I need it?
yea i do..
you can just var colliderInIenumerable = without ToArray, then do foreach after
look at layer specific collision. Separate your colliders by adding a layer to them other than default and look for the raycast on those objects specifically
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
ik ill do all of that
but
wouldnt this one: gameobject.activeinheiracry only work in the editor?
no it will work during runtime
ok lmao..
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 ๐
This isn't how layer masks work. Read through this https://docs.unity3d.com/Manual/Layers.html
yea I rly don't know how they work..
I never saw this kind of declaration could you explain it quickly maybe? Because this documentation doesn't cover it.
ok I found something
thx
thanks to everyone here this drastically improved the performance
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).
@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
Got it. I knew there was some generally accepted practice to achieve this "effect". I just couldn't think o fit.
Yes.
tf2?
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
why do you need to use a custom certificate for a video game? also, TSL seems like a typo
if they're really far apart from the camera that distance will be probably be larger than if it were close
you can encode each light/group of lights into its own lightmap, bounded by some distance, then composite (i.e., blending mode add) the textures in a shader to get the "final" lightmap
company pay to earn NFT game, it is not a typo tho
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?
what is your question?
when you say instance id, you mean your own instance ids, and not unity's, right?
are you using a pre-existing voxel engine
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?
unity has a IAP integration if you like to use it
https://docs.unity3d.com/Packages/com.unity.purchasing@4.1/manual/Overview.html
Hello guys, there is a full tutorial from 0 to deployment of a unity multiplayer?
0 as in you've made a singleplayer game and released it?
Or 0 as in welcome to Unity?
If it's the latter option, don't even bother with multiplayer
two questions:
-
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?
-
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?
Are you talking about a simple list here with "weak references" ? @proven thorn
No pre voxel engine
Yea thats what im trying to learn. Tutorials ive seen all use codeless, which ive heard is bad. But the documentation isn't great and seems to only point to the package manager samples which im not understanding
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
*its ovveride in place of virtual
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.
Sure but that should cost a lot of extra storage no?
And lot more texture samples
if my class is in doNotDestroyOnLoad, then how can I call a function from another class in it?
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()
Use Unity.Netcode. I wrote a word vomit Reddit post a few days ago. Essentially, use ServerRpc and ClientRpc to send data back and forth between server and clients.
11 votes and 20 comments so far on Reddit
make sure you are grabbing your references in on enable and not start or awake so that way you can get them anytime the scene is reset as onenable will run
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
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
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.
}
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
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?
hi, are there any good boids/flocking library out there suitable for building simple RTS unit group movement ?
What you guys think is the best pathfinding algorithm for a tile-based tower defense?
pregenerated paths?
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
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
Kind of like [RuntimeInitilizeOnLoadMetod] but for when a script is compiled
- its not really O(n) if you know index, the element shifting is costly but not really linear
- you can remove from a list with a reverse for while iterating
as for the question i have a custom array wrapper that does exactly what you want
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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
What you mean by that? Can ypu give more context (and maybe the code youโre referring to)?
What do you want to achieve with that?
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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Is there a way to dispose NativeSlice<byte>?
It's a slice of a native array. Would you expect that disposing the slice would dispose the whole array, or just that slice of the array?
just that slice of the array
but maybe whole possilbe
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
isnt a slice just a pointer offset struct?
Yes, but it doesn't store the pointer and the offset, it computes pointer + offset in its constructor and stores that
There's this method to get that pointer, but it's useless for getting the original native array unless you know the offset and stride of the slice, which also isn't stored in the slice
https://docs.unity3d.com/ScriptReference/Unity.Collections.LowLevel.Unsafe.NativeSliceUnsafeUtility.GetUnsafePtr.html
Specifically, a slice is a pointer and a length
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?
(Also a stride, in Unity)
what is stride?
Contrary to the .NET Span<T>, which does not support strided slices
The distance between elements
For example, if you had an array of Vector3s
You could use stride to get a slice that only refers to the X components
I see
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
You'd get an error because NativeSlice is a struct and can't be set to null.
NativeSlice<byte>? can be null
There's little reason to have a nullable slice, yeah
Better to just use an empty slice there
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.
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
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....
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
Isn't it highly inefficient to be making a call to gameobject.find() every second?
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
It's relatively rare for the singleton to keep references to other objects directly
A common pattern is for scene level objects to register and unregister themselves with the singleton in Awake and Ondestroy
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..
How does that work? How would i have game objects register themselves into the singleton
With a method on the singleton that they call
Register(this)
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
afaik base calls will be skipped by default when overriding if you don't do base.MethodName();
more clearly - i need to indicate for programmers, in which cases the base call is mandatory, in which it must/can be omitted
I think any pattern where the base call is mandatory is an anti pattern
Restructure it so that's not the case
you realize you are opinionating?
Yes
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;
}
}```
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
Yeah which is why I'm saying it's better to have a set up like this
#archived-code-general message
There's no way to fuck it up
you cant apply it everywhere
The base stuff happens and the virtual part is "extra"
its a good sandboxing practice but its not a "cure it all"
I like that approach, but it wouldn't work if the Child class doesn't wanna do the printing..
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
I would suggest by default not calling the base, unless it's specifically required
this, anyone? Pretty pls ๐
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
no highly inefficient is calling it over 300 frames a second
plus where did i use gameobject find
you mean 300 times a frame?
ty or 300 frames a second if you do not have frame rate capped
Well yes that'd also be highly inefficient. Its not that bad but its certainly not good to do. And u didn't explicitly. You used comments to say "find your object here" which i would use GameObject.find() to do that
thats what you would do not what i would do. Thanks for playing
? Why playing semantics? Im looking for help here
i know a lot
Lovely bit of ego. Always love those kinds of devs
please not in #archived-code-advanced
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
how about a summary comment?
very simple and I always refer to it personally and thats what we use in our project
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
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
No just adding the thing to a list or a set
For example keep a list of audio sources you need to know about
the problem is keeping the singleton alive? or registering its subjects?
registering its subjects
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
singleton stays alive but loses references to objects in the scene it needed. So Praetor recommended instead inputting the references from the other objects
So i think i figured this part out now. I think the remaining issue is that I have buttons that want to call a method in the singleton but lose their reference to it on reload as well
or Start/OnDestroy
They need to just call a method in a script attached to themselves, then in that script you do singleton.instance
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
it doesnt work like that
the references will still be in a collection, they will be invalid, but still there
so like a script with just one method of onClick rather than public reference set in editor?
okay so do i need a seperate function in the singleton script thats called on destroy of each object? little confused by that