#archived-code-general
1 messages · Page 290 of 1
or perhaps you need a ShipStats script
A ScriptableObject is probably a good way to design ship stats in the editor too
Hello!, with unity input system when i press "Z" in my dialogue action map, i have it configured so that it advances dialogue 1 time, evetually it finishes, and when it finishes, it opens the interaction again to the npc im talking to, so pressing Z end dialogue and inmediatly opens it up again, since opening the interaction is on the Z key too. How can i make it so that 1 key press equals 1 action? right now its triggering the action from 2 different action maps since calling it from the dialogue action map calls an event to change the action map to my walking action map (Sorry if its not explained very good, i will clarify if needed)
i have tried a lot of things but nothing seem to work
one solution is wait a frame before enabling the new action map
Another thing I never tried is perhaps unchecking the "initial state check" on the action in the menu
i tried that but the problem is that if i keep the key pressed, it still reopens it, and i hate it
that shouldn't happen unless your code is not handling the action phases properly
mmmm ok i will take a look at it, but no clue where the problem might be in
start with the input handling code for that stuff, as mentioned
never mind adding a 0.1 sec delay worked perfectly, dunno why before didnt, maybe i had something added inside the inputactions when i was testing
thanks for the help!
one frame should work too, but either way yeh
oh yea thats better i will change it, thanks 🙂
Anyone know why i cant create a keystore or load one? When i click add it says make sure you put in the right password even tho i have the correct one. And when i load it just dosent do anything.
Howdy folks. I've settled on a lookup table of shaders to encompass low end mobile, high end mobile and desktop platforms. Individually they all work well, but now I need to dynamically adjust their application across the entire game from the settings window. In the simplest case, if the user clicks "Lighting Off" I want to swap out the Sprite-Default-Lit shader for Sprite-Unlit. How should I approach this? I'd need to update all the prefabs and active objects and their materials. It is possible, just complex trying to find everything in the scene to update. I thought perhaps I'm missing some obviously easier way to accomplish this.
If you're using URP you can override materials across the board with the Render Objects feature: https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal%4013.1/manual/renderer-features/how-to-custom-effect-render-objects.html
the example in that doc is much more complex than what you need
Does that any overhead to the rendering?
no idea
keystore ?
An Android keystore lets you store cryptographic key entries for security. Android Keystore can be used to sign your apk, sign data, store certificates, and a variety of other needs. To release your app to a marketplace, you will need to setup the keystore.
sorry to mention but do you got your API key ?
oh not sure then..Maybe try #📱┃mobile
Its a vr game :/
You said android
oh yeah lol, My bad
you could just instantiate both types at once and just flip the renderers on and off
You mean have two gameobjects for each object?
yeah and keep the other inactive
Well, I'd still need to loop through all of them and do the same thing. The difference is someObject.visible = false vs someObject.GetComponent<Renderer>().material = newMaterial
Keeping track of all the stuff in the scene is just my concern.
Having a single Lit material destroys Android performance so I'm trying to be thorough and careful.
" The difference is someObject.visible = false vs someObject.GetComponent<Renderer>().material = newMaterial"
Quite a difference between caching and instantiating though
I would think the performance hit of having all those extra game objects would be much worse than a one time pause while the setting takes effect.
Its a thought. Just need to think on it a bit.
if they arent active then all you give up is some objects loaded into mem
Well we are talking up to 1000 of them. So its a bit...
public void SetButtons(int buttonCount, string[] labels, UnityEvent[] methods)
{
for (int i=0; i<4; i++)
{
buttons[i].onClick.RemoveAllListeners();
if (i < buttonCount)
{
buttons[i].GetComponentInChildren<Text>().text = labels[i];
buttons[i].onClick.AddListener(methods[i]);
buttons[i].gameObject.SetActive(true);
}
else
{
buttons[i].gameObject.SetActive(false);
}
}
buttonContainer.gameObject.SetActive(true);
}```
can i somehow pass a UnityEvent into AddListener()?
i'm getting the error "'UnityEngine.Events.UnityEvent' to 'UnityEngine.Events.UnityAction'"
which is the reason why game dev use object pools over cleaning up objects
buttons[i].onClick.AddListener(() => methods[i].Invoke());```
however
oh awesome, thanks!
you'll need this though @trail wraith
int copy = i;
buttons[i].onClick.AddListener(() => methods[copy].Invoke());```
I don't think I understand? For example if I have 1000 NPCs in the scene. I wouldn't want or need to pool them. If I had projectiles and things then yeah sure?
Otherwise you're going to run into the variable capture issue
i'll make sure to add it then
It's a balance, but I'd strive for stuff loaded into the scene than instantiating dynamically if possible.
Yeah I agree, if the instantiated stuff has a chance to be destroyed. Generally speaking these NPCs would persist until level unload/reload so I hadn't considered apply pooling to them.
pooling in this case would be reusing the npcs when you zone too far away, and apply them to others in your areas
:nod: My game has no concept of zones or anything like that, but sure. I can see that being something to consider for other game architectures.
im just poking at your comment of instantiating materials and cleaning them up every time you flip a switch
and it's not so much just instantiating them, it's the gc being a pain in the butt
Oh, well I'm not instantiating new materials. Sorry if that was confusing. I basically have a List of 1000 things, and can certainly loop through and update the material of each. But there's probably a couple lists like that. And then I'll want anything new added to the scene (singletons really, nothing pooling would help with) to also have the new material applied.
I can handle the new added stuff in their spawn scripts easily enough. Its just a lot of code in a lot of places for something I was thinking might have a centralized "replace material" call.
The shader materials are all loaded at runtime anyways. So I doubt there's any performance loss from GC taking place.
ah, ok I misunderstood then. Looping through them all and changing materials/shared materials probably fine then
I actually kind of expected there to be a utility. Swapping materials for different targets seems like a no-brainer with Unity multiplatform deployment.
:nod:
shared material updates probably as best as you'd get, but otherwise I'd just replace them all
yeah technically you can change the shader of the material on the fly
so if they're all using the same shared material, you can do that
(you'd also have to change all the variables of course)
to copy everything from a reference material
Ahh interesting.
though it does say "Material's shader is not changed."
I appreciate the ideas.
Ok I'll do some testing with it.
I guess next on the list is how to optimize this weird MouseEvents calls I'm seeing. Its taking up 2ms of frame time as profiled on device. Deep Profiling is certainly making it a bit worse than it would normally be.... but I'm surprised to see so many raycasts off the main camera when its sitting there doing nothing.
PreUpdate.SendMouseEvents is the lead call. There was a lot of complaining about it back in 2011. And folks saying adding a GUILayer to the camera fixed it. Then that became deprecated and nobody really knew what to do. Not sure if this is actually needed or not.
do you have any scripts using OnMouse Enter/Down/Over?
I make use of the Unity GUI which would need those events for buttons, right?
Oh. Hmm.
this is Monobehaviour.OnMouseDown etc
UGUI (not to be confused with IMGUI aka OnGUI) uses the EventSystem for its raycasts
a totally separate thing
Ok thats good to know. I couldn't think of a good reason why the UI would be doing raycasts every frame for its handling.
A grep of my code for OnMouse returns nothing.
if you expand this and go all the way down what is under there?
Although it seems to be ScreenPointToRay itself
which is crazy
that shouldn't be that expensive
Little more detail there.
Seems like it varies and goes up and down at times.
Like pausing/unpausing the game makes it switch between modes. Certainly nothing I'm doing intentionally.
So that's a long one.
do you have a complex physics scene?
Can someone help me privately? Because something is not working for me
So see it went from having 0.23ms of mouse events to 3ms
The orange band being the mouse stuff.
don't crosspost in every single code channel
ok
So this is a top-down 2D game. A tilemap with 4 units on it in this scene. They are just idling about. Nothing related to MouseEvents though.
Tapping in an unused spot on the screen can toggle it between 0.23ms mouseevents and 2-3ms mouseevent call durations. And it persists forever. Really kind of feels like a bug or something odd.
GameTime is 0 so no physics or AI or anything should be processing.
This appears to have been the same issue in 2011: https://forum.unity.com/threads/how-to-turn-off-sendmouseevents.160372/
But the thread just kind of fizzled out. I couldn't make sense of the PlayerLoop approach to disabling unused functions they described.
I don t know why but my slider value is different in build than in the editor.
wdym by "different" because they're two different instances
So i have made grabbing script, works well but im trying to add more features rn but im trying to make it detach when at a distance, to stop some bugs but there is an issue. It detaches as soon as starts. This is what im doing
checking
if (Vector3.Distance(transform.position, NearbyGrabbableObjects[0].transform.position) > UnstickRange)
{
IsStuck = true;
}
to check if you can climb or not
h > 0) && !IsStuck)
detaching
Climbing = false;
IsStuck = false;
I dont know why this is happening, it looks correct to me
Looks like your code is saying "If the distance is GREATER than the unstick range, we are stuck"
which seems backwards?
anyway these tiny little code snippets are difficult to grok without context
Sorry, ill get more in a second
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Share the code more nicely^
Ah ok sorry
so I don t know why but I figured that it happening when I change scenes . I have a cooldown that uses a slider and when I play the scene 1 the bar goes right, but when I go from Scene 2 to 1 the bar moves slower.
How is this bar changed/moved? Could be caused by framerate dependency
Are you using code to move the slider?
yes
Show the code
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.
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Yeah show the rest of the code, especially where time comes from is important
is pretty big
Yes that's why you should click on one of the links for "Large Code Blocks"
So you are incrementing time only once, in Start 🤔
And using that frame's deltatime as the MoveTowards speed in Update
It's very wonky
should be in update
ok
so what can i do about that
I think you can get rid of time and just increment it in update like thiscs slider.value = Mathf.MoveTowards(startdash, targetdash, Time.deltaTime * lerpSpeed);
What you currently do doesn't make much s ense
good evening, how can I create something like this dialog box where the user selects parameters?
(inside unity)
I am looking to produce a cut-away effect for walls in a 2d top-down game that would obscure the view. I'd like to create a 2d maze game. If the player walks behind a wall/piller. I'd like to hide the upper portion of the wall/pillar down to near the floor so the player can see what is there. I'm finding lots of tutorials on how to do the sorting layers, but not one on how to produce that cutaway effect I see in other games that have that type of top down oblique perspective. Any suggestions on where to get started would be greatly appreciated.
https://glowfishinteractive.com/dissolving-the-world-part-1/
And some general info on dissolve shaders
That pretty much covers the problem, but I'm wondering if there are any ideas on applying it to a 2d tilemap. I suppose I'll just have to create test scenario and start tooling around.
Ah, well if you don't really compare zdepth then you need to compare it to something like the character itself
probably need to do some sort of filter by sorting layer and tag, and apply some sort of method of changing the tilemap to another tile or something maybe?
you can probably compare by the y sorting value too probably
but like you probably want some smooth transitioning with the dissolve, so I'd just do dynamic comparison between characters and location probably since its 2D
unless you want something like the silhouette up there
like two ideas is like xcom where you enter a building -> remove the roof and walls completely. Or, if you just want to dissolve partial for where your character is, then that would be more rendering tricks (both render objects and the shader would work, but if you have layers to spare then I'd go with the render object approach since you don't have to apply it to every shader)
this is where you should start using Visual Studio's debugger tool and run through the code step by step to make sure the logic is being executed correctly
Is there anyone who codes windows forms with C# language?
Is this a Unity question
no visual studio c# windows form
This is a Unity discord. !cdisc
Oh, it's !csharp now
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
thx
How do Unity coding projects work?
Code goes in, game comes out
Well duh, I'm talking about the C#
I'm talking about the errors where it says UnityEngine.UI doesn't exist even when the package and everything is installed
then why not ask that instead
Are you using Assembly Definitions? You might need to include the UI namespace in it
What's that?
Do you have any files of type .asmdef in your project
special file that encapsulates scripts together
https://docs.unity3d.com/Manual/ScriptCompilationAssemblyDefinitionFiles.html
Oh, one second, I'll brb
Okay, I will try that and then come back to see if it worked
what? the question is , if you have those files in the project
search the Project folder
Somehow that makes it even more vague
Try what? They are not suggesting doing anything
Always funny when someones says "ill try it" after being asked a question about what they're doing
Sorry for ruining the laugh, but the reason why it's funny is because I'm an idiot and I'm horrible at Unity stuff
now
how do i do this stuff
Okay look here's my "basic" problem.
are you getting the error in Unity only or Unity and IDE
Unity only
always unity only
i think
do you have the UI package inside package manager?
Take a minute to actually describe the problem in 1 message, look at the #854851968446365696 if you're unsure what to say
i gotchu fam
one moment please
nvm wait hold up
I have DLLs like Assembly-CSharp, Rewired, all that stuff, maybe that could help reimport and fix and redefine UnityEngine.UI?
Hey guys I'm having an issue where my script is loosing a reference to an object when the scene is loaded with the scene manager, but when hitting play on that scene the reference is kept. What could be causing this?
are you just gonna keep guessing around or provide what was asked?
Is this script on a DontDestroyOnLoad object, and is it referencing something that isn't?
i'm sorry i'll do what was asked sir
the problem is that the namespace does not exist. CS0234.
The object it is referencing is a script on a prefab in the scene, the script that is referencing that object is a scene object. It has two references both to the same prefab, one is kept and one is lost. The one that is kept is a GameObject reference, the one that is lost is a script reference. Both are private fields tagged with [SerializeField], and neither are set in their own script, so nothing else can be setting it.
yes
is this a new project? ok do the search for asemdef file just incase
Prefabs cannot reference scene objects at all, so I'm not sure how one of them is working. Maybe you should show the object and the hierarchy to provide more context so we don't need to say "the object" and "the other object"
i don't think there is one of the asmdef files
lemme check
People really like to describe references in the most confusing way possible
sorry they're both in the scene. I'm just saying that the scene object is referencing part of a prefab that is dragged into the scene
Also I just discovered that it keeps its reference when it references the game object, but it loses the reference when it references the script. Could it be an execution order thing? Even though the one losing the reference does not have awake or start methods...
Context would help. Using actual names for things for one
has no asmdef file
Send a screenshot of this object selected with the hierarch and inspector visible
Are you modding a game or something? I find it odd how you describe things. Seems like you have code but didnt make the code
i moved pcs
here lemme explain
can you clear the console, if it appears screenshot the error
You've said that already (referring to "lemme explain") now can you do as asked and provide a proper question as per the #854851968446365696
No one wants to read 20 3 word messages
okay gee
i did not have time to buy a usb drive to back up my unity project data, hence why i had to download a compiled version and decompile it
This still all sounds like bullshit to me, but you should use version control. That's the answer there you go
this sounds like "my dog ate my homework"
okay then, in that case i'll convert what i'll say
public class ClickableUnit : MonoBehaviour, IClickable
{
[SerializeField] private UnitSelectMenu _unitMenuUI;
[SerializeField] private GameObject _turnMenuUI;
private bool _isOpen = false;
public void OnClick()
{
if (_unitMenuUI == null || _turnMenuUI == null)
return;
if (_unitMenuUI.UnitMenu.activeSelf)
{
CloseMenu();
}
else
{
OpenMenu();
}
}
public void OpenMenu()
{
_unitMenuUI.UnitMenu.SetActive(true);
_turnMenuUI.SetActive(false);
_isOpen = true;
}
public void CloseMenu()
{
_unitMenuUI.UnitMenu.SetActive(false);
_turnMenuUI.SetActive(true);
_isOpen = false;
}
}
```This is the one losing the reference. `_unitMenuUI` loses the reference while `_turnMenuUI` keeps it. Here are the screenshots:
my conversion is "see: shows footage"
however when that _unitMenuUI is a GameObject field, it does not lose the reference
Looks like TurnMenuUI is a reference to a prefab object, while unitMenuUI is a reference to a thing in the scene. Which things are dragged in to these boxes?
TurnMenuUI is referencing the prefab that is dragged into the scene.
when clicked:
And did you drag in the prefab file or the object from the hierarchy into that slot?
the object from the hierarchy. As you can see it is a child object of the prefab so i wouldn't be able to get a reference from the prefab file.
Okay, so the script is on the root of the prefab, and it's referencing an object on that prefab? Like, PF_BattleMenuCanvas references the pictured TurnMenu, and a different prefab would reference a different TurnMenu object?
the script is not on the root of the object, see this highlight:
the battle menu canvas does not reference turn menu
the script in the inspector is the "clickable unit" script which is on the selected objects in the inspector
like the first picture
And the ClickableUnit script references a UnitMenuUI and a TurnMenuUI object. Are both of those on the same prefab as ClickableUnit
correct
so if I just hit "Play" it keeps its reference, but if I use SceneManager.LoadScene(1) it loses the reference. This scene is the second scene in the build index, i only have 3 scenes.
I don't really understand why the original screenshot had a solid-blue prefab icon for TurnMenu, when surely it should be the same as what's in the scene view
im not sure, it must be a unity thing. It's just a gameobject, so gameobjects that are part of prefabs appear as a solid blue object all the time in the object reference field.
Or how selecting multiple prefab instances would show an object reference instead of a --- if they're each referencing their own TurnMenu object
they all reference the same object, the reference is applied in the scene
I just tested it and it does seem like it does this, so I retract that
So, is the script referencing a TurnMenu on itself or are they all referencing the same one? These are contradictory statements
That's a strange UI choice
The only reason you'd lose a reference is:
- You are setting it to null
- The instance has been destroyed (often because the scene it was in has been unloaded)
I would not make assumptions about bugs and would triple check both your code, for assignments, and the scene's references
why does it not lose reference if I change it to a GameObject instead of the script?
all that changes in the code right here is that instead of _unitMenuUI.UnitMenu.SetActive() it's _unitMenuUI.SetActive()
i mean that's what I'm doing, changing it to a GameObject, but... i feel like that should not be what fixes it.
We can't really help any further, the issue seems specific to the details of your setup, or is a weird bug that nobody has seen before
If you record a video of the whole thing, including the references, how they relate to each other, the scenes they're in, and what changes when you reload the scene, then maybe there'd be something we spot
hmm ok
My guess is that since you have to re-assign it in the inspector after changing the type, you're probably properly referencing the one inside of this prefab (which will not be lost) instead of a specific one in the scene (which is)
heya, I'm pretty rusty on my trig (ignore the ugliness, I've been prototyping this pretty hard for a bit)
I know enough to realize this can be turned into a usage of sin + cos or atan, but I don't know enough to know how
would anyone mind pointing me in the right direction
{
"name": "FigurativelyGames.Main",
"references": [
"FigurativelyGames.Main.Tools",
"FigurativelyGames.Main.Planes",
"Unity.RenderPipelines.HighDefinition.Runtime"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.render-pipelines.high-definition",
"expression": "7.1.0",
"define": "HDRP_7_1_0_OR_NEWER"
},
{
"name": "com.unity.modules.particlesystem",
"expression": "1.0.0",
"define": "USING_PARTICLE_SYSTEM"
}
],
"noEngineReferences": false
}
will someone tell me where to put my packages? i have some packages i need to put in here
What exactly are you trying to do? What are all these vector params?
I'm attempting to find the correct rotation for this edge sprite that you see clipped all over the place
the arguments I have available are the vertices of the triangle on top and the vertices of the triangle of the wall below it
Vector3 shared1 = Vector3.zero;
Vector3 shared2 = Vector3.zero;
if (parent1 == target1 || parent1 == target2 || parent1 == target3) shared1 = parent1;
else if (parent2 == target1 || parent2 == target2 || parent2 == target3) shared1 = parent2;
else if (parent3 == target1 || parent3 == target2 || parent3 == target3) shared1 = parent3;
if (parent1 != shared1 && (parent1 == target1 || parent1 == target2 || parent1 == target3)) shared2 = parent1;
else if (parent2 != shared1 && (parent2 == target1 || parent2 == target2 || parent2 == target3)) shared2 = parent2;
else if (parent3 != shared1 && (parent3 == target1 || parent3 == target2 || parent3 == target3)) shared2 = parent3;
return Mathf.Atan2(shared2.z - shared1.z, shared2.x - shared1.x);
this is it taking the two shared vectors (the edge) between the two faces and getting the angle of that edge, which I thought might work but clearly hasn't
it works exclusively along the bottom there where the angle is 0
Can you visualize what these points are on the screenshot? And rotation(?) of what you're trying to find? Because it's not really clear from the explanation.
sure
shared 1 is the red dot here, shared 2 is the blue dot
the returned rotation is the angle of the edge highlighted in green, which is used to rotate this south-facing sprite
the ugly comparators are just a sloppy way I'm using to find the shared vertices atm
i believe so yeah
Does it need to be an angle? How are you using it after that?
Ok, so it's uvs for each tile..?
oh my god
I think there're more problems than that...
that's it right
it's rotating worldspace uvs
so obviously it's going to be way off
god damn it
my entire problem with this so far has been trying to texture a procedurally generated marching cubes mesh
which exclusively uses worldspace uvs
You could use a cross product of the edge to get a perpendicular vector, then get it's angle.
that sounds correct, I'll try that out
do you know how to rotate a texture using worldspace UVs also by chance
All the nodes are doing are rotating the uvs, not the texture. The texture is then sampled according to the uvs.
I don't know enough about your shader to say any more than that.
Maybe ask share more details in #archived-shaders
is there any way to make an inheritted static function?
found it, a bgolus hit as per usual haha
led me to here: https://www.reddit.com/r/godot/comments/ldqwve/how_to_rotate_each_uv_tile_individualy_in/ which had the answer
praise be bgolus
what are u trying to do? you can just redeclare the function in the child class and itll work. like
public new static ...
base class has a static method, which calls on some of the abstract functions in the abstract base class
and I want each base class to just have their own version of the static method that operates on their overrides.
do you have any actual errors with implementing this? to my knowledge this shouldnt be a problem at all. you just write the method
wait you're right. I can just do that lol
ty
nvm, I can't
because my static method depends on an abstract method, which is itself not static
so if I could make that static, I would be set.
if that method isnt associated with any instance, then just make it static and remove the abstract
it's associated with the derived class
anyway, in this case, I just bit the bullet, and made a nonsensical instance, which won't cost me anything. it's just dumb.
https://dotnetfiddle.net/TDERI5 is this not what you want? im confused on what the actual issue is
public class NonFungibleTileDataCollection : ObjSaveDataCollection<INonFungibleTileHandler> {
protected override IEnumerable<INonFungibleTileHandler> EnumerateDataSavers() {
NonFungibleTileManager customDrawManager = NonFungibleTileManager.GetInstance();
foreach (INonFungibleTileHandler logic in customDrawManager.NonFungibleTileHandlers) {
yield return logic;
}
}
}
public abstract class ObjSaveDataCollection<TDataSaver> where TDataSaver : IDataSaver {
/// <summary>Enumerate out all the IDataSavers that this data type is connected to.</summary>
protected abstract IEnumerable<TDataSaver> EnumerateDataSavers();
/// <summary>Load all as default</summary>
public void LoadAllAsDefault() {
foreach (TDataSaver saver in EnumerateDataSavers()) {
saver.LoadDefault();
}
}
let me reduce the total info
ok, better. the members I have there for the ObjSaveDataCollection should both be static, in the sense that they are not really associated with an instance
but EnumerateDataSavers can't be both abstract and static, for LoadAllAsDefault (depends on it) can't be static either
why cant both be static?
you dont use the abstract keyword when its static, but i dont really see what you mean with LoadAllAsDefault cant be static
because Enumerate… can’t be both static and abstract
that method must be filled out by the derived class
making it not abstract is not an option
realistically i would be questioning why u want it static in the first place, but what i was saying was you could just make them all static (without the abstract keyword). The one in the base class could just yield return null or whatever dummy data. I guess the issue with static is you might have to redeclare LoadAllAsDefault in each child class
i was interpreting what you were saying as it isnt possible, which it is. Its just not ideal here
could someone explain to me the differencce between defaultcapacity and maxsize in an object pool?
Its explained on the docs for the constructor (ctor)
https://docs.unity3d.com/2022.2/Documentation/ScriptReference/Pool.ObjectPool_1-ctor.html
how high should maxSize be generally? for something like a damage number system
I use the vfx graph for numbers but usually like 30k
what about the default capacity? like 1000?
but that's usually harder to extend, but unity pool is a queue right? so probably fine to extend
i dont know too much about the unity pooling, but ideally you make a smart pool that extends gradually when it hits break points you set
at 70% extend another 100 over time
That's just something you'll have to experiment with and find out. You'll likely not have that many on screen at once, and if these are game objects then you'll not get as many as possible with vfx graph
Is the Unity website down?
so vfx graph is more performant?
defaultcapacity is loading right when the pool is created, if you set it to 1000, the pool starts with 1000 available entries, maxsize is how many it can contain total
so it differs from use-case to use-case, there is no "best" values
gpu instancing is usually good for stuff like text or minor renders to be batch in single calls. (srp does provide easy access to gpu instancing which you can just flip on in the material, so something to profile. VFX graph isn't required, but it's great at set and forget stuff)
because I do not need an instance for it, or access to any instance variables, and I need to invoke when there is no instance
if enumerate is not abstract, then how will the static LoadAllAsDefault call the right function for the derived class
I am trying to publish a game for a class and for some reason, unity is being weird with me when I try to edit/publish it. It would not fully load
press ctrl + shift + r, clears caches and does a fresh reload
if that doesnt help you would need to look into the console
oh and also disable ad blockers 😄
i fixed it by just making a nonsensical instance this time, but it is annoying that I can’t make abstract static methods
That's what I was talking about in the final part of the message, you may need to declare that method in all child classes. Theres likely a cleaner workaround
Thank you
worked?
It worked : )
Is there a better way to grab a reference to the current gameObject's PhysicsScene when it moves between subscenes?
Preferably outside of Update()
private string lastScene;
private PhysicsScene physicsScene;
void Update() {
if(gameObject.scene.name != lastScene) {
lastScene = gameObject.scene.name;
physicsScene = gameObject.scene.GetPhysicsScene();
}
}
You mean to a different scene? "Subscenes" are an ECS thing.
I don't think there's a message sent when an object moves between scenes, unfortunately
Yeah i didnt see anything at the object level, just when the main scene changes on scenemanager
If I'm understanding correctly, something like this (https://stackoverflow.com/a/66927384/882973) might help if you use it with your NonFungibleTileManager to get the instance. You would need to pass in an additional type parameter to EnumerateDataSavers to reference the tile manager type. This would make the entire EnumerateDataSavers function general purpose and thus could be static without needing to be abstract.
This seems to do its job, its not hurting performance and works fine
I'm trying to implement gadgets that damage/heal players on interact and was wondering if the best way to do it was to inherit from an interactables class I wrote and overriding the behaviors in functions? Does this seem like a scalable approach
sure, but you're not stuck strictly to a single interface. Could consider dividing it down into behaviours like Use(EntityTarget)
but otherwise, yeah you can do a lot with one of these behavioral classes/interfaces if you embrace those polymorphic method calls
what's an EntityTarget?
By dividing down do you mean creating more template interfaces?
for example all objects dealing damage inherit from x and such
Yeah, I primarily use interact for interacting in the environment if I use it, but for stuff like items I have Use(), Equip(), Trigger(), Throw()
Thanks!
Usually with a parameter specifically for targeting
What would an example of this be? I'm not sure what exactly you mean by parameter and targeting
Well, if you make it parameterless then you could assume the object that has the behaviour will use it for themself, but if you supply a specific targeting parameter you can specify how and where to use it, like say you have an effect class that adds poison to the target, so you'd have something like Apply(), but you don't want to apply it to yourself so you'd add something like Apply(target)... but you can also still apply it to yourself if you decide to target yourself ;)
Gotcha
the target itself could be an interface too like say an IEntity which contains an implementation of Stats class where you can deduct health from
or an abstract class. Either or honestly
Somebody mind helping me out with a collider issue i am having a hard time on how to fix?
I get stuck like this when i jump between objects, I move my character with force (guessing that is why it happens as it has a physics material with no friction)
what you want to pool?
Some object pooling will pre-allocate, there will still be default allocation during initialization for the array.
This imported asset has a copy of every mesh and material for each animation
is this normal, and will it affect build times / run time / storage??
where the coding question at
This does not make logical sense anyway because abstract is supposed to be implemented by an instance. Static does not depend on an instance and neither does it support inheritance, so there would be no way to implement it.
It sounds like overcomplication if you want to do this. For what it's worth, newer C# versions support static interface methods which do something that's close to what you want, but instead in a more logical way
Hey I added this script to my project: https://diegogiacomelli.com.br/unitytips-scene-selection-toolbar/
To add a scene select menu to my editor. However I can't see where it saves the data is uses, and I want to push it into git. It uses setpref, I assume this thing: https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
How can I share this over git and will it update when we change build numbers etc?
look deeper
EditorPrefs.SetString
If you want it on git, replace the editor prefs stuff with a file that gets saved in project. Prefs dont get saved to places that are pushed to repos
Ok thanks, I was looking in playerprefs not editorprefs, I don't see any pref beginning: "SceneSelectionToolbar.Scenes" tho 
edit to above, yeah I figure, I wouldn't be super opposed to sharing a .reg that trusting people can add on the side
you won't, look at how the key is made
$"{Application.productName}_{name}"
That's not what I was suggesting, I meant replace the code that uses editor prefs with your own saving code which saves to a file.
so sharing wont work if the project name is not exactly the same
yeah and we increment build numbers a lot as well which would break this, first I'll try changing that to a static hardcoded string (you can prob tell I'm less a dev, more a tech artist)
yeah, do what @lean sail said, save to a json file and share that via git
Very strange bug I'm experiencing at the moment that I've never ran into before.
Each frame I check for inputs from a static class and it works fine until I reload the scene.
{
public static PlayerInputs GetInputs()
{
var inputs = new PlayerInputs();
inputs.MoveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
Debug.Log(new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")));```
The debug log is being called however, after reloading the scene it's no longer registering the input axis and alwasy returning 0,0
The reloading scene coroutine:
``` private IEnumerator HandleReset(float duration)
{
yield return new WaitForSecondsRealtime(duration);
string currentSceneName = SceneManager.GetActiveScene().name;
Debug.Log("RELOAD");
SceneManager.LoadScene(currentSceneName);
}```
Does the debug log print after the scene reload?
yep another clue I found, the inputs are not registering for GetAxis. Input.GetKey(KeyCode.Space) is working
Does GetAxisRaw work?
yep
can you share the code for PlayerInputs
Are you setting time scale to 0 perhaps?
thats exactly it thank you, so basically before the reload I have a code that sets the time scale to 0. I had no idea its permanent
{
var inputs = new PlayerInputs();
inputs.MoveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Debug.Log(new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")));
// Debug.Log(Input.GetKey(KeyCode.Space));
inputs.LookInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
inputs.PrimaryDown = Input.GetKey(KeyCode.Mouse0);
inputs.SecondaryDown = Input.GetKey(KeyCode.Mouse1);
inputs.InteractDown = Input.GetKeyUp(KeyCode.F);
inputs.ReloadDown = Input.GetKeyUp(KeyCode.R);
inputs.AbilityDown1 = Input.GetKeyUp(KeyCode.Q);
inputs.AbilityDown2 = Input.GetKeyUp(KeyCode.E);
inputs.MeleeDown = Input.GetKeyUp(KeyCode.LeftShift);
inputs.ScrollInput = Input.GetAxis("Mouse ScrollWheel") < 0f || Input.GetAxis("Mouse ScrollWheel") > 0f ? 1 : 0;
inputs.JumpDown = Input.GetKeyDown(KeyCode.Space);
return inputs;
}```
It is. Had no idea it affects get axis though
{
if (state == GameState.Default)
{
Time.timeScale = 1;
_gameState = GameState.Default;
_playerMaster.SetState(PlayerMaster.State.Default);
}
else
{
Time.timeScale = 0;
_gameState = GameState.Default;
_playerMaster.SetState(PlayerMaster.State.Disabled);
}
}```
I meant the class
{
public Vector2 MoveInput;
public Vector2 LookInput;
public Quaternion CameraRot;
public bool PrimaryDown;
public bool SecondaryDown;
public bool ReloadDown;
public bool MeleeDown;
public bool AbilityDown1;
public bool AbilityDown2;
public bool InteractDown;
public int ScrollInput;
public bool JumpDown;
}```
Ok so I found the culprit here. I'm currently in a different scene and entergamestate default isnt being called which is why the time scale isn't being set back to 1 thank you
that is very odd. That timeScale would affect GetAxis but not GetAxisRaw. I would definitely report that as a bug
what is it supposed to do?
Get axis interpolates to get axis raw value, so it would make sense.
timeScale should not affect either, mouse movement should be independant of timeScale
This is not mouse movement. I wonder if it affects the axis set up as mouse though.
ok I reported the bug
I see what you mean, it's deltaTime dependant, so yes, that makes sense
Probably not a bug. Just undocumented behavior
iffy, is it a bug or is it a feature?
definitely an edge case
@jagged snow Well spotted. If I was you I would flag a change to the GetAxis doc page and ask them to add this information
alright
on the above conversion to assets folder json from editorprefs you'll be pleased to know chatgpt did it for me
thanks for pointing me in the right direction
actually, far from pleased. Please do NOT rely on AI to produce good working code
that ws tongue in cheek. I'm sure we are all displeased with "AI" for many reasons, however you gave me enough to leverage it to solve my issue, so thanks 🙏
what most people fail to realise is that GPT does not write code, it produces text that looks like code. There is a huge difference
I guess I'm not many people, however knowing that and knowing how to specify code and debug it and see where it's falling down it's been a hugely helpful tool for me and my team, anyway getting out of scope of my "thank you"
np, glad you fixed it
why is my navmesh agent so clumsy lmfao
How to fix this rectangle? I think that unity cannot convert m_text: "\u2615\uFE0F \U0001F375" to right emoji
hes like walking into walls and unable to enter doors sometimes LOL
Is this a coding question? If so please share actual code because your question is not going to get an answer in its current format
If this is an issue with navmesh, you might be better off asking in #🤖┃ai-navigation or something
oh i see ty
Hi everyone! I'm experiencing some issues with the optimization of my game. I went into settings and set the LOD Bias to 0.1 and saw that even without almost anything on my screen I have 3.0M tris. Is this how it should be or something that I'm not aware of is happening?
how many triangles are you expecting to see from the assets you're showing in the viewport there?
with the LOD bias set to 2 i have 3.7M
i want to lower it down but idk where to start from
i mean like, we don't know your assets and the scene is super dark, give us an idea of what's on screen there
we don't know that tree in the background isn't 1 million tris haha
this is from the scene view
ok, but how many triangles are in those meshes?
how can i check this?
time to delete some verts 😄
i think there's some third party tools to auto generate lower detail LODs in unity, otherwise you can make them in blender or something
Alright, I'll look it up, thank you!
i have my inventory system with inventory items as scriptable objects, should i change them to be classes with [System.Serializable] for a easy way to save/load them or its fine to have them as scriptable objects? will saving/loading be way more complicated with scriptable objects or its no big deal?
just thinking long term for a project with a lot of different type of items
Use scriptable objects to store item definitions
Use plain-old classes to store item instances (or your entire inventory)
so you'll have a scriptable object that defines what iron ore is
you will use this to store its name, its icon, its 3D model, etc.
then you'll have an inventory object that tells you how many of each kind of item you have
If items need additional data (maybe you can upgrade your sword into a +3 flaming sword), you should store that in a normal class as well
public class WeaponItem {
public WeaponDefinition definition;
public List<Enchantment> enchantments;
}
ok so this WeaponItem would have [System.Serializable] and my inventory will consist of a list of items that have [System.Serializable] right? instead of having a list of scriptableobjects in my inventory directly, instead i have a class that is serializable and inside i have the scriptable object
no?
so in your case WeaponDefinition is a scriptable object and WeaponItem is a class with [System.Serializable]
so I found something. I think I've done something wrong when I was creating the house. One box has 30 tris and one 50k. I clicked the one with 50k and it has a combined mesh and after clicking the combined mesh it looks like this
I've seen this is on plenty of my items
I surely did something wrong when I was creating the map
Have you seen anything like this before?
i think that's just static batching doing its job
Right.
The only catch here is that you need a way to actually serialize that weapon definition.
You aren't going to serialize the contents of the definition. You'll need to save an identifier you can use to look the definition back up later.
I've done this copying the GUID of each asset into a field on itself. So, the item definition looks a bit like this
public class ItemDefinition : ScriptableObject {
public Guid guid;
public string label;
public float cost;
public int florps;
}
I use Json.NET. I wrote a custom converter so that, when I try to serialize an ItemDefinition, it just writes the guid.
note that since System.Guid isn't serializable by Unity (which is necessary to store the guid in the asset), this is a custom Guid type
I used this to figure everything out.
When I deserialize an ItemDefinition, it looks up the guid in a dictionary
Would anyone mind?
This way, I can remember which ItemDefinition asset my item used, and then recall it later when I deserialize.
It's not clearing.
Every instance of that item in an inventory shares the same ItemDefinition.
Look at the bottom half of the console. There is probably more text.
e.g.
i see, so somewhat similar to sprites since u cant serialize them directly but use references
but in your custom way to save guids
You can also use any other unique identifier
The name of the item might work, but I avoided that because I might want to rename my items
I use this pattern for my settings system. So my saved settings look like this:
{
"choiceSettingValues": [
{
"setting": "828733BD80E3745DCBA6E5F4E67AD4CE",
"value": "F1D8CC763672F48839D944402699EE23"
},
{
"setting": "F1E50A54133E14D3C85226948900A3AF",
"value": "D6FB5C2D145C1457F8F1CBB1D9F0791A"
},
...
choice settings are for things like picking an anti-aliasing mode
both the setting itself and each choice are assets
no yea i have a similar case where i store 2 guids for my items, 1 for the itembase, for things like recipes where i dont mind the item being modified, and other for the unique item to identify from the rest of the same type. So i need something similar
from an older game where I initially figured out saving and loading an inventory:
{
"lastUplink": "32E2281B4657447BCB710B50D6470FB9",
"uplinks": [
"32E2281B4657447BCB710B50D6470FB9"
],
"items": [
{
"$type": "InventoryRangedWeapon, Assembly-CSharp",
"spec": "20AFB2D518C6B4CB0A26D744C1EEF498"
},
{
"$type": "InventoryMeleeWeapon, Assembly-CSharp",
"spec": "BAAE6BDFA0F554EDB8BD467BAFF0A73C"
}
],
"wallet": {
"currencies": [
{
"currency": "8582C22BF7E3E4299948738362554384",
"amount": 100
}
]
},
"playerProgression": {
"levelUps": []
}
}
well thanks a lot i will take a look at all of this and change my system
there's not
"uplinks" are save points
try scrolling down in the lower area
thanks a lot!
note that discussion of reverse-engineering isn't permitted in this server, which it looks like you're trying to do here
Using GUIDs means that you can rename and modify your assets without breaking existing save data. Just don't delete and recreate them 😉
i'll slide my way out of here
You'll just need to make a list of all of your items, or put them in a Resources folder and use Resources.LoadAll
I do a little bit of both
for settings, I need a hierarchy anyway to organize them in the settings menu
so I have a hierarchy of SettingCategory assets that reference all of the individual settings
ok i will try to change my entire system with all this, i was directly having a list scriptable objects in my inventorymanager, which i imagine this would be really bad for saving/loading compared to having a list of serializable items. Never gone too deep into complex system of saving/loading
with a list of scriptable object i imagine the script for saving would be very complex
This is fine if you don't need to store any other data for each item
i.e. you don't have "stacks" of items
You still have to figure out how to save and load which items you have either way
Having a class like this just lets you tack on extra data
ok i see, thanks a lot ❤️
Hey,
I have a JS App that has data I require in the game
How would be the best way to transfer that data to the game ?
http post i guess
UnityWebRequest can be used to make HTTP requests.
i think they want to receive the data in game
it requires a server listen to some port running on other thread
making a post request from browser and send that to your game
what? That makes no sense
i have no idea why there is a js front end (probably) and unity running at same time
no such thing as a JS backend, I'm guessing it's Node.js and a UnityWebRequest GET should do the job
👀
Not sure where to ask this but I have a problem:
I have a Player Prefab containing a few different things:
- a Character from Mixamo
- a Player POV Gameobject containing an AudioListener and a Camera
- a GroundCheck object.
my current problem is the mouse look script that is attached to the Prefab itself, doesn't move the actual head / arms of the player like it should.
the camera itself moves but once I look down my hands are still looking forward
make the arms a child of the camera?
Thanks 🙂
Done it in 5minutes using HttpListener.Start 🙂
Thank you Fen too
just make sure you're not listening on the main thread, and that you handle transferring data between threads properly.
how would I do that efficiently? I don't want to rip apart the rig and put the arms somewhere else
i think im doing both correctlyu
wdym by efficiently?
This is the whole rig
I mean how do I do it?
so I have to put my question there? isn't it just a code problem of telling the head to rotate?
No because you're dealing with an animator and a skinned mesh
and trying to override part of the animation
that's aim constraints and inverse kinematics
Ah okay so I will ask my question there, hopefully someone can help me
i think need fix problem script
Pretty straightforward error. You're using something on line 26 called slb, but slb doesn't exist.
without seeing the code, that's all we can say
if (Vector3.Magnitude(GetVector33(i)) <= collider.radius)
{
Vector3 vector33 = GetVector33(i);
Vector3 vector32 = entities[i].transform.position - transform.position;
(int, int, int) p = (0, 0, 0);
Vector3 vector31 = Quaternion.Euler(spin)
* p;
Vector3 vector2 = vector31;
(int, int, int) p1 = (0, 0, 0);
modifiers[i].movementAddend = (vector2 - p1 / Time.deltaTime);
}
else
{
modifiers[i].movementAddend = Vector3.zero;
}
I'm trying to figure out how to multiply Vector3s by p and divide by p.
How can I do this?
Why are you using an int int int tuple
what is the goal of this code?
I just try to fix slb but doesn't work so how? About Juice bottles
Again without seeing you code I can't help further. This comment doesn't clarify anything
Juice bottles? What?
this Juice bottles
Ok what relevance does that have to your compile error?
You can only use variables that exist in C#
You can't use things that don't exist.
You don't have a variable named slb, so you can't use it.
just used ctrl + .
without seeing the code, that's all we can say
Again without seeing you code I can't help further. This comment doesn't clarify anything
variables is so work?
What?
i can't really explain without giving a good answer, because i have no good english
I have no idea what that means or why you're using (int, int, int).
if you can't explain your problem in a way that I can understand, unfortunately I won't be able to help
Likewise for you, I cannot understand your question
ah okay
i can try to explain in my best manners but it may be hard to do so
Hey, Really stupid person question but
string receivedData = "";
using (System.IO.Stream body = context.Request.InputStream) // auto-disposes
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(body, context.Request.ContentEncoding))
{
receivedData = reader.ReadToEnd();
}
}
Debug.Log("Received POST data: " + receivedData);
responseContent = !string.IsNullOrEmpty(receivedData) ? receivedData : "No data received";
PastData = responseContent;```
How can i make "PastData" a actual Json / JObject so i can traverse it properly 🙂
Sorry
i'm using int int int because ctrl+ . is my only choice out to do so
parse it with a json parser
What is "ctrl + ." and why does it matter?
You should not limit your code to whatever this "ctrl + ." does
quick fix in vscode, and they should learn to use vec3
go inside visual studio
I'm guessing you used the "Introduce Local" quick action.
This fixed the compile error by creating a variable that's compatible with (0, 0, 0), but this is..not correct
If you want to multiply a vector by a number you can just do it. There's no need for (int, int int).
For example:
Vector3 test = new Vector3(1, 1, 1);
Vector3 result = test * 3;
print(result); // prints (3, 3, 3)```
You asked the compiler to do something to make your code compile. That something is wrong.
(1, 2, 3) is a tuple of three integers
It has nothing do whatsoever with a Vector3
i meant more like how?
Like newtonsoft? or is there a better one as i kind of hate the PastData[Match][Example]
its just awkward compard to PastData.Match.Example
Newtonsoft offers several parsing APIs
Thank you so much.. kudos to you for that
JsonConvert can convert it to a regular C# class with the appropriate structure
there's also the JObject API which you specifically asked about
I have another problem though.
There's also JsonUtility from Unity @glad plinth
ohh i never knew that
i thought Newton soft = JObject way
Newtonsoft is generally the best and easiest way. There's also System.Text.Json which is even better but this requires work to set up due to lack of support. Lastly there is JSONUtility which is very basic and barely works due to backwards compatibility, so I advice against this
It says something about a call being ambegious or how do you spell this
No it also has a dynamic approach and JsonConvert
private Vector3 GetVector33(int i) => entities[i].transform.position.ZeroOutY();
if you have an error please provide the full error message and the full code
So what does it reference in the error? Would this be Vector3?
If so, remove the using System.Numerics; from the top of your file
Dynamics definetly sound best as then it is still using . to change levels unsure if the others do
Sorry. Will do.
Severity Code Description Project File Line Suppression State
Error CS0121 The call is ambiguous between the following methods or properties: 'Vector3Extensions.ZeroOutY(UnityEngine.Vector3)' and 'Vector3Extensions.ZeroOutY(UnityEngine.Vector3)'
you duplicated your function
delete one of the copies
You might have duplicated the whole class
Now it says it doesn't exist.
If you don't know where you did it might be worth checking for stray files in the explorer
Perhaps there is a duplicate file with the same code, causing this.
This is why you don't use quick fix (ctrl + .) Without knowing EXACTLY what it is suggesting. It likely had you add System.Numerics
Edit: ah, lag, different issue it looks like
What I said first is still important though
Don't use quick fix without knowing exactly what it is doing
anyone knows what could cause this WaitOnSwapChain? I also have it even with Vsync enable or disabled
Could someone help? Severity Code Description Project File Line Suppression State
Error CS0121 The call is ambiguous between the following methods or properties: 'Vector3Extensions.ZeroOutY(UnityEngine.Vector3)' and 'Vector3Extensions.ZeroOutY(UnityEngine.Vector3)'
Proooobably, waiting for the GPU to finish work.
Sounds like duplicate extension methods..?
I'm lookin' for a way to fix.
I tried cleaning the binaries.
About to try cleaning the solution.
Find all the places that implement that extension method and delete some of them.
I don't think cleaning stuff is gonna help. The issue is with your code.
this looks like it's from VS, do you get a compile error in unity? it might just be your project/solution needs regenerating
I'll find out
I regenerated my whole solution and my whole Unity project just collapsed.
given that the unity project doesn't really use those solution files at all, i have no idea how you managed that 😅
What do you mean by "collapsed" anyway?
I just got a bunch more errors.
In the unity console?
VS IDE
That is expected....
That is not collapsing, that is working
Are there any errors in unity?
Yup
Start from fixing the errors that appear in unity console.
2 syntax errors
can't do that
Those errors are not related to the errors I need to mainly fix
Fix the errors anyway
I'll fix them after.
Bad plan
Here are the errors though if you want to see them:
fine, I'll fix them.
{
if (text.ToLower().StartsWith("file://") || text.ToLower().StartsWith("http://") || text.ToLower().StartsWith("https://"))
{
MidiSynth[] synths = UnityEngine.Object.FindObjectsOfType<MidiSynth>();
Routine.RunCoroutine(ImSoundFont.LoadLiveSF(text, ImSoundFont.GetDicAudioClip(),DicAudioWave dicAudioWave,
DicAudioClip dicAudioClip, defaultBank, drumBank, synths, restartPlayer), Segment.RealtimeUpdate);
return true;
}
UnityEngine.Debug.LogWarning("MPTK_LoadLiveSF: path to SoundFont must start with file:// or http:// or https:// - found: '" + text + "'");
}
These are not errors...
Well in general Idk how to fix them.
I only see a code snippet
Fix what?
In the snippet, are the errors
Without seeing the errors we can not help of course
This is not the unity console
Now share the line that throws the error.
Routine.RunCoroutine(ImSoundFont.LoadLiveSF(text, ImSoundFont.GetDicAudioClip(),DicAudioWave dicAudioWave,```
You'll need to start sharing code properly...
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
DicAudioClip dicAudioClip, defaultBank, drumBank, synths, restartPlayer), Segment.RealtimeUpdate);```
Just share the whole script...
You included a type
But I guess the issue is DicAudioClip dicAudioClip
Can you send me the code with it fixed?
No
What exactly are you trying to do there?
aw
Whatever you're trying to do, I suggest you stop right there, and go learn the C# basics.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I do know the C# basics, it's just different from Unity's C#
Wdym?
WPF
It's totally the same C#.
False
Unity is just an API you use with c#
The C# is the same. Syntax errors like the one you get would be fixed exactly the same way in WPF.
Remove the type from your method call
This is a basic c# thing
nevermind
You can't have a declaration right in the method params like that.
Thanks for your guys' help
You helped a lot, and I'll definetly check out the Unity Learn thing! 😄
Might want to go through the C# manual too, since the issue is less related to unity.
can i somehow make this smaller or make it dissapear? I'm getting frequent frame drops
Optimize your shaders I guess. This issue requires a lot more diagnostics. Can't really help you without more details on it.
Alright. Thank you for the tip!
Does it happen every frame or is it spikes? Does it happen at some specific timing? Check the GPU module of the profiler. What GPU time does it show? What takes most of the time?
Spikes, not specific timing
I'm just moving around
What does your scene look like? Are you using GPU heavy stuff like a lot of post processing effects? What's your screen resolution? Are you using compute shaders? Are you using custom shaders other than that? Is your gou doing any other work than rendering the game?
Game looks like this. around 3.5M tris
pp only bloom vignette and chromatic aberration
1080p screen res
Check the GPU profiler to make sure these spike coincide with high GPU time.
Hi. How to check internet connection correctly?
If you can send messages on discord, you probably have an internet connection.
what's strange is if I'm in unity editor I'm not getting them anymore
I've been running around for the past couple of minutes and no freezes anymore
I also have a script that does this: QualitySettings.maxQueuedFrames = 2 as I've read in a unity forum it helps
but as far as I know this is also the default option?
protected override async UniTask AsyncRunInternal(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
IsConnected = Application.internetReachability != NetworkReachability.NotReachable;
if (!IsConnected)
{
IsConnected = false;
_provider.Popup.Show();
await _provider.Popup.TryAgainBtn.AsyncWaitForClick(CancellationToken);
_provider.Popup.Hide();
}
await UniTask.Delay(TimeSpan.FromSeconds(0.2f), cancellationToken: token);
}
}
I check this way, but as I understand it, this is an unreliable method. As the Unity writes "Note: Do not use this property to determine the actual connectivity. For example, the device can be connected to a hot spot, but not have the actual route to the network."
send a ping to google
Yeah, this method is for testing what kind of connection you appear to have
The only real way to decide if you're online is to check if you can reach the service you need.
You'd use this to avoid downloading 500 megabytes of stuff over a cellular connection
which services are best to check in order to cover most countries of the world? Maybe someone has a small example on this topic? Thank you
Why do you need internet access?
my application works with server
Try to talk to your server, then!
note that Application.internetReachability can reliably tell you that you don't have internet access. So you can check that first before trying anything else
as I said, google is probably the most reliable place to ping. but since you need internet in the first place... why not just use the game server?
It just can't reliably tell you that you can actually talk to your server
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
private async UniTask<bool> CheckInternetConnection()
{
try
{
Ping ping = new Ping("google.com");
PingReply reply = await UniTask.Run(() => ping.Send());
return reply.Status == IPStatus.Success;
}
catch (Exception)
{
return false;
}
}
Is it good variant?
i got another one in the editor called Semaphore.WaitForSignal and it does not correspond with the cpu usage, is this a new one or the same as before?
Try to talk to your own server.
That will be more useful (and make slightly less spam aimed at Google)
ok, is everything correct in the rest of the code?
there is a lot of code. what you need to do is:
- Add these methods to a class, and call PhysicsMethodBenchmarking(); in Awake
- A lot of the stuff in the actual physics benchmark method is custom. Edit as needed. The main methods you need to run MeasureBenchmark( on are: 1) TestMovement, because this is time cost that is not associated with benchmark that you should ignore. 2) TestColDist(, which tests Distance, and 3) TestOverlapBasic(, because that tests OverlapCollider
I don't know how Ping works and I'm unfamiliar with UniTask, so I can't say much
@latent latch
you do not need all the other methods. and you should be able to infer more or less what you need, for all of the classes unique to my code
stopwatch pretty accurate?
yeah. it goes off system time
also, MeasureBenchmark on TestMovement gives you a baseline
I added in comments the result of the test
but that is for like, all of my stuff
it should give you an idea of what it should look like
aight, probably worth making a test script for this stuff as it's gotten to that point now
tyty
glhf
unrelated, but UniTask is a allocation free implementation of Task. I highly recommend it, it's a fantastic little package
my style here is kind of messy (hence the 200 LoC function), since it is like a one-off experiment
so sorry about that lol
Hi
having some issues in Python. Can anyone assist?
trying to get screenheight & width to be 4/2
not sure where I am going wrong in my code.
try asking in a python discord. this is a unity server with no off topic allowed
Hi, I'm trying to create a level generator script that will generate prefabs based on their given entry points and to try and prevent overlapping. Here are the two scripts so far:
https://paste.myst.rs/oyfceedq
However, I'm running into an issue with freezing during my while loop and can't figure out why
a powerful website for storing and sharing text and code snippets. completely free and open source.
ahh I saw code-general, my bad
you should probably check that there are any valid segments in the list first, presumably none of them are valid so it loops forever in here:
while(!s.IsValid(spawnPoint, entryDirection, currentPositions))
{
s = levelSegments[Random.Range(0, levelSegments.Length)];
}
also, you're picking random segments until you find one which is valid, which i guess could take a long time if you have lots of segments and only a few of them are valid... why not make a list of valid ones first and then pick one of those at random?
In unity I am trying to make ice, the friction thing works but the object on it stops pretty quickly, I want it to slowly keep sliding a bit (even at low speeds). How do I have control over that?
yeah, that'll turn into the coupon-collecting problem
it gets increasingly unlikely that you'll hit a valid space as time goes on
how are you moving the object
rigid.AddForce
and does the rigidbody have linear drag applied to it?
Not sure, do you mind me sending you the current movement script?
share it here !code
and also show your rigidbody's inspector
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
private void Update()
{
// Movement
float xDirection = Input.GetAxis("Horizontal");
float zDirection = Input.GetAxis("Vertical");
Vector3 moveDirection = transform.forward * zDirection * speed;
rigid.AddForce(moveDirection);
// Rotation
float rotationInput = Input.GetAxis("Horizontal");
float rotationAmount = rotationInput * rotationSpeed * Time.deltaTime;
transform.Rotate(0f, rotationAmount, 0f);
}
Yes, one moment
don't add force in Update. you should be doing that in FixedUpdate. also why are you getting the horizontal axis twice instead of using the value you got the first time that you didn't even bother doing anything with?
I wasn't yet working on the rotation part, I'll try to add it in fixedupdate, maybe that works.
Unless it's impulse but yeah.
It doesnt really move with fixed update:
void FixedUpdate()
{
// Movement
float xDirection = Input.GetAxis("Horizontal");
float zDirection = Input.GetAxis("Vertical");
Vector3 moveDirection = transform.forward * zDirection * speed;
rigid.AddForce(moveDirection);
// Rotation
float rotationAmount = xDirection * rotationSpeed * Time.deltaTime;
transform.Rotate(0f, rotationAmount, 0f);
}
in what way does it not work
It still rotates but it doesn't go forward
well how much force are you applying? What is speed?
FixedUpdate generally happens less often, so it is being called less
what is the value of speed and you still haven't bothered showing the rigidbody's inspector like i'd asked
the speed is 5
1 lb of force is really not going to move a 1kg object much when you consider friction is a factor too
I increased it, is there a variable I can change to make the object stop at lower speeds sliding?
Now it can move again by the way
you increase drag and/or friction to allow the object to come to a stop
then your object will continue sliding forever until it hits something
unless you are doing something elsewhere that stops it
how did you set friction to 0?
the average of 0 and non zero is non zero
this material would need to be on both objects
oh, I'll try it like that thanks
Perfect, now it doesn't stop which is what I wanted! Thank you both
I'll add drag to make it stop
Hi i get an error when i try to compile my game in Unity, and idk what could be wrong because i never changed the date on my pc
Product: ARM Compiler 5.04 for Nintendo
Component: ARM Compiler 5.04 update 5 Extended Maintenance (build 231)
Tool: armcc [4ce830]armcc : error C9555: License checkout for feature bsp_compiler5 with version 5.0201509 has been denied by Flex back-end. Error code: -88
System clock has been set back.
Feature: bsp_compiler5
License path: C:\Program Files (x86)\ARMCC_Nintendo_5\sw\info\nintendo-anyhost.lic;c:\program files\arm\licenses\license.dat;
FlexNet Licensing error:-88,309. System Error: 2 ""
For further information, refer to the FlexNet Licensing documentation,
available at "www.flexerasoftware.com".```
if you are using nintendo sdk we cannot help
that looks like something you should be asking about in the nintendo developer forums
:( sad
don't think they support the 3DS SDK anymore lol
that's why i'm asking here but if you can't help i understand
shit outta luck
they sure don't. but if you don't even have access to those forums then you shouldn't be using that sdk in the first place because that's piracy
Hey everyone. Dealing with a lots of world space canvases and i needed to disable backface culling.
Found a shader in the forums to do that.
It works great, but those elements can only be seen on the left eye in VR.
I'm a complete beginner when it comes to shaders though.
Could someone help me adjust this code so it works in VR on both eyes? I dont want to change Stereo Rendering Mode for Oculus since it works with default UI shaders too.
If possible (but not as urgent), i'd also like to be able to Mask the Ui Images that use Material of this shader.
I appreciate any help.
The code for the shader i used is too long to post here: https://pastebin.com/YLiAieh8
Source: https://forum.unity.com/threads/worldspace-canvas-backface-culling.310857/
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.
sadly i don't think they're even letting you get the SDK nowadays so that's pretty much the only way i found
but i understand i shouldn't talk about this here, so this conversation can end, thanks anyway ^^
Hey,
cant tell if this is "code" i mean it IS but still
How could i make this UI using HTML instead?
wdym HTML,
You can use RichText at most
if you want html-like you need new UIToolkit
Anyone can help me out with my problem please? I'm adding a value to an object in a canvas to set its height but it doesn't work at a different resolution.
is that paid? or in the package manager
UIToolkit is the new Unity system for UI , its free
check the docs pinned in #📲┃ui-ux to learn how to properly anchor and scale your UI
Thanks 🙂
ill look now
is probably more work to learn new ui thann it might be worth. Coud you explain what are you trying to do and why do you want html ?
i don't think uitk supports world space UI out of the box yet btw
ahh thats fkt
Well the Watch will display some player data like shows currently
(there will be more)
and HTML/CSS can create really nice UIs and animation so i was seeing if it was possible to use a UI System i already know rather than learning Unitys which seams more effort than itll produce
if you are really deadset on html/css you can probably find a webview asset
^this . Or also learn Unity UI which is not horrible to get some decent results
im not deadset no
i was just wondering as that ofc would have been the go too
damn so its old UI forced for me then?
For anything that is not extremely complex, UGUI is still a good enough solution.
yeah agreed
9-slice sprites will be your best friend
holy shit... big bucks in unity web browser huh..
If Android and iOS are what you care about, there is https://github.com/gree/unity-webview
Free and IIRC actively maintained.
honestly just use uGUI
But honestly just use UGUI.
lol
NOTE: This plugin overlays native WebView/WKWebView views over unity's rendering view and doesn't support those views in 3D.
So i guess no worldspace ?
yea im going to 😭
360$ for no world view is crazy
nah thats the one from the github
ahhh
I wouldnt be surpised if it used UGUI internally lol
The main issues with uGUI (at least for me) is the layout system and global styling
and performance ig
takes a decent amount of patience to get decent results yea
The GitHub one? That uses native OS WebView, definitely not UGUI.
oh meant the assetstore one
I've briefly looked into lots of UI solutions because the project in working on is very UI heavy (it's practically an app more than a game) and there's really not anything that's remotely close to modern frontend. WebView + web tech for frontend was one option but performance really tanks on mobile. I ended up building my own frontend framework on top of UGUI.
Hey has anyone run into this problem before? I am making an isometric tilemap with these blocks and as soon as i start using a new block it starts overlapping instead of falling in line like the grass blocks did. Any ideas why, i feel like im missing something obvious
make sure they are sorted by pivot point and pivot is correctly placed
those are sprites right?
yes
Looks like the stone "block" is up in the air compared to the others, the top-right edge does not align with the grass "blocks" ones
Ok i figured something out
this is my tile pallette
Everything to the left of the grass block goes above it but everything to the right goes below it
Im new to tilemapping so im not entirely sure how i would fix that
(Zoomed in view) Notice how the topmost corner doesn't align with the others
I would check the pivot sorting
But I would move that question to #🖼️┃2d-tools since it's off-topic for this channel
👍 thanks for the help
hey, what did we use for sending big codes in here ?
!code
📃 Large Code Blocks
Use 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 format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
thanks
https://gdl.space/zegidedoje.cs
hey i have this code for saving player data locally, it works normally on both android and the normal windows builds. but it doesnt work in the universal windows platform build that i made and published on microsoft store.
neither the load or the save functions work. does anyone know why ?
any errors?
If I remember correctly, UWP apps do not use the stuff in System.IO to access the file system, they have their own methods.
Also BinaryFormatter is unsafe and should not be used.
i would imagine UWP would not allow binaryformatter to work
do you know what they use ? if they have any other way to save locally
or do i have to just stick to only saving on my server ?
Regular apps not made with Unity use stuff like StorageFile, FileIO but this is only available in the Windows.Storage namespace, which Unity probably doesn't have by default
Each app has its own isolated storage space
you put debug mode on?
this is a code channel. but you need to put the inspector into debug mode to view those
expand the 3 dot menu in the upper right of the inspector window
is there a particular reason you need the instance id though? 🤔
that shouldn't be related to the instance id unless you are doing some weird stuff
level manager persist script
huh?
you should take a look at #854851968446365696 for what you should include when asking for help
but again, instance ids should be entirely irrelevant
Hi, I have a question about transform.LookAt. When I apply it to a plane it rotates it weirdly.
The first picture is how it should be (it is rotated like that in the editor), the second is how it is in play mode (it rotates it to the 0).
I'm trying to achieve the rotating sprites, think the original Doom objects
anyone know why my events aren't working with enemies spawned by an object pool? it seems like the enemy subscribes but does not call the function properly
where as my character who derives from the same class which setups up the event does work properly
the LookAt method makes the Z axis of an object point towards the other object. if that is a plane, then its Z axis will be along the plane not perpendicular to it
see #854851968446365696 for what to include when asking for help because without seeing relevant code we can only guess
Use Quad not Plane
Aaaa thank you, is there a way to force y axis rotation?
Quad is set up for this, Plane is not
i know man lol, im just asking if there are known issues with that regarding object pools. My code works fine
no, your code is the issue
Hello, for a university workshop I need to solve the following problem: Given a PLY file, using Matlab, obtain its vertices and faces in separate text files. Then, create a script in Unity that reads these text files and creates a mesh. I am aware that there are applications like Blender that can take a PLY file and convert it into an OBJ file which Unity can read. However, my professor wants the process as I mentioned. I have already written the script, but I do not know what the error is that prevents the mesh from being displayed correctly. The PLY file is a dental model. I am attaching a photo of the file, as well as the script code and what it looks like in Unity. I appreciate any help in advance.
transform.up = playerPos - myPos;
Thank you so much
i guess you could say that, but i think its rather im missing something when it comes to object pools
object pools don't do anything at all except pool objects. they have literally nothing to do with events or unity messages. your code is the issue.
how does it work in one case and not the other?
one problem with it, it's reversed, it's pointing the transparent side
lookat the opposite direction
i sent the wrong second link, fixed it
are the triangle indices in the file 1-indexed?
Yes, and in the code I already minus 1
I see
you create a new instance of the Stats object in SetEnemyDifficulty which will, of course, create a new instance of your event delegate so no methods are subscribed
mesh needs a 32 bit index buffer, you've apparently got 163k verts. There may be other problems but start with that one
strange cause I do the same thing for the player
i doubt that. unless you are subscribing to the event after the new instance is created on the player
it seems like you are just manually calling the StatChange method on the player
Okay okay, thank you <3
it is still reacting to the events
I just tested it
after you have called ResetToBase it cannot react to the events unless you are still referencing the old instance of the Stats object somewhere
the new one does not have anything subscribed to it
prove it
is this after ResetToBase has been called during this play session?
and what exactly am i seeing in that screenshot? because that doesn't show where any of this is happening in code
IT WORKS!!!! 
this still does not show that it is reacting to the change after ResetToBase has been called
resest to base is called when the player is spawned
do you mean in Awake? because Awake is before OnEnable
I am referring to the event being cleared after OnEnable has been called. because that is what is happening with your enemy
do you just not read anything being said to you?
i was responding to your first comment but okay
and this whole fucking time i've been talking about what happens when you create a new Stats object after you had already subscribed to the event. not before. that was the entire god damn point\
dont lose your temper man
then learn to read
Operator icon not found for: JACKAL at path: Assets/Siege/Operators/Icons/JACKAL
UnityEngine.Debug:LogWarning (object)
Watch:LoadOperatorIcon (string) (at Assets/Watch.cs:219)
Watch:AssignOperatorImages () (at Assets/Watch.cs:189)
Watch:Update () (at Assets/Watch.cs:93)
private Sprite LoadOperatorIcon(string operatorName)
{
string path = $"Assets/Siege/Operators/Icons/{operatorName}";
Sprite opIcon = Resources.Load<Sprite>(path);
if (opIcon == null)
{
Debug.LogWarning($"Operator icon not found for: {operatorName} at path: {path}");
}
return opIcon;
}
How can i load Images from that path as the Icon Exists there
you aren't using Resources.Load correctly https://docs.unity3d.com/ScriptReference/Resources.Load.html
Anyone some good ideas for implementing "furthest along the track" logic in a tower defense game? Since units can be displaced via knockback and slowing effects, I can't simply order them as the units are spawned onto the track. At the moment I'm just grabbing targets via overlap sphere which are in the tower radius and choosing the closest/furthest to the tower, so having more options would be nice.
I mean, I do have an idea what I need and it's taking the path they walk on and expanding it out into a linear distance and im not sure what tools I would go about that with
Ah, maybe sampling the navmesh a bit more
Yeah, I don't know. That seems quite expensive...
could you just check the navmeshagent's remainingDistance?
oh, huh that's distance of the path and not the point?
"NavMeshAgent.GetPathRemainingDistance(). Be aware though this can be performance expensive depending the situation, so have that in mind when using it."
I assume it does the same corner/face calculations
where did that info come from? because as far as i can see there is no GetPathRemainingDistance method
Reading some stackoverflow post, but it's a little outdated
oh, it's their own custom method, ok yeah they do similar to another post
Let me try it out though and see how it goes, otherwise maybe I can segment the levels out instead and compare by that.
it's more that I have like 100+ enemies bunched up at times with quite a few towers pelting them
Maybe you can find info on how btd6 does it, not sure if that info is out there. It is made using unity, and there is a decent modding community.
pretty sure even the earlier versions had it. Freaking flash games mastered it
probably not expensive as I'm probably thinking, but I do also spawn like 500 projectiles everywhere too
and I know btd6 does frame drop like crazy eventually
Yea it is, but btd6 also let's you get way further than previous games like btd5
Super late game isnt playable, to the point where people remove towers that shoot a lot just to play faster. It lags so badly that the extra dps makes it play slower
haha, gotta keep that original experience as if you were playing in flash
webgl pretty impressive though and that's kinda what I'm trying to get working
Some quick thoughts of different approaches
Create a path that they follow and track percentage complete.. This might be handy for picking the best in a group. But dont loop through every balloon
split the tracks into pieces and order the pieces in distance along the track, grab the one that is occupied and farthest. Then you can determine actuall target from all balloons inside that section. Basically Spatial Partitioning
Yeah, the percentage idea is what I'm thinking here and trying to figure out if I can just grab that info directly from the navmesh. But, I don't think I can go about not recalculating a new path every time a unit gets displaced, so comparing back the waypoints generated probably isn't possible. Sooo, I need to kinda make my own fixed waypoints that each unit needs to compare to.
If it’s like bloons you don’t need a navmesh, they are all just following a line
Right, mines a bit more 3D-ish instead of the typical on-rails
Yeah, I think that's the idea, segment the track into way points and calculate the distance from the unit to the waypoint and compare against that.
you do that benchmarking, mao?
mostly want to know if I can just take down that file yet, to keep my repo tidy
yeah kinda, need to chop a lot more physic calls down and merge them into distance calls
Separate note: I made a small class to house localized string objects.
https://github.com/LoupAndSnoop/UnityRepositories/blob/main/LocalizedString.cs
any feedback?
Pretty neat, throw it into #1179447338188673034 or dev logs.
Why'd take the repos down? I cram as much as possible in mine just so it looks like I've some interesting stuff going on lmao
it's not even functional code by itself lmao
I just threw up some functions from a gigantic, dirty class that won't be useful to anyone in a public repo
depends on a ton of crap not in the repo
Anyone know of any videos about the actual function of "Unity Code Assist Lite" Extension for VS?
? are you trolling? what is going on here
mao is talking about other code I put up in the middle of the day
the repo I just linked is fully functional
it has a dependency, btw. so go here #1219781801900249148 message
hello, does anyone know if we can use photon engine with unity visual scripting or it's only in c# ?
Ah. thanks for the clarification
2 second search
https://forum.photonengine.com/discussion/20627/how-can-i-use-photon-with-visual-scripting-tool-bolt
So, since Visual Scripting is what used to be called Bolt, it should work, right?
ty i'm stupide i was chearching in frensh ty :D