#archived-code-general
1 messages Β· Page 191 of 1
It looks like this makes the main thread run that method whenever it gets a chance to
which would be roughly equivalent to having a job produce a list of things you want the main thread to run
although, does Invoke also block the thread until the action is finished running?
yes it does
but it would be the same as running any other code
what I generally do in WPF is do all the network IO in the task, then invoke the main thread and update some UI state there, which takes no time
I see. I'm not aware of a way to do that, but there's a good chance I'm just not familiar enough with writing async code (in the context of Unity) to know
right
I've already posted the way to do it, twice
I'm reading it π
A script that makes as soon as you click the button it moves your object to another scene
please
Demands are not how you get answers here
ask an actual question about a problem you are having
also the demand is unclear
and do not cross-post.
consult #854851968446365696 for how to ask such a question.
yes it does
sorry about that π
I was just trying to understand the flow of it, it's all clear now
basically calling one of the methods will decide where/when the task will run
Speaking of doing things in the background, I have an annoying problem.
I want to do a huge number of raycasts against level geometry. RaycastCommand has been very helpful for this, but there is one issue: many things force all pending physics batches to finish before they can proceed. This includes stuff like moving character controllers or recalculating bounding boxes after LateUpdate is finished.
I just care about the level geometry, so there should be no need for this. These colliders aren't changing at all.
I tried creating a separate scene (with its own physics scene), but it looks like batches in physics scene B still have to complete before anything that happens in physics scene A can proceed.
Is there anything I can do about this?
It's possible that I just botched setting up a separate physics scene. I'll check that I actually did that properly.
What do these errors mean after fixing merge conflicts on github?
Corrupted assets, you likely did something wrong on the merge
I hate git so so much
what merge conflicts, did you manually try to fix a scene file or something?
yeah
i have been trying and failing to implement an inventory system to my battle system for weeks now
my end goal is to make it like the mario & luigi system; i've tried a bunch of tutorials however can't find one that particularly suits my needs
how would i be able to make an inventory system similar to it?
any help linking me to the proper resources n such would be appreciated
Easiest way would be to create scriptable objects with name, icon, and some gameplay related gameobject reference as items, and the inventory would be a dictionary of those objects as keys, and the values as amounts.
Don't merge scene files or any . asset file, ever. Only edit them through the inspector and then replace it on git, not merge
And when item is used, just spawn the gameobject that's referenced, with the player for example as parent, and let it do what it needs from there
hmmm alr
There is a unity tool to merge scenes
You can use an external merge tool in most gui git clients
You can use that
Scenes and prefabs
You can, but shouldn't. That's how you lose progress
Just add the tool, right click the conflict, merge using external tool and it'll solve... Most things. Then edit the rest by hand in notepad++. That's my usual approach
Keep your scenes modular, don't let two people edit the same one in different branches
Sometimes there are projects that you didn't have a hand in creating, and you have to live with what someone else made. That's where that tool is a true lifesaver
Anyone here use Sebastian Lague's BΓ©zier Path Creator tool? I'm using Unity 2021 and some Spline paths drift from their position slowly over time. It's really annoying having to move the splines back into place every time I have the spline object selected.
I'm using the github version as it is the most recent version.
Has anyone found a solution to the path drifting?
I used that tool once and didn't experience the drifting you're referring to. Have you tried Unity's first party spline tool instead?
for clarity, apparently it happens if the spline object is a child of another object while having a rotation applied to it
You are misinterpreting things, I was just asking if anyone has a script for this
Do you recall what version of Unity version you used? Might be worth trying it out in that version. 2021 LTS has the issue for me currently
Can you stop hopping all over this discord. You were asked to show your code and the issues you're having in #π»βcode-beginner , but you only did the first part.
I don't.
I am building on meta quest 2 and I am getting this error
why are you posting this here?
is not code
U told me to do so
2D seems to have this functionality: https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCollider.html
Is there a reason why 3D does not have it but instead has some primitives only? I have a serialized Collider field and would love to do an overlap run on it to be honest :(
well they are two separate Physics engine so they work kinda differently
what shape overlap do you need that you can't do with primitives?
I would like it to not be tied into any shape is my problem.
I wanted to serialize a collider, drag and drop any collider on it and be done with my day
I was hoping for a cone shape in the future for example, this puts a dent in my plans :p
hmmm you can make it Trigger and use OnTrigger I suppose
if you're doing a vision cone use something like a Dot product for FOV
then fire raycasts to make sure you're not blocked or something
Honestly if it means keeping a list of objects within the area using triggerenter and triggerleave I may just scrap it, it is a very weird omission to have in physics module
Any ideas why parallax background might be flickering?
π€· layer order fighting each other maybe ?
depends what "flickering" looks like and when its happening exactly
are you sure its code related?
I mean the whole parts just disappear and appear, not just the sides
im not sure
it happens really fast, but is really annoying
some kind of culling perhaps?
Hello, anyone know if it's possible to set the IP where the client must connect in NetCode for Entities ? (I've pack in ded server, and want to connect to ded deploy in remote server, but i didn't find anyway to set IP)
{
float temp = cam.transform.position.x * (1 - parallaxEffect);
float dist = cam.transform.position.x * parallaxEffect;
transform.position = new Vector3(startpos + dist, transform.position.y, transform.position.z);
if (temp > startpos + length) {
startpos += length;
if(textureIndex >= 0) {
textureIndex++;
if (textureIndex >= spriteArray.Count)
textureIndex = 0;
int tempIndex = textureIndex - 1;
if (tempIndex < 0)
tempIndex = spriteArray.Count - 1;
GetComponent<SpriteRenderer>().sprite = spriteArray[tempIndex];
transform.GetChild(1).GetComponent<SpriteRenderer>().sprite = spriteArray[textureIndex];
}
}
}``` if this helps
maybe you see my mistake
Are the parts on the same sorting layer, and order?
this is the hiearchy
they're all sprite rendereres, so order doesnt matter I think?
No, the sorting layer. It also has an integer order (lower being closer and higher being further away)
Nothing to do with the hierarchy
If you don't know what the sorting layers are, then they are probably all Default, and order 0, so it's layer fighting causing the flickers
Oh, here
The order in hierarchy is only relevant for UI Canvas Image components
SpriteRenderers arent supposed to zfight
are all gameobjects using sprite renderers ? are you using 2D Renderer URP ?
?
I think you're being sarcastic but they're most likely used in two different ways internally.
similar difference to between can be turned on/off and is on/off probably.
Oh wow. Ok. I always carefully lay out the sorting layers to avoid it. I know it's still important for having the order correct, but that is hilarious that I thought so for so long.
Thanks for the correction!
Edit: sorry for that heroshrine haha.
Yeah np, SpriteRenderer ordering uses: sorting layer, the order in layer and lastly hierarchy order.
The same with canvas renderer, they never zfight with the same renderer. They can zfight with meshrenderers.
I thought ONLY ui/canvas elements use hierarchy order
You are correct, my mistake. Sprites dont use hierarchy at all. Its like some internal order with sorting layers and order in layer are equals
Oh ok, and no worries! Haha
Learned two new things from you now with that internal order thing
Thanks a bunch!
why isn't OnEnable called in the script that is attached to DDOL GameObject? do I have to call it manually in SceneManager.sceneLoaded += _ ?
if its DDOL it only OnEnable once in beginning no?
well, now I guess yes ??
is there a method that is called in ddol when scene changes too?
except of my previous variant with action
the one you posted but no built in call
I see, thank you
I'm using this function to simulate fish swimming in a pond, and have them go toward a pellet if one is present.
void SearchSwimPoint()
{
//return a random point within range
RaycastHit info;
float travelRange = Physics.SphereCast(koiTransform.position, pellet && waterVol.bounds.Contains(pelletPos) ? Vector3.Distance(pelletPos, koiTransform.position) : swimPointRange, Vector3.zero, out info, 0f) ? info.distance : pellet ? Vector3.Distance(pelletPos, koiTransform.position) : swimPointRange;
swimPoint = pellet && waterVol.bounds.Contains(pelletPos) ? pelletPos : koiTransform.position + new Vector3(Random.Range(-travelRange, travelRange), Random.Range(-travelRange, travelRange), Random.Range(-travelRange, travelRange));
while (!waterVol.bounds.Contains(swimPoint) && !(pellet ? Vector3.Distance(swimPoint, pelletPos) < Vector3.Distance(koiTransform.position, pelletPos) : false))
{
swimPoint = pellet && waterVol.bounds.Contains(pelletPos) ? pelletPos : koiTransform.position + new Vector3(Random.Range(-travelRange, travelRange), Random.Range(-travelRange, travelRange), Random.Range(-travelRange, travelRange));
}
swimPointSet = true;
}
However, for some reason, these fish are swimming to the point (0, 0, 0) when the pellet is located at (0, -0.1, 0).
jesus how can you even read this function
ternary can be ok for a 1 liner but this is just....
why so many lines? you could do it much shorter for better readability
Also, once the pellet is destroyed, it shows up as "missing". Does that mean the object is not "null"?
I'd be glad for any suggestions.
Missing is basically just unity's fake null. you can compare it to null using the == operator and it will return true
first of all, it can be simplified using do while and property
float range => Random.Range(-travelRange, travelRange);
float travelRange = Physics.SphereCast(koiTransform.position, pellet && waterVol.bounds.Contains(pelletPos) ? Vector3.Distance(pelletPos, koiTransform.position) : swimPointRange, Vector3.zero, out RaycastHit info, 0f) ? info.distance : pellet ? Vector3.Distance(pelletPos, koiTransform.position) : swimPointRange;
do
{
Vector3 offset = new Vector3(range, range, range);
swimPoint = pellet && waterVol.bounds.Contains(pelletPos) ? pelletPos : koiTransform.position + offset;
}
while (!waterVol.bounds.Contains(swimPoint) && !(pellet ? Vector3.Distance(swimPoint, pelletPos) < Vector3.Distance(koiTransform.position, pelletPos) : false));
swimPointSet = true;
nested ternaries are quite unreadable. id just split this up and cache some of the values then use them when needed. You have 1 line that contains a spherecast, .contains, .distance, another .distance and just other stuff I odnt even know what is for
so do they swim more than needed?
cuz I cannot see the purpose of your code so well
then you make travelRange as a distance
The way this function is supposed to work is it has the fish choose random positions within a specific range.
If no pellet is present, the SphereCast's radius for its travel range is set to its SwimPointRange. If there is a pellet present and is contained within the water collider, the SphereCast's radius is set to the distance between the fish and the pellet.
Next it acquires a point toward which it will swim. If no pellet is present, one is selected randomly from any point within the specified radius. If there is no pellet and the destination point is outside of the water, or there is a pellet and the distance from the fish to the pellet is greater than or equal to the distance from the destination point and the pellet and the destination point is outside of the water, then it selects a new point until those conditions are rendered false. This way the fish stays in the water and only goes toward the pellet.
Somewhat?
It seems they just continue swimming toward that point even after the pellet is destroyed.
And they seem to not be swimming in the right direction.
pellet && waterVol.bounds.Contains(pelletPos)
actually I guess that the issue is that this is false
because the distance should be ok
Vector3.Distance(pelletPos, koiTransform.position)
try to make your code human readable and put some prints I guess ?
I keep forgetting about this since I have very few places where this would actually work. Thanks for this. π
"Data": [
{
"Day": 1,
"Month": 1,
"Year": 2023,
"Money": 0,
"Loan": 0,
"Emi": 0,
"CutDay": 0,
"RawMaterial": 0,
"NumberE": 0,
"MacLock": [ false, true, true ],
"MacP": [ false, false, false ],
"MacE": [ 0, 0, 0 ],
"Product": 0
}
]
}```
this is my json file
{
public int Day;
public int Month;
public int Year;
public int Money;
public int Loan;
public int Emi;
public int CutDay;
public int RawMaterial;
public int NumberE;
public bool[] MacLock;
public bool[] MacP;
public int[] MacE;
public int Product;
}```
this is my c# file
not complete but the important snippet
ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <347e3e2bef8c4deb82c9790c6e198135>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <27a779fc555e412cad6318e4bfb44443>:0)
I am getting this error
i think the issue is
the incorrect data type i used for maclock,macp,mace in my c# file
Is that the complete error (stack trace and all)?
i don't know what stack trace is
Show the complete error
Show the complete error uncut
OK, somehow it's working now.
that's an editor error. are you writing editor code?
no
All I did was do this and now the fish are actually swimming after the pellet is destroyed.
do you have any custom inspectors or assets with editor windows?
so does it work as you expected now?
idts
ALMOST
But progress is still progress. π
well it's not an issue with your code
This doesn't fix them not swimming toward the pellet.
As in, when it's not at (0, 0, 0).
I'll post code related to that later.
well, you haven't mentioned it before, have you fixed this problem?
I had, tho, but I will detail this in a bit.
Also I forgot to mention that for whatever reason, when the fish are swimming toward a pellet, they move rather slow.
Now for code.
Here's where the pellet's position gets assigned and stored:
void Update()
{
Seek();
if (pellet)
{
pelletPos = pellet.transform.position;
}
}
And here's the movement code for the fish:
void Seek()
{
if (swimPointSet && !pellet && pelletPos == swimPoint)
{
swimPointSet = false;
}
if (!swimPointSet)
{
SearchSwimPoint();
}
else
{
Vector3 swimPointDist = transform.position - swimPoint;
float travelMag = swimPointDist.magnitude;
RotateToTarget(swimPoint);
ApproachTarget(swimPoint);
if (travelMag < stopDistance)
{
swimPointSet = false;
}
}
}
void RotateToTarget(Vector3 targetPos)
{
// get vector from us to the target
Vector3 targetDir = targetPos - koiTransform.position;
// get a vector that is somewhere between us and the target direction
Vector3 newDir = Vector3.RotateTowards(koiTransform.forward, targetDir, followSpeed * Time.deltaTime, 0.0f);
// build new rotation based on new_direction
koiTransform.rotation = Quaternion.LookRotation(newDir);
}
void ApproachTarget(Vector3 targetPos)
{
// if distance between us and the object is small enough, stop moving towards it
if (Vector3.Distance(koiTransform.position, targetPos) < stopDistance)
{
return;
}
// adjust our transform so we get closer every frame if applicable
rb.velocity = koiTransform.forward * Time.deltaTime * followSpeed;
}
}
this issue started when i added the bool[] data types
please, use normal site to post this code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
and, again, if you are not writing editor code then the issue is not your code.
sorry
i will keep that in mind
then what is
and how to find it
Clear the logs
ok, so what's the issue?
this?
Also I forgot to mention that for whatever reason, when the fish are swimming toward a pellet, they move rather slow.
Yeah that's one of two.
the 2nd one?
Anyone have ideas on how they are doing this camera move (starts at 0:33 ish) from FPS to focused on keypad? https://youtu.be/LFkBCmwZtYk?si=46e_DpBMy2yOW-6t&t=33
Deus Ex Mankind Divided - A Heated Combination Trophy / Achievement Guide - Enter a classic numerical code in the game's first keypad. [Bronze / 10G]
Mission 1: Black Market Buy
At the very first keypad you find (which is story related and unmissable) you must enter the code "0451". This will open the door and unlock the trophy / achievement.
...
Am I crazy already, or is Unity broken?
for (int i = 0; i < carMeshRenderers.Length; i++)
{
carMeshRenderers[i].materials[carMeshRendererMaterialSlot[i]] = carMaterial;
Debug.Log($"carMat: {carMaterial.name} setMat: {carMeshRenderers[i].materials[carMeshRendererMaterialSlot[i]].name}");
}
I have this in script. As you can see, it should set the specific material for the i-th mesh renderer to carMaterial. Simple stuff.
Although it does not! To exclude the possibility of something else messing it up, I've added the Debug.Log. And what does it show? That carMat and setMat are different materials!
I really doubt there can be anything else changing the material, especially since no other script has access to these mesh renderers, nor the materials used here. What can be wrong here?
this is definitely not the right way to do that
.materials returns a copy of the materials array
modifying that copy will not do anything to the renderer
this is noted in the documentation
you would need to do this:
Material[] mats = carMeshRenderers[i].materials;
mats[carMeshRendererMaterialSlot[i]] = carMaterial;
carMeshRenderers[i].materials = mats;```
it worked just fine before I updated my script. I simply had .material before, and it worked. Unless those two are actually different
they are different
are you sure about that?
yes
I was under the impression it duplicated the materials if this was the first time you accessed it, so that the renderer now has unique materials
.material = and .materials = both work, however you were not even doing that latter one
you only used the getter, which returns a copy
it ALSO does that
but the array it returns is a copy regardless
Oh, I misunderstood.
setting into the returned array does nothing, because you're setting into the copy
I was mixing that up with modifying the array elements, which does work exactly as expected
Oh, it does work. But it's kinda weird that .material returns the material, and .materials[i] returns a copy.
Anyways, thanks a lot for the help!
Now I feel dumb for not looking at the documentation at first. Shame on me
they both return direct references to the material.
The thing that's a copy is the array
There are many things in the Unity API that return arrays and most of them return copies. Mostly this is done because the real collections are in native code, not C#
so it wouldn't be possible to directly return these collections
in fact, most things that look like fields are actually properties
hence why transform.position.x += 1; doesn't work
I guess that makes sense then
so basically, I was just modifying the material that is in some copied array, not the original one, correct? That would explain why it didn't work
No, because that would have worked.
You were assigning an element of the copied array.
renderer.materials[0].color = Color.red;
General pattern for properties of value type or collections:cs var things = ... //things.x = ... //things[...] = ... ... = things
This is completely fine. It makes a new array that has all of the materials in it. You access a material and set one of its members.
It's when you try to assign into that array that it doesn't work
because you just change what the array is holding
yeah, that's what I was thinking. Modifying materials inside the array works, because it's one material in 2 arrays (copied and original).
But if I assign new material to copied array, it doesn't get set to the original one because those are different arrays
i've been coding it now but i'm still kinda lost on what i'm doing
got any examples so i can understand a bit better?
it doesn't look like z fighting, it just random flickers like every 10 seconds
@fringe ridge are you moving them ?
yeah
but its not consistent with the movement
like i move the last panel to the front, but it doesnt happen then, it just happens randomly
oh no, wait, it does corelate with something
when the last panel is moved to the front it flickers
its not because of speed or anything, because of the transition
the way this works is i move the background to the front when it has passed the defined length
try to isolate the part you believe the bug is, and let us see the code
How do I stop a new animation starting until the current one finished using code on animator?
This was the code. I found the problem. I changed the position and it was only applied in the next frame
causing some kind of weird glitch where for a fraction of a second it got stuck inbetween
Kinda of hard to debug without seeing what are you really doing.
Are you swaping sprites between parent and child 1 (the second child) ?
Is this supposed to happen only once after a certain limit ?
Is this limit being resetted after you swap ? Or its constantly checking and swaping every late update.
Why does result of a task cause Inifite Loop / Freezing in Unity?
you mean using await?
presumably because it needs to block to wait for whatever the async task is
you should NEVER block the main thread in an interactive application
otherwise the user experiences "freezing"
public async Task<string> LoadSomeData()
{
Dictionary<string, string> savedData = await CloudSaveService.Instance.Data.LoadAsync(new HashSet<string> { "PlayerSave" });
Debug.Log("Done: " + savedData["PlayerSave"]);
return savedData["PlayerSave"];
}```
//Another script
```cs
[ContextMenu("Load")]
public void LoadData()
{
var jsonData = cloudService.LoadSomeData();
var data = JsonUtility.FromJson<PlayerSaveData>(jsonData.Result);
}```
LoadData for some reason is freezing
yeah when you do this you're basically saing "block ther main thread until the network request is finished"
so that's what it's doing
unfortunately for you the main thread is the thing that renders the game every frame
if it's blocked, it can't do anything else
I'm trying to make a snap function for props in my builder to snap to the side of another object, I do that by using the position of the object we hit + 50% of it's width in the right direction
buildPosition =
hit.transform.position + hit.transform.right *
(buildOrders.item.width * (hit.transform.localScale.x > 0 ? 0.5f : -0.5f));
buildOrders.desiredRotation = hit.transform.eulerAngles;```
This works perfectly for objects that are 0, 90, 180, 270 degrees but other it seems to be incorrect? I tested a 45 degree object and I needed to offset it by 0.0000182 to remove it detecting a collider overlap.
Any suggestions on how I can do this better? I assume there is some floating point accuracy issue here?
wait so am I just missing await ?
no
the await is implied here
and it's the problem
Ahh okk is this why they made an Awaitable class I suppose.
recommend UniTask if you really want to do stuff like this
Oh wait.. I'm dum dum.. I just needed to make LoadData() async and await the function so I don't need .Result..
public async void LoadData()
{
var jsonData = await cloudService.LoadSomeData();
var data = JsonUtility.FromJson<PlayerSaveData>(jsonData);
}``` this worked
unity UGS really forces you to use async with things like async void. cringe
where do you store ur "jsonData"? just out of curiosity
You mean this ? cs public async void SaveSomeData<T>(T incomingData) { var data = new Dictionary<string, object> { { "PlayerSave", incomingData } }; await CloudSaveService.Instance.Data.ForceSaveAsync(data); }
I havent done anything with LoadedData yet cause the .result from Task was fucking me up lol
Im just making a video on Cloud Saving UGS , not really using this in a production product
thought it was neat unity finally added Email/Pass login to authentication package , it actually made it useful now
no i was just curious where do you load it from
oh this one?
#archived-code-general message
no i mean ur CloudSaveService singleton, if thats what it is, where does it take data from
like do you have database for that or what?
yep that was what i was wondering
Ohh its a Unity SDK class
yeah i figured but wasn't sure, thanks
so how do you manage ur login system for that?
is it connected to steam or database or what?
Unity Authentication service is built in the UGS, you can choose whatever platform you want.
it has Anonymous login by default, they finally added Email/Password login though , it was something missing I wanted first before trying this
everything is stored on UGS Dashboard
can you use Players SteamID for it for example?
yeah you can use SteamID
yeah nice , cool
https://docs.unity.com/ugs/en-us/manual/authentication/manual/platform-specific-signin all the ones they support
im curious cuz im soon off to create the login system for my game aswell so just figuring out all the options
OpenID was the only Option for custom logins but its difficult, I'm glad they built their own email/pass . I was missing that from many services like Lootlocker or MongoDB
Oauth comes with too many hells to deal with, so yeah this is easy solution without worrying about security since they take care of it
why not use SteamID though, isn't that like best if ur going to put it on steam?
MongoDB
Am I missing something here? O_O MongoDB was missing custom logins?
No I meant "I miss having that from these services "
sorry my bad wording π
not native
True but its an investment, if u got good game going on why not
You can use the Steam default game to develop too, so you don't need to front the $100
Yes would do this 100% for productions. I'm just making How-Tos. on this UGS feature, up to everyone else how to us it
π
Not sure how that works with Unity's system though, I'm using someone else's
really ? thought any steamwork api access needed "Partner Fee" lol
gotta look into this
Just google Steam Spacewar (app id 480)
I'm using unity's input system and would like to return the players GameObject when they join, I have been googling for about half an hour and cannot find anything lol
Oh i've seen friends play "Spacewar" but i t was probably a uhh "gray area game" using steamworks
So I can just use this for testing? neat.
Is there a way detect when an object is deleted from the scene in edit mode and find out what that object was?
{
GameObject[] gb = GameObject.FindGameObjectsWithTag(tagName);
GameObject gb2 = GameObject.FindGameObjectWithTag(tagName + "Input");
foreach (GameObject g in gb)
{
g.SetActive(isEnable);
if (isActive & g.GetComponent<Button>()!=null)
{
g.SetActive(false);
}
}
gb2.SetActive(isActive);
}```
NullReferenceException: Object reference not set to an instance of an object
Play.EnableDisable (System.String tagName, System.Boolean isEnable, System.Boolean isActive) (at Assets/Scripts/Play.cs:112)
Play.BuyMachine (System.Int32 mid) (at Assets/Scripts/Play.cs:273)
Play.Mac1Button () (at Assets/Scripts/Play.cs:234)
nope you can just fully use it, I paid the fee (cause im gonna do it anyways) and then never linked my build yet still can connect to someone across the world.
Steam just kinda lets u do it, π€·ββοΈ they're rich like that
I must be clicking the wrong things, last time I tried it kept bringing me up to the "become a partner" to access API . its been afew months, I have look again. I would assume they could, or even provide a test API ffs
you could probably find it online but i just use facepunch instead of steamworks. Facepunch is just free online and has its own transport that setups the steam sockets already
so idk specifically about steamworks api
oh right facepunch is the .NET version or something
we can't read line numbers like this
use site !code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Even though it's a GameObject, I can't reference the Player Goal to a prefab that is not in the scene. When I put the prefab into the hierarchy, I can reference it, but in that case, I can't override the prefab, and the "Apply" option remains greyed out.
Start with the top error. line 112
GameObject gb2 = GameObject.FindGameObjectWithTag(tagName + "Input");
Check if gb2 was found
So should I use .find in Start()?
I was mistaken
are you using a spawner for your prefab ?
pass the PlayerGoal from scene object with reference, when you spawn it
avoid Find methods
Yes
right so when you spawn the EnemyX prefab, pass that on Instantiation
Enemy. lol no big deal.. same concept applies
what is spawning Enemy
make that thing hold reference to the Goal in the scene
then pass it when you instantiate , look at the example link I've sent
Thanks! 
I'm not sure if i'm being dumb but that didn't work
What i'm trying to do is, I want enemy balls to aim to my goal post and go for that direction.
@rigid island
public class SpawnManagerX : MonoBehaviour
{
public GameObject enemyPrefab;
public GameObject powerupPrefab;
**public GameObject playerGoal; **
public GameObject player;
private float spawnRangeX = 10;
private float spawnZMin = 15; // set min spawn Z
private float spawnZMax = 25; // set max spawn Z
public int enemyCount;
public int waveCount = 1;
and there's this.
public class EnemyX : MonoBehaviour
{
public float speed;
private Rigidbody enemyRb;
private SpawnManagerX smx;
// Start is called before the first frame update
void Start()
{
enemyRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
// Set enemy direction towards player goal and move there
Vector3 lookDirection = (transform.position - smx.playerGoal.transform.position).normalized;
enemyRb.AddForce(lookDirection * speed * Time.deltaTime);
}```
you should not be calling ADdForce in Update, nor should you use deltaTime with AddForce
Im just doing what unity's junior programmer course said π
typical of unity to do stupid things in their tutorials lol
unfortunately it seems to be espousing some things that are not best practices
they even give you a bugged game and get it fixed
Anything physics related should be called in FixedUpdate()
using AddForce in update isn't strictly wrong
it will be correctly summed up and applied in the next physics update
it will be slightly less consistent then doing it in FixedUpdate
throwing deltaTime in there is just goofy though
I mean it's definitely wrong if it's a continuous force
at 300 fps you will get twice as much force added per physics update as you would at 150 fps
the docs say that AddForce will change velocity by force * DT / mass
it assumes DT is Time.fixedDeltaTime
I'm trying to figure out which way that asumption goes
and always uses that
i'm gonna test this. i'm curious now.
you're right!
π₯
that's very annoying
well, now it's nice and clear-cut
it's mega-wrong to apply continuous forces in Update
rather than just sort-of-wrong
it does become sort-of-wrong if you multiply deltaTime in
then it's just as wrong as putting it in FixedUpdate, I guess
but still a lot less right than doing it in FixedUpdate
Does unity fire any events or actions when an object is deleted while not in play mode?
Youβll get OnDestroy if you put ExecuteAlways to your script
ah, thank you!
okay so I'm really just asking this for my own general knowledge, but certain interfaces are clearly event based. An example is ISerializationCallbackReceiver which has a member OnBeforeSerialize(). When you implement the interface it's clear that under the hood the engine adds all of the classes that implement that interface into a list and invokes the event handler at runtime, but I'm not quite sure syntactically how you'd add them to the delegate
public class SerializationCallbackHost
{
private List<ISerializationCallbackReceiver> _receiverObjects = new();
public delegate void CallbackReceiver();
CallbackReceiver _receiever = new CallbackReceiver();
foreach(ISerializationCallbackReceiver _rec in _receiverObjects)
{
_receiever += _rec.OnBeforeSerialize;
}
}
public interface ISerializationCallbackReceiver
{
public void OnBeforeSerialize();
}
apologies in advance for the horrific code, this is 99% guesswork and I know a lot of this is probably very wrong
that's my best guess at the idea, where am I wrong?
_receiver += _rec.OnBeforeSerialize; ?
You donβt call the method when you turn it into delegate
oops, just a typo
how much of that do you suppose is accurate if any? also, how would the engine collect the implementers of the interface at runtime?
no issue, just conceptually trying to understand
I know collecting interface implementers is simple enough on our end because the hierarchy is a graph, but I don't think that's globally true
well nevermind that might be stupid. It would only make sense that they're all part of the graph
I mean I doubt Unity would need delegate there
https://github.com/Pinkuburu/Unity-Technologies-ui/blob/2a218ade09fc3528ba4b6bf171878b2920683260/UnityEngine.UI/EventSystem/ExecuteEvents.cs#L287
This is how event system does for example
there are no delegates involved. Unity probably just does something like this:
foreach (UnityEngine.Object o in thingsToSerialize) {
if (o is ISerializationCallbackReceiver receiver) {
receiver.OnBeforeSerialize();
}
DoSerialization();
}```
wow, much more elegant than what I had written lmfao
thanks, that explains a lot actually
Good evening,
I'm current writing a voxel game in unity and have been working to get UV's properly affixed to the generated voxels.
After hours of work, I've finally gotten it to a point where it looks decent, but the texture stretching is undesired. I believe it's caused by a misaligned vertex, but I have yet to find where in my code that causes the misalignment.
Do you have any ideas?
My apologies; I've found the solution. The answer was that the order I had assigned the UV's needed to be adjusted.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
is there a way to change the size of a game object in runtime? if possible, not by scaling but something like setting the radius to be 50
Like its mesh or collider or�
uhh it's basically a prefab with a circle collider2d
so you probably want to change this right? https://docs.unity3d.com/ScriptReference/CircleCollider2D-radius.html if you have a reference to the collider in question it should just be a matter of changing the radius value
so, I have a localPosition and a localRotation stored; I want to position my gameObject as if it was the child of another object without SetParent; like if I did the SetParent(transform,false)
I tried:
transform.rotation=parent.rotation*localRotation;
transform.position=parent.TransformPoint(localPosition);
but the values result in a small offset from the actual position if I copy-paste the transform component
My visual studio (2022) does not show errors in the Error list and I dont know why
Is it just position and rotation for an object one time, or is it needing to be constantly updated to have the position/rotation of an object?
constantly updated
you can take a gander at this then, https://docs.unity3d.com/Manual/class-ParentConstraint.html It's a way to have an object follow an object's transform rotation/position without it being parented
hi, i work on my this project. when I jump, the animation works as I want, but when I want to jump again after hitting the ground, sometimes it gets stuck in the jump animation trigger. at the same time, I want the animation to work when falling from a high place. how can I achieve this?
`private bool _isJumpPressed = false;
private bool _isJumping = false;
[Header("Jump Settings")]
[SerializeField] private float speedY;
[SerializeField] private float _gravity = -9.81f;
[SerializeField] private float _jumpForce = 15;
void PlayerMove()
{
if (_isJumpPressed && !_isJumping)
{
_isJumping = true;
_playerAnimator.SetTrigger("Jump");
speedY += _jumpForce;
}
if (!_characterController.isGrounded)
{
speedY += _gravity * Time.deltaTime;
}
else if (speedY < 0 && !_characterController.isGrounded)
{
speedY = 0;
}
_playerAnimator.SetFloat("SpeedY", speedY / _jumpForce);
if (_isJumping && speedY < 0)
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, .1f, LayerMask.GetMask("Default")))
{
_isJumping = false;
_playerAnimator.SetTrigger("Land");
}
}
Vector3 movement = new Vector3(_currentMovement.x, 0, _currentMovement.z).normalized;
Vector3 rotatedMovement = Quaternion.Euler(0,_camera.transform.rotation.eulerAngles.y, 0) * movement;
Vector3 verticalMovement = Vector3.up * speedY;
}`
you need to have this component on the object you want to have updated but aside from that it shouldn't be too bad
oh, thanks, I'll take a look on it! but do you know what could be wrong with my transform mathematics?
but Parent Constraints should be a great alternative for what I was doing; I was creating a complicated Serialized array of values to be applied, so I'll replace it with your suggestion.
hmm for just generally setting position + rotation, what I found to work is
objectToUpdate.transform.position = originalTransform.transform.position;
objectToUpdate.transform.eulerAngles = originalTransform.transform.eulerAngles;
Something like that should work, was looking through my code but I use a slightly different setup since I generally have an offset, but something like this should work fine
Yeah that parent constraint stuff is awesome because another alternative would be during an update/late update method you would typically update the position/rotation but this seems to just take everything needed and update it accordingly I use it for a barrier type setup for a player and it works great!
a little on the learning to know how to set it up but once you get over that hurdle it's great
thank you!
So I guess I'll add this:
You need to add a constraint source like so
GetComponent<ParentConstraint>().AddSource(new ConstraintSource()
{
sourceTransform = playerDataReference.m_PlayerProtectionParent.transform,
weight = 1
});
and I have this on the actual component, the freeze position bit kinda confused me at first but the freeze position basically means it will take whatever position is given from the source (so it's essentially freezing it's own position) so you would do that + rotation if you want it to follow the position/rotation of an object (in this case the source)
oh right and last bit would be to remove the source, I use an object pool so that's where I typically clean up my objects
if (objectToDespawn.TryGetComponent(out ParentConstraint parentConstraintReference))
{
parentConstraintReference.RemoveSource(0);
}
So if that isn't the case for you, I would say something like OnDisable/OnDestroy is where you'd put the clean portion
thanks for the great explanation and examples! I'm already reimplementing the "carrying inventory items" system using your approach :)
Hey no problem! it's a great alternative so I'm happy to share the knowledge I have on it π
does somone know?
wouldn't that be for for a build? if you want to see errors, it'd be better to look at what is shown in the unity console
hmm actually that might not be the case, I can see errors in visual studio, maybe restart visual studio? I know it can be iffy at times
hello, you have to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
sometimes I fix this problem by going to Edit>Preferences...>External Tools and setting the External Script Editor to Visual Studio and then pressing Regenerate project files
but I'm not sure if that's the case with your project
yes, they either have to configure their ide or this script is not the part of their project
Ill try
the second case can appear when changing scripts name in unity, but it is not changed in vs yet
or vise versa ?
wrong tag lol
That worked thanks Arthur and apple
For a online rpg, its obvious that player data such as level, skills, currency, achievements etc are stored in the database. But what is the best practice for storing static data such as, weapon and equipment base stats, monster stats, monster drop tables, quest dialogues, etc? Do I also stored them in the database, as JSON files, or like just hard coded in the scripts?
For the game I worked on, we used an sql database, each table stored various amounts of data basically like you suggested. It definitely worked but you have to create essentially an API that connects the sql database to your game, it's a bit of work but it's definitely doable.
So just store both dynamic and static data in the database
What do you mean by "dynamic" data?
would the static data be the exp table(as an example) , and dynamic anything specific to the player that updates?
dynamic as in data that changes over time such as player exp
static as in ones that doesn't change like weapon base attack
You can store static variables off-machine and on a database or something so you can make easy updates to the game, but dynamic ones don't really need to be stored on a database, just do it locally on the player's machine.
static wouldn't have to be in the sql table, you can just essentially bake that into the client itself, but the dynamic would be what you use the sql table for (at least that's how we did it, you can do both in sql but still requires a bit of effort)
sorta depends on the circumstances, though, because having it stored in an sql database off the machine means that it's harder to alter locally, and doesn't exactly work for an online rpg
Could always encrypt it.
I'm not a network guy but I imagine by making requests to a server you're opening yourself up to attacks like impersonating the server
Then again every system has vulnerabilities so yeah, pick whatever
the way we set it up, was in order to get or send info, you had to essentially get a token from the server itself, the token expires every I think 5-10 mins so it refreshes
there were probably ways to get around it but nothing is perfect
yeah i mean both way works i just wanna know whats like the industry standard before i start implementing it
hmm I didn't setup the sql portion just the bits that connected to the sql server to get and send info, though tbh I wouldn't know how to exactly describe what I did lol it's kinda a lot to put into words
I think a general idea is that for the setup at least on the client end, since there is a lot of deserializing/serializing is to generalize that portion, and also setup data class types that are similar in design to what the data tables are like. Having those two things helped quite a bit when setting up everything needed for sending and reading data.
yeah im not worried about the setup, just wanted to know where is the best place to put data that's never going to change.
Oh for static data I just have it stored in the client, since it never really changes we never had to really change it aside from fixing whatever bugs we found. We essentially had local databases, but more in a sense of a dictionaries of scriptable objects for particular info on things like equipment/item data
It's actually what I do for the game I'm working on now, we have close to 200 attacks for the player, that are stored in a database (but again it's just a dictionary really), I guess the better alternative is to have something be able to parse in an excel/google spreadsheet to update all the different values which I might end up doing in the future if it's necessary (I've read this is a good idea, but I have yet to try it out) so that is something you could look into if you want.
hmm yeah makes sense. only time ill ever change the data is for like balancing.
Scriptable objects are great, we use them to store the animation clip for the attacks, the prefabs that we want to spawn in, along with any transform offsets, and also things like the damage values and such, which if they were split up (the damage portion that is) we could probably just have it use the spread parsing stuff. The great thing though is we can do all the changes to the scriptable object live and we can see the results straight away, which definitely help for things like balancing, and also just prefab positioning
can someone help me? I have a problem that I'm unable to make my player move when I'm trying to call a public class from other script which is the player controller. What I did is I called the play controller into another script and use it for if else game state. I used HandleUpdate on public void to make the function work
I used public enum GameEstate to make sure that the character won't be able to move when the player interacts with NPC
are you able to show your code, so we can see what maybe wrong with it?
Code is much better than words. Also an explanation of what is actually happening compared with expectations and what debugging steps you've taken thus far.
Is it wise(advised) to store data that will be used across scenes by some gameManager in a scriptableObject
Is it impossible to do within 1 condition?
if ((ItemController item = hitTransform.GetComponent<ItemController>()) != null)
if(hitTransform.TryGetComponent(out ItemController itemController))
TryGetComponent returns a bool
oh, completely forgot about this one, thank you
Yep no prob!
otherwise
if (hitTransform.GetComponent<ItemController>() is var item)
I see, thank you too π
you're welcome π
it'll come handy in other comparisons -- but for Components TryGetComponent is recommended
actually I've just realised that I don't need'em, cuz I just have to compare getcomponents
but now I know how to get them
using GetComponent isn't good practice in general -- except when in collisions/physics
it's a pity that normal transform is ItemController item doesn't work
why?
is using is better than say .Equals?
I actually don't have another option
they are not the same
you can override Equals
so its kinda different for every class and struct
mainly because you got better options π
is is another
architecturally speaking
Is there a way I can sync a game object's movement to a bone on my model during an animation?
if (component is Behaviour behaviour and not Collider2D)
{
behaviour.enabled = value;
}
huh okay, I've never actually used is before
not always
Isn't that just apply root motion?
almost always, but yeah
I have a Transform item, but I still have to access its ItemController and ActivatedItem components
hmm in proper OOP you'd have InventoryController that references each of those
haven't ever heard about that
Wouldn't that move my character about the screen?
I have something similar to that, my inventory controller would hold references to each inventory slot, and what is in each inventory slot
Are you trying to do something like, have an object for instance say you have a sword on your character's back, move with the character while they are animated?
because that I guess would be different
I'm trying to have my character do a pickup animation and tween an items size from a bone moving with the character
As if the animation and bones were gameobjects and the item is just a child of one of the game objects (a bone)
If that makes any sense
hmm, I feel like I could probably figure out what you mean but it might be better if I saw a vid of it or something lol
is there some sort of example from another game you could show?
about OOP? π
I'm not at my computer right now, but imagine just one bone standing perfectly straight.
Theres a base component and a head component. Now, rotate the bone forward. The head should now have moved. I want a gameobject to move with the head
Hmm nothing comes to mind, I could try think of a solution in the morning though, might be able to think up a way to do it (would still be better with an example or vid though)
Hi i am wanting to make my car game multiplayer and i want to use PUN 2 but idk how
start by following the guides on their website
Im trying to upload a build to Meta Developer portal, and its telling me that since june 30th, api must now be minimum of 32, but I dont know how to get this on the editor? in the settings i can try select it but it doesnt have a name like the others, just "API Level 32".... ??? I have never had this problem when working with it before.
Am i missing an update to the Android SDK? I searched the editor modules and it only says that theyre installed. so is there anyway to force an update?
but I would recommend against PUN2
it's quite old / outdated at this point
and missing capabilities
then what would you use then? BTW i have a budget of 0$
Photon Fusion is where it's at, so much better imo
Photon Fusion or Unity's NCFGO is newer/better
crazy budget
I have the exact same budget lol
I am a student and i have game design
you dont need to spend anything :p
https://doc.photonengine.com/fusion/current/getting-started/fusion-intro this is an intro to fusion and here is a kart multiplayer game you can use as an example https://doc.photonengine.com/fusion/current/game-samples/fusion-karts
anyone active here right now got any knowledge of this?
money is only needed if you want to make it into a bigger multiplayer game anyways, can just use the basic setup if you just need to make something like a game for studies or even for a game jam
i remember api level of android is somewhere in project settings->player->other setting with target platform is android
jsut search for api in project settings
I will take a look at this thanks
Hey so, I am trying to make a random contient generate, I am kinda new to procedural generation
Basically what I have now is perlin noise combined with fallof map.
What should I do if I wanted to have more organic shape?
(ping if you respond) (my code knowledge is medium) (my unity knowledge is somewhere between beginner and medium)
You could mix it with different sizes of perlin noises
Like throwing in a layer that is ~4x the current noise scale would help already
Play around with min/max, multiplication and other ways to blend the noises
thanks for the tip
Hi, I am working on a rhythm game and I want to procedurally find the beat ( Drum or Bass) according to the melody of the music, but I couldn't do that. I can now find bpm, beat interval also the peak of the music using spectrum data. can someone help me ?
is there a method that doesnβt need to be called on that will still you know do stuff, i want to have a separate method with all my if statements that run if a key is pressed so i donβt have update all junked up
make a method
call the method in Update
ig that would work
Or use the input system and events since that's what it sounds like you want
hello, im trying to make a turnbased combat system but i got int osome questions. Im making a turn manager that setup all the turns and initatives, but i want to make events happens if the characters have different skills or effects
for example
i have a character that always at the start of the its turn he receives 50% of his hp as a shield
other character receives 100% crit cahcne if its hp is full
this 2 triggers happens on the turn manager "turn start"
there is a way to make a method "subscribe" to this evetns?
For that kind of things, you could use C# events.
Each skill would subscribe to the relevant events when turned on (and unsubscribe when turned off)
alternatively, you could add methods to your skills like "OnTurnStart"
then just loop over all of your skills and run the methods when appropriate
hmm bit im going to need to grab all the skills and check if hte onturnstart exist in all of them
- the other effects
i will check the event thing
thx a a lot
Has anyone seen this error:
βSaving has no effect. Your class βUnityEditor.XR.Simulation.XREnvironmentViewManagerβ is missing the FilePathAttribute. Use this attribute to specify where to save your ScriptableSingleton.
Only call Save() and use this attribute if you want your state to survive between sessions of Unity.
UnityEditor.XR.Simulation.XREnvironmentViewManager:OnDisable () (at ./Library/PackageCache/com.unity.xr.arfoundation@5.0.7/Editor/Simulation/XREnvironmentViewManager.cs:169)"
Any suggestions on how to resolve, or possibly how to suppress it?
It's coming from the ARFoundation package 5.0.7. I tried 5.0.5 as well but same thing. It's just an editor script that throws this at runtime
Hi everyone. I'm working on a marching cubes voxel terrain in Unity and I'm running into issues trying to "dig" into it. My setup includes a MeshGenerator class and a DensityGenerator class that uses noise for the terrain. I'm trying to modify the density values to dig holes into the terrain but it's not working as expected.
- I've tried to use a Dig method to change the density at a specific point and regenerate the mesh.
- I'm using raycasting and I've also added debug spheres just to check if the raycast hits the terrain, and it does hit but no digging happens. The digging is supposed to happen where the raycasting hits.
I've added a few debug logs which you can see them in the screenshot. I have no idea where the issue lies. I'm also using a few compute shaders but haven't modified anything in there, the digging related code is in my scripts.
Are those the same?
Input.GetKeyDown(KeyCode.LeftAlt | KeyCode.RightAlt)
Input.GetKeyDown(KeyCode.LeftAlt) || Input.GetKeyDown(KeyCode.RightAlt)
hey, I'm new to the discord. Is there anywhere i can ask for help with C# scripts?
in #π»βcode-beginner if it's about unity
ok, its just i cant find any guides for a swipe movement system
have you tried to google it?
its a golf game, but i want the touch input to be when touching the golf ball
yes, ive googled it, but only found guides for 3d fps
No, the first one is not correct, and will probably detect another key that corresponds to LeftAlt | RightAlt numerically
I see, is there any way I can make it shorter
Nope, that's as compact as you can get
I see, thank you π
This kind of thing works when the enum is explicitly designed to work as "flags"
this is not one of those cases
I dunno if there's an easy way to check if that's true.
(KeyCode.A | KeyCode.B).ToString() - if it returns "A, B" then it's flags. If it returns a number or a completely unrelated key, it's not flags
oh yeah, that'll indicate it
https://github.com/Unity-Technologies/UnityCsReference/blob/0aa4923aa67e701940c22821c137c8d0184159b2/Runtime/Export/Input/KeyCode.cs#L13
KeyCode does not have the Flag attribute
Haha, doing the "short" but invalid way will poll inputs for the LeftWindows key, which is deprecated
secret achievement unlocked
I can also make a custom method for this stuff though
public static bool GetKey(KeyCode key1, KeyCode key2) =>
Input.GetKey(key1) || Input.GetKey(key2);
indeed. i was about to say "you could use a params argument", but that makes garbage every time you call the method
public static bool GetKeys(params KeyCode[] keys)
{
foreach(var key in keys)
if(!Input.GetKey(key))
return false;
return true;
}
supports unlimited number of keys, but yeah creates garbage like fen said
I guess I'd just implement a few of them
actually, how does overloading work if there's a params version of the method?
okay, it takes the non-params one
I believe it attempts to resolve the exact signature first
If all else fails, params
why does it create garbage?
performance?
it makes an array
it allocates a new array each time you call it
i discovered this when using LayerMask.GetMask in a very hot part of my code
(Did you know you can pass an array directly to the params argument and it won't complain?)
it's all syntactic sugar, isn't it
I see, and is this a huge impact on performance?
a lot of garbage collection can cause hangs/frame rate issues
I see
yeah, you get hitches as the garbage collector runs
how should I name these different methods?
public static bool GetKey(KeyCode key1, KeyCode key2) =>
Input.GetKey(key1) || Input.GetKey(key2);
public static bool GetKey(KeyCode key1, KeyCode key2) =>
Input.GetKey(key1) && Input.GetKey(key2);
oh, GetAnyKey and GetAllKey ?
Yup to be consistent with the names Input already provides
I see, thank you π
Apologies if this is the wrong chat but I tried putting my project GitHub and when I cloned it back to make sure it works I got a lot of errors. I used gitignore but added an extra line to ignore zip files. Is there something I'm missing? Thanks in advance
it should just work, did you use the git ignore for unity? What errors are you getting as well, maybe some of your files didnt upload if they were too large like big assets
It's this link right? https://github.com/github/gitignore/blob/main/Unity.gitignore
I put that in my project folder before sending it to GitHub. Of course I renamed to .gitignore
hm, one of those errors where a package can't see a name.
so the Library folder is not included in the repository, correct?
Yeah no library
what do you mean you cannot access events?
those events are static, you access them directly through the class rather than through an instance of the class
im trying to make a messa appear on hte on tuurn start on oteh exterior gameobject
so it's just turnbasedUnit.onTurnStart += <whatever>
(do you actually want static events?)
yeah but it dont appear as a event on my fiel for soem reason
also you should consider naming your classes with PascalCase rather than camelCase to align with standard naming conventions for c#
again, it's not an instance member. since it is static you access it directly through the class rather than an instance of the class
perhaps the guide is talking about a situation where it makes sense to be static
See the dots here? That means your class isn't named correctly, it should be TurnBasedUnit so you know it's a class at a glance.
Same for the two events there, they need to be renamed
i see
i will solve that
and yeah the static stuff was teh rpoblem
yap worked fine
Figured out the solution was to update from editor version 2021.3.16f1 to 2022.3.5f1.
Is there a way I can record the best performance of my agent during the training process? (Unity ml.agents)
Im making a script that generates different objects with different values. so I made a struct that holds the values for the different objects. but I dont know how to make a for loop that loops and increments for each index of the struct. I thought maybe i could do this for (int resource = 0; resource < Resources.length; resource++) but that doesnt work.
here is the struct
What do you mean by "increments for each index of the struct"?
for each element in the struct. it starts at zero so i called it an index
ok back up here
this is an element in an array containing this struct
an array or a list
oh, sorry.
you have either:
Resources[] myResources;
// or
List<Resources> myResources;``` right?
that's very important information
ok perfect
so if you want to iterate over those you can do either of these:
for (int i = 0; i < resources.Length; i++) {
Resources r = resources[i];
Debug.Log(r.name); // for example
}```
```cs
foreach (Resources r in resources) {
Debug.Log(r.name); // for example
}```
so to be clear on the terminology here:
You've defined a struct called "Resources". And you have an array of Resources structs. The array of structs is called "resources".
which is more efficient?
or are they pretty much the same?
Technically the foreach is slightly slower but it's so close as to not be worth worrying about at least at this point in your journey.
the for one is useful mostly when your code needs to know the index i for some logic inside the loop
Alright, thank you so much.
I have a new problem, I cant figure out how to get these trees not to spawn so close to eachother. right now im shooting a raycast from a random point in the sky towards the ground and spawning the prefab at the hit.point. but the trees are spawning to close together. how can i fix this?
well its random, so they've randomly spawned close together. You can run it again for different results. Also you can add in some minimum spacing while storing the location of spawned trees or instead define spawn points like one for the blue area and one for the red area, then have both areas randomly spawn trees inside their area
How could I apply a minimum spacing?
You might be looking for something more like poisson disk sampling?
there'd be a few ways, one would be storing all the locations previously placed then making sure none are too close to any in the list. If you're doing this on like 1000s of objects, you might have noticeable lag.
Another way I could think of would be define some grid where you will check to possibly place a tree at each location in this grid. For each position randomly decide if it should place a tree
Theres probably better ways online but this is the first thing I thought of π€·ββοΈ
I have a question for IAP.
I succeed init product to fakestore and be able to buy it , but all product is in 1 tab(their are many product type: gold packs, diamond packs, misc).
And how can i classify them by type(gold, diamond, misc) so i can separate them into many tabs.
are you asking about code. wdym types?
Yup it's about code.
There are many packs
gold(100)
gold(200)
Diamond(100)
Diamond(200)
I want to classify them instead of load all product.
?
I could classify by using
product.metadata.localizedTitle.Contains(string type)
But i wonder if there is better way.
@rigid island
hmm yea I'm not sure I haven't really used IAP
Ok thank you.
Hey, just wanted a second opinion on this, for a loot drop system, should I make all the items part of an object pool, or just instantiate them? Large amounts of ammo, money and health are expected to spawn throughout the game, so I figured an object pool would be best, but I'm not 100% sure
also, is there a way for multiple objects to share the same pool?
Bingo. That's a great way to get a bunch of points that are at least a certain distance apart
there's at least one nice C# implementation I've acquired before
Hello everyone, I'm working on a hyper-casual tycoon park game and I'm looking for advice on how to structure my code efficiently to keep it clean and maintainable. Are there any design patterns or best practices that you recommend for organizing code in tycoon park games
except from solid principles
there is a platform that responsible of spawning attractions based on player balance and can be used to upgrade the attraction also a platform can be used to spawn a worker
platform is the blue square in the picture can have many commands let's say List<ICommand>
I'm following this thing to do that, and I've gotten an error.
PoissonDiscSampling.GeneratePoints (System.Single radius, UnityEngine.Vector2 sampleRegionSize, System.Int32 numSamplesBeforeRejection) (at Assets/Scripts/ProceduralObjectPlacement/PoissonDiscSampling.cs:31)
Test.OnValidate () (at Assets/Scripts/ProceduralObjectPlacement/Test.cs:16)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)```
here is line 32
here is line 16 of test
you will need to share the code you are using
I think I recognize it, but I'm not sure
PoissonDiscSampling: https://hastebin.com/share/ujazidiwex.java
Test: https://hastebin.com/share/mucorizuca.csharp
Hello I am using Unity Gaming Services Economy and more specifically the inventory system. I am trying to get custom data from the inventory items but it doesn't work it just returns null.(code:
[code=CSharp]var inventoryResult = EconomyService.Instance.Configuration.GetInventoryItems();
foreach (var item in inventoryResult)
{
var data = JsonConvert.DeserializeObject(item.CustomDataDeserializable.GetAsString());
Debug.Log(data);
}[/code])
I have checked if it was getting the object and it was. I didn't seem to find how to get custom data on the docs and had to rely on just description in the ide and some forums with limited info. Personally I find it baffling that unity doesn't document a important part of their service. Any help would be greatly appreciated.
Surely it should be / (cellSize - 1) if cellSize is the size of the grid.
Either way, seems like an issue with this implementation, or perhaps you've passed in parameters this implementation doesn't like that it doesn't filter against
it works now. but now i need to convert it to positions within a radius.
Think I might be misunderstanding structs,
I have a EventInfo struct which contains a UnityEngine.Object variable,
I have an Array of EventInfo's that I'm looping through where I'm trying to get that UnityEngine.Object
When I debug log this object, it's totally what im expecting it to be, But when I try and add it to my list or direct variable it's just not happening, Like it's somehow only a reference that is dying at the end of my function?
I'm running this code in editor
foreach (EventInfo eventInfo in interactionSuccessEvent.EventInfos)
{
Debug.Log(eventInfo.parameterObject is ItemData);
if (eventInfo.parameterObject is ItemData)
{
ItemData Item = (ItemData)eventInfo.parameterObject;
Debug.Log(Item);
trackingItems.Add(Item);
myItem = Item;
myLoot = (LootData)eventInfo.parameterObject;
}
}
Item is Debug.logging completely fine but trackingItems, myItem and myLoot are just not retaining the value
There's a few moving parts in this so please let me know if I need to provide additional context
[System.Serializable]
public struct EventInfo
{
[SerializeField] public enum Mode { Defined, Void, Object, Int, Float, String, Bool }
[SerializeField] public Mode parameterType;
[SerializeField] public string className;
[SerializeField] public string functionName;
public UnityEngine.Object parameterObject;
snippet of my struct
what are the scopes of these three variables?
i.e. where are they declared?
you should share the entire script
Theres like 4 scripts going on here haha
EnhancedEvent : UnityEvent
contains the EventInfo struct and the stored array of EventInfo's
Interaction : MonoBehaviour
contains a EnhancedEvent and that is running the foreach code (interactionSuccessEvent is the EnhancedEvent)
this is the EnhancedEvent cs (all those TryGetParameters are unused at the moment)
https://hastebin.com/share/necilamupo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
my first question is why public List<EventInfo> EventInfos => new List<EventInfo>(eventInfo);
you're allocating a new List every time you access that property
I knew someone was gonna hit me with that haha, Was just playing with shit my bad. Can confirm directly referencing the array does not resolve the problem
okay, are you going to share the class that fen asked you to?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
might wanna double check that link
my public variables are declared up top, I use AddEnhancedEventListeners button to run RefreshEventInfo. everything else in the script is unrelated
are you getting any exceptions? or is it just not behaving the way you expect it to?
No exceptions, The publicly exposed variables just aren't being set. Or atleast visably, Ill debug log them directly just incase it's a serialization issue
How can i pick a random value in a list?
are you looking at the right object?
get random integer between 0 and end of list. access list at that index. that's it.
Verify by doing Debug.Log("whatever", gameObject)
clicking the log entry will take you to gameObject in the hierarchy
I was wondering if I could get a hand on static functions, I have a static class called calculator with has a bunch of different math functions in it for a custom data type. These functions have inputs which i used through the function but I always thought these function inputs were in variables but are they pointers?
Yup, they are all really null.
if (eventInfo.parameterObject is ItemData)
{
ItemData Item = (ItemData)eventInfo.parameterObject;
Debug.Log(Item);
trackingItems.Add(Item);
myItem = Item;
myLoot = (LootData)eventInfo.parameterObject;
}
Item Debug.Log's completely fine, No errors are thrown when I try to set it in this if statement but it's like they all die as soon as this finishes running
Can confirm it's the right object
btw what version of unity are you using?
the list is of type vector2, how can i access the values of the Vector2's within the list?
2021.3.6f1
That's why I was wondering if somehow I'm only getting a reference and not a real value or something odd
do you not know what indexing a list does...?
what part specifically are you having trouble with? because there's nothing special you need to do here
it gives you the element at that index
you now have a Vector2
are you asking about modifying the x and y values?
For additional context the data inside EventInfo is being set via a custom property drawer but in theory that shouldn't matter?
okay so this isn't going to fix your issue, but it will clean your code up a bit: you can actually perform your cast in the same line you do the type check.
so instead of every if statement where you do if(eventInfo.parameterObject is ItemData) then immediately perform a cast into a local variable on the next line you can just do if(eventInfo.parametersObject is ItemData item) and it will not only do the type check but then it will also cast to the ItemData type and store the result of that cast in the item local variable
oh ok cool
How do i get a random vector2 within the list. sorry, im quite confused.
don't you have to tell unity that you've messed with the serialized property afterwards
or is that for custom editors
bro what. you use the random number to index the list
pick a random number. index the list with the random number.
you know how to access a list at a given index, right?
..no
otherwise it doesn't know you actually did anything
then just say that instead of leading us on a wild goose chase
I'm just getting the value though, not changing it. and when I debuglog it in the above code it's totally the right thing
I'm new to lists and arrays. sorry
there are beginner c# courses pinned in #π»βcode-beginner that will go over how to use arrays and other collections
foreach (EventInfo eventInfo in interactionSuccessEvent.eventInfo)
{
if (eventInfo.parameterObject is ItemData newItemData)
{
Debug.Log(newItemData);
trackingItems.Add(newItemData);
Debug.Log(trackingItems.Count);
Debug.Log(trackingItems[0]);
myItem = newItemData;
myLoot = (LootData)newItemData;
}
}
running this gives me this
I know how to use arrays, just not in this context. I've already taken a beginner course. i figured it out.
and then running this right after gives me this
public void DebugLogValues()
{
Debug.Log(trackingItems.Count);
Debug.Log(myItem);
Debug.Log(myLoot);
}
how did you confirm that you are actually looking at the correct object?
Debug.Log($"State of {name} ({GetInstanceID()}): list count {trackingItems.Count}, item: {myItem}, loot {myLoot}");
replace both sets of your Debug.Log calls with this line and show what it prints
The data that is being debug logged as well as the buttons I need to press in order to run the functions
will do
there's two whole seconds between those logs. are you certain nothing else is changing those values in that time?
also it looks like the myItem and myLoot variables were null at the time you logged the first one. did you make sure to call that after assigning them rather than before?
I run the DebugLogValues() after my other function and still retains the values, should I test the exact frame after?
I am not certain but if something else is changing them I am not aware of it
trackingItems, MyItems, MyLoot etc. were written like within the hour and it's not being touched by any other code
gonna be honest, i have no idea what might be causing your issue at this point. i'm certainly not going to try and read through 400+ lines to figure out what might be overwriting those values. and if you have a custom inspector involved, there's also a decent chance that something you've done in that is causing the issue
That's totally fair homie. It is kinda weird though right?
Trying to recreate this mechanic... https://youtu.be/LFkBCmwZtYk?si=46e_DpBMy2yOW-6t&t=33 starts about 0:33, not getting any errors, but also not getting the camera to move either... https://pastebin.com/EVGWK5Ex
Deus Ex Mankind Divided - A Heated Combination Trophy / Achievement Guide - Enter a classic numerical code in the game's first keypad. [Bronze / 10G]
Mission 1: Black Market Buy
At the very first keypad you find (which is story related and unmissable) you must enter the code "0451". This will open the door and unlock the trophy / achievement.
...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
how can I move this square to follow my gameObject, the square is using values from a grid array. The grid always starts at 0 even when i move my gameobject.
why not just use cinemachine ?
you don't need any of this, just 2 cameras nd ur done it blends them nicely for you
seriously?
fr
This is a demonstration of Unity Scene showing different cameras blending using Cinemachine and a simple script used for user interface for blending.
Damn man
i asked on 3 different servers how they thought the best way to make that camera move and no body said a word so I figured I'd just build it my way
To be fair, I was half way there ;P
cinemachine is godsent
saves soo much code and headaches
https://x.com/DeveloperHarris/status/1701783041901985794?s=20
I use gameObject.setActive(false) and setActive(true) to remove the character while they're sleeping but the sprite changes for some reason, and I can't see anything that would reset my character hair sprite back to the preset default. Why?
my agents finally learning that good sleep literally makes you a changed man
show !code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
i'm gonna use it, but I kinda want to finish mine at some point
and the Character class as well
i don't see anything in here that would cause the sprite to change. at least not anything obvious that would. have you checked your animator to make sure that isn't somehow causing it?
also this Entity class you have doesn't derive from MonoBehaviour, does it? π€
because if it does, you shouldn't be using a constructor on it
@somber nacelle It's something to do with where I'm calling the event. When RefreshEventInfo() is called from that context it seems like it's only getting a reference to that data but if i can it on a button or ondrawgizmos etc. it works fine
I'm guessing I'm misunderstanding an aspect of serialization
it does π
need to go back and refactor, but in regards to constructors what should I avoid? just not use them at all?
then you definitely shouldn't be instantiating it with a parameterized constructor. best not to use them at all with MonoBehaviours
i don't think I'm instantiating any
tbh i don't know why i have the constructor, I originally thought unity called that
but i learned unity doesn't do that
by instantiating i am referring to creating an instance, not just using Object.Instantiate
it can only call a parameterless ctor. it will never call a parameterized ctor
oh i think i know my issue
you're gonna hate it
i have every single animation for the hair in a single animator that i switch between by calling my PlayAnimation function
lol yeah that'll do it then
my guess is that when it re-enables it goes back to the default, and since it's already in idle it doesn't switch to the correct hair type
need to refactor that at some point
i just am not sure how to handle animating different parts of a character that need to swap out for example
so like the base and tool animations will be the same so they have their own clean animator
but the hair will all swap
This is math stuff. This square is always offset to where the gameobject is in the corner of it, how can I make this square always centered on the gameobject? This is what i tried, size = regionSize + new Vector2(transform.position.x, transform.position.z);I cant use negative numbers because it throws me an error. cause you cant have negative numbers for arrays for some reason. So what can I do?
Does anyone know how I can Determine the selected "Lightmap Encoding" for the current build target. I've dug through all the docs on the PlayerSettings class (which seems like it ought to be the right place). I've also looked through the LightingSettings class which has a lightmapCompression property, but that doesn't seem to correspond to the Player Settings field.
any particular reason you need to change that setting via script? or is this for editor tooling?
I don't need to change it, I just need to detect it. Yes, it's for an editor tool. My editor tool fiddles around with the lightmap after it's baked, but I need it to use the correct encoding when it overwrites the pixels.
I tried that. The value set in Player Settings doesn't seem to change this value.
oh wait, this is for android
https://docs.unity3d.com/Manual/Lightmaps-TechnicalInformation.html#:~:text=Player Settings.-,[2],-The texture compression
The texture compression format used for lightmaps on Android depends on Player Settings and Build Settings. See Texture compression settings for more details on how these settings interact.
How can I secure my game server by only accepting connections for authenticated clients? I need help with the authentication part, not the connection approval part. I'm using Azure Active Directory to manage client identities and my game servers have sensitive customer data, so I only want to allow clients from the Azure AD tenant as able to connect to the game server
I was reading about access tokens, but how do I prevent man in the middle attacks? It doesn't seem recommended to send access tokens over the connection to the game server
Yeah, that looks like the right thing. In all those docs, though, I still don't see how to access it through script.
Thanks for the help. I might just have to add a public variable and manage it manually.
That's where public/private(ssl/tls protocols?) keys come into play. Https implements them by default, so it should just be enough to use https.
Anyways that's not really a question related to unity.
I am trying to set it up so that where if a building's x coordinate is right next to another building, it sets active to true, but this isnt working
do i need to for loop somehow?
don't compare floats with ==
or is it int?
its an int
im just trying to compare these 2 building's and set it to true when they are next to each other on the x axis
just cant seem to figure out the for loop for it i believe
are you debugging the values to see if they should match ?
How would I do that with something like netcode for gameobjects or fishnet? I'm not sure how the initial connection is made, but I imagine I'd need to send the access token to the server via their transports. Unity for example explicitly states that their transport isn't encrypted
It depends on what transport layer they're using, but usually it would already be implemented by default.
they arent matching, because both building.data.x's are being set to the same value
idk how to not have that happen
What if it isn't supported?
I need to look more, but this implies that I can't just send an access token via the Unity transport for connection approval
Just wondering how else I could have the server authenticate the pending client connection for either approval or denial
do you have a tilemap or custom grid?
when do you call these methods, bit of context would help
Hmm... looks like it.
I wouldn't send sensitive data like that via the netcode anyway.
But if you do want, it seems like you can encrypt the connection. They have it explained in the unity transport documentation under "best practices".
You have a link to that?
Either way, I'm not knowledgeable enough in that area to provide proper guidance. At the very least, try asking in #archived-networking
Google unity transport docs.
I was going to ask this is code begginner but some ppl are talking in there and i didnt wanna interupt, Could someone please explain what this might mean please?
for context, i built the game and installed onto my phone, and was using android studio to read the logcat, where a intistitial ad is supposed to appear the game freezes and the logcats displays this message
you might have put the object in the wrong instance layer
registers it as something invisible or that is not yet supposed to be rendered maybe
it would be reffering to my adsmanager prefab?
also do you mean the layer in the inspector?
that's not at all what null reference exception means
oh ill have a look π
I'm trying to implement an interface
{
public void Strike() { }
public void Destroy() { }
}
I havent implemented its methods in my class but theres no errors, why?
public class Tree : MonoBehaviour, IDestroyable
{
private void Start()
{
}
}
is your IDE configured
Im surprised there are no errors on your interface. I don't think it should have curly braces.
yeah it is, i think so atleast
new c# can have default methods iirc
on the methods?
OHH
you've given the methods on the interface bodies which makes them default interface methods
well then that's whats going on. There are no errors because it's using the defaults
had to remove the braces, fixed it π
yeah took me a minute to remember thats part of new c#
I strongly disagree with that choice. if there are default methods in interfaces, then what's the difference between an interface and an abstract class?
lol at this point it's barely even new. it's a c# 8 feature which is like 4 years old now
yeah i should say for new-ish unity*
ah yeah, fair enough lol
interfaces cant have private methods can they
the same difference lol the fact you can use multiple interfaces on one class but can't inherit multiple abstracts
i know that default interface methods can be private, though i'm not sure if that was a feature added in a version that unity supports and i don't have unity or vs open at the moment to double check
hmm
ah looks like it was added at the same time default interface methods were so should be supported
I see. I can look this up in my own time (it seems I'm a little behind the curve on this), but if I implement multiple interfaces that have default methods with matching signatures, how does the compiler know which default to use?
so i have IStrikable, i'd like to use it on tree and rock for now. I thought id have Strike() and Destroy() in it, but now that i think about it, destroy can just be a private method in the tree (for eg) directly beacuse its just goint to be called from strike anyways
Class (abstract or not) can have actual data (class fields and whatnot) whereas interfaces cannot - they only request that whoever interfaces them promise to implement (any non implemented) method.
Does it make sense to just get rid of Destroy from the interface?
because it doesnt let me to make it private directly, needs me to give it a body
if it should not be called by outside objects then yeah remove it from the interface. unless your interface includes any properties the method may access, then you can just add the default implementation
its just going to be called internally, so i guess ill get rid of it
Is using interfaces with only one method in them normal?
Also a good point. I guess I should try the default methods before knocking them, it just seems to go against the paradigm to me.
yeah not really anything wrong with that if that's the only thing that makes sense to be on the interface
Thank you π
You mean like this ?
public class Player : MonoBehaviour, IBeans, IPotatoes
{
private void Start()
{
SayHello("nav");
}
public void SayHello(string name)
{
Debug.Log("Which One Am I?" + name);
}
}
public interface IBeans
{
public void SayHello(string name) { Debug.Log("HelloFrom Beans" + name); }
}
public interface IPotatoes
{
public void SayHello(string name) { Debug.Log("Hello from Potatoes" + name); }
}```
Exactly
good Q, curious myself.. haha let me try
it will log the Which One Am I one
yup
with default implementations you can only call those methods on objects specifically of the interface type. so you'd have to cast your class to the interface to use the default methods on the interface.
that's my biggest gripe with them tbh, kind of annoying to use the methods within the object that implements the interface
wait, no, not like that. Take out the SayHello method in the Player class, so that it has to use one of the defaults.
but defaults dont enforce the method
then it would be a compile error since you have to cast to the specific interface you want to call the default implementation from within the class
so you would have to do something like (this as IBeans).SayHello("whatever");
NOW I GET IT!!!
Wow. I did not either
wait that does nothing
Oh lol
you can also explicitly implement the methods on the class using public void IBeans.SayHello(string name) { //different implementation here }
ah ok I think i've seen this one before
you can't use public tho right?
ah, right yeah gotta omit the access modifier
niice. I pesonally may not use this ever but kinda nice to have
Youβll have to use it when you are implementing own IEnumerable<T> for example
so basically soon lol IEnumerable is kewl
think when i was using entity framework i ran into this but was so long ago i forget
how might someone assign a tile via code in this context?
I need to be able to call the tiles I have in the project by name in some way
without making a public variable for it since that will become increasingly tedious over time
for clarity I just want to call the tile type, not a specific tile in a tilemap
Does anyone have a suggestion for how to build an infinite scrolling menu? Meaning if i scroll past an item it appears on the other end
Unity has an alright scrolling tool for the UI, which you can normalize a set of elements from 0 to 1, but depending on your design you may just want to craft it yourself.
can any tell me the syntax to access the animation track of timeline asset so that when the game starts i can have the animator changed for that animation track
can someone help me, i have got a problem. Unity has detected errors in my scripts but there are no errors in my console?
show error
There are none tho
Unity has detected errors in my scripts
but there are no errors in the console
so where do you see this?
hmm so exit safe mode
go to Assets > Reimport All
recently i put my projects into an External Disk is that safe?
Thanks so much
it works thank you
Note that default methods are not directly accessible in the class
You need to cast the type instance to that interface, and then call the method. You can't call it when the type represents an implementing class
Anyone know how to do this?
You should probably ask in #archived-unity-gaming-services, because it seems very specific to that.
Also heres a guide on how to post !code
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Yeah sorry I kinda felt lazy I just copied the question from my unity forums question
The text channel is pretty inactive so it would be a long time for even the simplest of questions I thought trying here to see if I could get a quicker answer
Yeah that's a problem for the more specific channels indeed, but its also a very specific problem you are having. I see you already asked there, so lets hope someone has an answer somewhere then.
having some issues with editor GUI code,,
https://pastebin.com/UWqCbx8y (< EventTriggerEditor)
there is the editor script, this code is for this script (this code is not the issue but it might help with context) https://pastebin.com/njcifNnR (< EventTrigger)
this code is meant to let me setup in a neat GUI a list of commands that will be executed in order of listing. that all works fine with this script here https://pastebin.com/USuejKMc. (< EventHandler, once again for context)
one of the commands is called sendEvent() and it lets a eventTrigger command chain send a list of commands to another EventHandler other than the one it currently is giving commands to, so letting me affect a player to say,, make them speak then also make the follower speak with one eventTrigger
the issue is the GUI code as said in the start. im trying to make the sendEvent GUI a nested ReorderableList just like the main list is, so i can make command chains for the sendEvent and assign them to nestedCommands in this script https://pastebin.com/snit1gBH (< Command) to well,,, send. but with the current GUI code im getting a strange result and dont know how to fix it everything else works fine other than the sendEvent. the issue is its showing a expandable arrow instead of the select dropdown, i also JUST as writing this saw that in editor it says Teleport when the sendEvent command is the selected command, and i havent checked for that yet so dunno if its a dumb mistake for that one issue. i have not tried to fix the spacing just yet so i know thats broken
if you wonder why i dont just make a normal hard coded system, i just want something extremely modular for game dev like an extention to unity
and something a friend of mine can understand to make things happen in game
clicking the arrow labeled target (idk why it says that) does nothing at all other than rotate the arrow
Ngl, i found ReorderableList to be too much of a pain. 
Not a lot of extensive tutorial either, nor is it even documented well. 
what version of the editor are you using
I just avoided ReorderableArray entirely tbh.
2021.3.23f1
okay. the reason i asked was because reorderable lists were a bit broken in very early versions of 2021.3 and caused a display issue similar to the one in your screenshot but it was fixed in like patch 7
might wanna ask in #βοΈβeditor-extensions then π€·ββοΈ
Possible to make something fairly decent without ReorderableArray.
Just using structs and property drawers. 
Granted, the only thing u can't edit is the array itself, stuff like the format or the add/remove element.
if i cant figure out ReorderableLists in this broken context then ill try other ways
just with the nature of the commands being executed in order of how i set them, its not fun when i cant quick drag them around
I kinda confused. Aren't all lists now reorderable by default or is it how you've got it encapsulated remove the attribute from it?
im not sure, im not good with editor code,, i just copied what worked overall inside of case sendEvent with small changes based on what phind said
Well, you can continue developing out your script, but if you find yourself stuck on this, why not just make a list of structs for this part?
and just use the normal list unity has to offer for the gui
hmm,, i guess if only the one command has no reorderable stuff that wouldent be bad
its the main block that matters and that works fine
well ive stayed up 5+ hours too long on this issue, imma pass out.
if anyone has ideas on fixes that would fix the current code with ReorderableLists please @ me!
Can anyone explain why this is happening when trying to input a quaternion value on a script?
No custom editor scripts are set up to modify this
- are you sure that's a quaternion not a vector3? i only see 3 values there not 4
- if it is a quaternion, why are you entering in values manually?
- adding on to 2, if it's a quaternion why are you entering any numbers above 1? quaternions are normalized and do not contain euler angles like that
yeah you're right, didn't know they were normalised. It is a Quaternion but w value not showing, will switch it out to a vector and use euler. Thanks!
Because Euler angles are not unique
Quaternions show in the inspector as euler angles by default
ReorderableLists is an editor class, basically the GUIEditor for arrays.
the three angles are not independent of each other
How could I set the pivot of a gameobject without a parent object? The goal is to specify an offset from the gameobject's natural center that will be the pivot point for rotations
If it's a 3D mesh you must change the mesh itself in Blender and reimport it
if it's a sprite you can change the pivot in the sprite editor
Ooh interesting... it's 2D, but its more of just a game-object that could potentially have any sprite.
Mmm I hadn't thought about how the sprite would effect the pivot tho...
Thanks!:D
You always have the answer @leaden ice
What are you working on at the moment?(:
Hmmm i love custom editor, u think u did well but nope, it broke. 
I am working on a debug system. Each debuggable object implements IDebug, and either directly registers itself with the debug system or gets registered by a parent object.
I'm concerned about memory leaks. My naΓ―ve implementation looked something like this;
private Dictionary<IDebug, bool> debugShown = new();
...
if (debugShown[debuggable]) {
debuggable.ShowDebug();
}
This means that every debuggable object will wind up referenced in that dictionary. Thus, they will never be GC'd.
This sounds like a decent place for "weak references". I see two ways to do this:
- Use a
ConditionalWeakTablefromSystem.Runtime.CompilerServices. https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.conditionalweaktable-2?view=net-7.0&redirectedfrom=MSDN - Use a
WeakReferencefromSystemin a dictionary -- so,Dictionary<WeakReference<IDebug>, bool>
Is this a reasonable plan? Have people had this kind of thing work well in the past?
I've used ConditionalWeakTable for this reason, but had bad experiences with it in IL2CPP builds. Crashes and things not working correctly.
I haven't used WeakReference directly before.
I'm not sure CWT will work properly outside of a compiler
it just falls over and explodes due to a code signing error
I searched the term here and found some people talking about it not actually working right.
WeakReference is a good idea but you will need to periodically prune the dictionary by checking https://learn.microsoft.com/en-us/dotnet/api/system.weakreference.isalive?view=net-7.0#system-weakreference-isalive
Gotcha. That sounds reasonable.
I ended up just using IDisposable.
I was also considering this.
I don't want to have to explicitly dispose these objects, though. There's going to be quite a variety of them -- some will be MonoBehaviours, some will be plain old classes
I also need to store a hierarchy. Normally, non-root debuggables only get drawn if their parent is getting drawn. It looks like this:
foreach (var child in debug.ShowDebug())
{
if (!debugShown.TryGetValue(child, out var shown))
{
debugShown[child] = false;
}
if (debugShown[child] = WantsDebug(child))
{
ShowDebug(child, depth + 1);
}
}
I want to be able to "pin" a debuggable so that it is always drawn. But if an object is pinned and its parent is active, it shouldn't get drawn twice
i guess i could make a list sorted by the depth the child is found at (this is a tree, so the object can't be at multiple depths), store all of the rendered objects in a hash set, and then scan the list for objects that are 1) not in the hash set 2) marked as pinned
i'll play with that. i'm more interested in the weak references right now
also, what a nuisance: WeakReference and WeakReference<T> have completely different sets of methods and properties!
ah, there's an issue: two weak references made from the same reference aren't going to count as the same dictionary key
I presume that's why ConditionalWeakTable exists in the first place.
I already use System.Runtime.CompilerServices elsewhere in my code -- I remember having to go find a DLL so that I could use Unsafe.As for some cursed enum stuff. So I guess it couldn't hurt to use it again...
argh this is cursed
there is a third option: just don't worry about leaking at all
all of this data will die when the scene unloads anyway
and I could really just do a "manual prune" by dumping out the state dictionary into a list of weak references and asking for a garbage collection
if it absolutely mattered
I have a custom spotlight texture that extends the vertices automatically to get the right size. But, it gets frustrum culled when the original sprite (shown by the box size) is offscreen. Is there any way to fix this without reworking the shader?
There's no "update when offscreen" equivalent, is there?
like you have for SkinnedMeshRenderer
You can manually change the Bounds on the renderer to convince Unity not to cull it:
https://docs.unity3d.com/ScriptReference/Renderer-bounds.html
You can override the default bounding box by setting your own world space bounding box. This is mostly useful when the renderer uses a shader that does custom vertex deformations, and the default bounding box is not accurate.
Ah, there it is. I forgot you could just set it!
that's awesome, thank you so much, you've saved me
Is there any major difference between vscode and visual studio for Unity?
VScode = more initial setup headaches and intellicode is broken
VS = superior but more heavy (not lightweight) in size
they're completely different, yes.
Navarone summed it up well
I recommend Rider if you can afford it or if you're a student and can get it free
I want to premake rotations and pick them with a dictionary but im not sure how to do it
var rotation = dictionaryWithRotations[localpos.y]
something like this. but the issue is position Y could be eg. 0.923426. Theres too many possibilities to account for all of them (to make dict keys for all of them)
maybe i could use math inverse lerp or lerp idk
but a number from LERP could also be something long and bizarre like 0.912321
i could round them up to 0.01 but then I would have only 100 (lerp goes from 0 to 1) entries in my dictionary but i need more/a better control over the amount of dict keys
I feel like this is a simple math problem but i cant wrap my head around it
just an animation made by rotating things based on position
is there no formula to turn a position into a rotation?
You could use InverseLerp to turn a range into a value from 0 to 1, then convert that into an integer between 0 and n (exclusive) to index an array
that's roughly what you described here, and it's about as good as it's going to get if you really need to have a lookup table


