#archived-code-advanced
1 messages ยท Page 187 of 1
@grim oxide So, the only problem with the way you're describing doing it is (and this is more of a "domain" question - like, does your game behave this way, which it might) is that you're implying you'll never have instances of your items
ItemState is an instance
It has a reference to an ItemData which is a static scriptable object that defines what items can actually be
ItemState is an object that describes stuff like durability and such, actual per-item state
OK, so... why do you want a ref to it? In my current project.. maybe 100k lines by now? I can count on one hand the instances of ref i have in the codebase
I don't apparently, I'm not clear on what ref is for
I don't know what it would even mean to pass an int by reference lol
I think my question may have been misunderstood
Like I can pass an int by reference to some other area of code, then change that parameter and it changes the original int? How can that even work without a wrapper or special definition of the original type? 
it means the int isn't copied in, instead you pass the integer variable reference in. So any modification will modify the original variable as well
I thought that was definitionally impossible for value types ๐ค
1 instance in my blazor app, 8 in an imported library, 3 in my own codebase, 2 of which were commented out and one which... i don't think I'm even using
Is it wrapping it for me behind the scenes?
Yeah, unless you pass by ref
It's not impossible, but it's not really a great idea
If you start tying up your codebase with ref you're going to .. potentially have a bad time knowing which data is a copy and which is a reference
Not really, instead of passing "5" you're passing the memory address to the variable that holds 5
ref isnโt a bad thing, not sure where that idea comes from. Itโs not common sure but itโs not bad.
I'm pretty sure it's bad ๐
Yeah so like.. again, I don't think you're applying the pattern "FSM" correctly to equipping inventory... I'm sorry to be blunt, but I just don't think a relationship between an inventory slot and an item is inherently stateful .. it's a relationship between things
It smells bad
It's not bad, it's just.. you need to know where you're using it
Btw in terms of performance, anything larger than 4 bytes passing by ref is much faster and takes up less stack.
@misty glade I think you are just confused on the details of how i have it implemented, I'm not sure what you even mean
I'm not at all confused.. I see how you're implementing it with your getter/setter...
Itโs actually a very common performance optimization to do when passing large structs.
But thatโs kind of a side topic.
And again, I don't think you're really listening to my answer.. if you made a Dict with a key of the slot and a value of the item, you could have an arbitrarily large number of slots with almost (maybe no?) code addition
And then when the object is serialized I have to manually serialize the dict
If your character suddenly has head/shoulders/neck/left arm/right arm/left leg/right leg/left foot/right foot/ring finger 1 etc.etc...
imagine if you've copied and pasted that code for all those slots
I can just do it with a list, with indices
then you find a bug...
Yes of course that's why I am seeking alterantives before I resort to a collection or wrapper
List with indices by the enum type is ugly IMO
Dictionary is a no go due to serialization needs
But list with indices by enum type is probably fine just ugly
You can easily serialize a dict in to 2 arrays though
Yea
i don't really know what the serialization issue is, but ... a dictionary is a list with enum indicies, basically
Ease isn't the issue, I'm trying to find the best/cleanest answer
I mean, sort of, but it seems to be the right data structure for your issue..
All of these solutions are easy ๐
The dictionary one requieres an interface and some extra methods and boilerplate
And it can't be assigned in inspector anymore
Inspector assignment of slots is a requirement
Doing with list is gonna suck for that too but
Functional at least
You'd need to provide a slightly different API surface instead of setting the item via a property, but .. I don't see that as a bad thing.. your consumers shouldn't be concerned with the underlying data, they should just be able to call Dude.Equip(item, slot); and it just works.. not having to remember how the property for the Dude.Foot works
โ๏ธ what about this
This is why I was avoiding a collection in the first place
Now of course I could make a custom editor 
This is for some kind of inventory right?
ItemState is an object that has a reference to a ScriptableObject ItemData, ItemState has stuff like durability
ItemData defines what the item is
What is ItemState, normal c# object?
Yes, [Serializable]
Tying items to whole gameobjects seemed really insane
For ones that are stored
Would it be possible for you to use the ItemData directly?
You can create a ScriptableObject instance at runtime
What do you mean exactly, it's free to view for anyone with a reference to the ItemState

Go on...
So my idea is that you just make a ScriptableObject reference for your editor
Then when the game starts you create an instance of the SO and use that, you could even reassign the field if you want to
I mean, you can still have the items assignable in your editor if that's a requirement... you'd just denormalize a reference to the field you want
You mean like have some serializable fields excluslively for the inspector that populate the slots on Awake or so?
private Dictionary<SlotType, EquippedItem> EquippedItems = ...;
public EquippedItem FootItem => EquippedItems[FootSlot];
I thought of this also but of course still feels a bit cluttery
Yeah something like this
if you want a serializable dictionary get one from odin
Come to think of it, this is probably the best answer anyways because this way I can just assign ItemDatas instead of ItemStates
Things-spawning-with-items don't need those items to have unique state on spawn
The generic initial state is fine
Hey Dr. P: UniRX revisited.. I opted out of it, managing state manually and popping queued states off as the turns come in, and it's actually turned out tolerable.. soo.. !remindme 1 year to check in on how much I hate/love life without RX. ๐
@undone coral - sequential animations, multiplayer
looks great
(this would obviously be ideal for rx but.. I have to spend more time breaking my dino-brain out of the old way of doing things)
no it's okay
this has good mobile game energy
do you really need to see the opponent's board? is that what's being visualized?
in the gray grid?
it's not super simple though, but.. the way it works .. "works". Basically I copy the ENTIRE battle state, push it onto a queue, modify the real one instantly (as the networking messages come in) and the animation/UI sniffs the queue, peeks and pops and modifies a fake copy of the state as slowly as it wants to, and when it's done, compares that "new" state against the copied state, and if they're identical, discards the new one
yeah - there's abilities that do things like steal "drones" from the enemy grid, etc. The intent is a strategy game centered around your crew's abilities, which all do different wacky things .. blow up enemy drones, your own drones, upgrade them, whatever
yeah - forgive the developer art obviously.. we're hoping to hire an artist this week
that gray grid is the only thing that's breaking "Rules of Mobile Games" for me (#1 only 1 screen)
but like i said, this is probably a great application for RX but.. I just couldn't take the dive
what's that rule..?
(layout is just mockup for now.. I'm more concerned with the networking/game functionality/etc)
you can go through apple arcade games
that are fun
and the apple design award winners made in unity
and especially multiplayer PvP games on mobile, which are very few in number
and they all take place on "one screen"
like you don't scroll around, and you don't toggle between windows or look at some kind of expanded view of your "board"
and when you do it really kills the vibe
ah, gotcha
I'll mention it to our UIUX guy.. we tried cramming it all on one screen and it was pretty sloppy feeling
you'd have to make it less important from a gameplay perspective somehow
which i'm not sure is possible
I think maybe we can have a goal of most of the gameplay for an experienced player all happening on one screen (ie, no popup to "use" the active ability as we have it now).. i'm still working on a redo of my progress bar prefab so .. HP, cooldowns, etc will be shown on the screen and not require popups to see
i'm getting some puzzle fighter vibes from what i see in the current gameplay
yeah
(not mine)
I have a talented game designer that I work with, have maybe fed in 5% of the design myself
music guy is pretty talented too.. he's got this whole "space cowboy" thing going on which i love
sick
@misty glade meant to ask--you mentioned FSM--is the term "state" only appropriate in the context of an FSM? All along I've just been using it as a generic term for "stuff that varies", i.e. "The current state of this object" 
Hey so if ive used bitconverter to do this
uint a = System.BitConverter.ToUInt32(System.BitConverter.GetBytes(e.x), 0);
where e is a vector3
How do I then go from a to get back to e.x?
I assume with this: https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter.uint32bitstosingle?view=net-6.0
error
'BitConverter' does not contain a definition for 'UInt32BitsToSingle'
ended up having to dive into the code of the bitconverter itself on microsofts github and recreate it, but that means requiring unsafe code to compile which I would rather not have to require others to do who use this
so im lookin for another solution that doesnt require unsafe code
Typically a FSM means .. something that has a fixed number of states, and typically can only go between those states in specific ways. An example might be a network connection. You'd have states like Disconnected and AttemptingToConnect and WaitingToRetry and Connected, with logic that determines how to get between those states, and other logic that says "OK we can't send data unless we're in state == NetworkStates.Connected" or whatever.
State typically doesn't mean the value you place in a variable here, which is how you were using that term.. No big deal, but within the programming world the word "State" carries the implication of a finite state machine (more info here: https://refactoring.guru/design-patterns/state and as an aside, this website is fantastic for design patterns, which you may or may not know already).
Design patterns aren't important to learn, but they tend to be the de facto language to communicate higher order problems effectively. You'll find that over time you just sort of naturally encounter them, and the more patterns you know, the better you'll be able to solve them.
Your problem is not an FSM, your problem was more of an API issue - how can you design the API for Unity's editor to consume so that you can edit your data via Unity while maintaining/minimizing de/serialization complexity. PB suggested Odin as a plugin so you can see your Dictionary or whatever other System.Collections.Generic you use to describe your data, and I suggested that you "denormalize" your access to an underlying data structure with property getters that access the elements directly: either solutions will work. But you're definitely dangerously close (if not already over the line) for abusing the DRY principle - which will make your code far smellier or outright impossible to maintain if you have any meaningful number of inventory slots.
I work pretty hard myself at avoiding abusing DRY - and if it's a problem, you can always extend your public interface to call a better underlying private method. Example - I had these two animation methods that were almost identical. Animate an "attack field" and animate an "attack crew". Shortly after I had both working, I literally rewrote them into one private method so that I would only ever need to fix bugs in one place. There's only one "animate attack" method, and so the API surface remains the same, but under the hood there's one method:
// before
public IEnumerator AnimateAttackField(DroneIcon defendingDrone) { .. huge block of code ... }
public IEnumerator AnimateAttackCrew(bool isOpponentAttacked) { .. another almost identical block of code ... }
// after
public IEnumerator AnimateAttackField(DroneIcon defendingDrone)
{
yield return AnimateAttack(defendingDrone, false, false);
}
public IEnumerator AnimateAttackCrew(bool isOpponentAttacked)
{
yield return AnimateAttack(null, true, isOpponentAttacked);
}
private IEnumerator AnimateAttack(DroneIcon defendingDrone, bool isCrewAttacked, bool isOpponentCrewAttacked) { .. huger block of code, but only one ... }
Anything calling this object still calls it "the same way" (either AnimateAttackField() or AnimateAttackCrew() with only the params they care about), but the underlying animation only happens in one place so .. any bugs are easy to find, only ever have to be fixed once, etc.
Polymorphic deserialization.
Polymorphic deserialization.
Polymorphic deserialization.
I keep running into this exact problem over and over and over while using Unity. Surely there's a standard for this? A way to compose your behavior structures from within the editor that does not require spawning entire new GameObjects?
Say you have a turret component. This component allows for you to select whatever kind of targeting behavior you want without having to explicitly know what that behavior is. All it does is ask another class "Hey, what's my target?"
Cool. Put whatever ITurretTargeter class you want into a field or on the object as a component. No problem.
Now change the behavior on the fly. How do you swap out the behavior?
Easy. You write a script that constructs the new behavior and slots it into the field.
Alright, now make it so that you can specify which behavior you want from the editor.
...How?
On top of that, these behaviors have different sets of fields, too. How do you store that data?
State typically doesn't mean the value you place in a variable here, which is how you were using that term.. No big deal, but within the programming world the word "State" carries the implication of a finite state machine
I don't think this is correct. After I asked the question I looked around and it seems my definition is correct and FSM is not at all implied by the usage of state? ๐ค
In information technology and computer science, a system is described as stateful if it is designed to remember preceding events or user interactions; the remembered information is called the state of the system.
The set of states a system can occupy is known as its state space. In a discrete system, the state space is countable and often finite...
Similarly, a computer program stores data in variables, which represent storage locations in the computer's memory. The contents of these memory locations, at any given point in the program's execution, is called the program's state.[5][6][7]
No offense, I know you are trying to be helpful, but you go a bit overboard in your responses asserting beliefs you hold that are not accurate and answering questions that were not asked. It was a bit confusing and a little condescending
I'm not entirely clear on your situation but isn't this a bit of overengineering? Does your turret targeting code need to be that generic? How many different targeting behaviors will there ever actually be in practice? ๐ค
This is something I struggle with myself because I simply love to overengineer stuff like that
So YMMV
Assume it's a lot. This is a fake scenario.
Oh I see
I can't really picture such a case in a video game tbh
Even like a RTS with all sorts of different units...
(i'm not saying it doesn't exist I'm saying my own experience as a dev/gamer is failing to picture it)
Alright, how about a real scenario.
I have a bunch of objects all responsible for procedurally generating GameObjects. They each pull from their own set of prefabs that are stored in a ScriptableObject.
They also store information about the frequency of generation, and have two interface type fields. One controls where the object is put on the Y axis (On the floor, a certain distance above the floor, a random Y value in worldspace) and one controls which prefab gets selected (At random, in sequence, in a random sequence)
And as the game goes on, all these parameters change.
Every time I've caught myself setting up an interface in unity I've realized I was overdoing it and wound it back
Ok lemme read this carefully ๐
I want to store the way objects generate in a plains biome, a desert biome, a mountain biome, ect.
Plus, I want to generate all these generators at the start of the game, so that I can provide easy access to the generators for other scripts to change them dynamically or fetch information.

I'm probably wasting your time by asking clarifying questions because it's actually becoming less clear lol. I eagerly await the answer from someone smarter than me ๐
I'm having trouble picturing what exactly you're doing and what problem is arising ๐ค
You have generators being generated? 
Like the parameters on the generator itself, that it uses to randomize, are randomized? So the results of a given generator are more consistent within an instance of a biome?
Not necessarily randomized. I do have concrete data that I want to plug into them. But they do change based on the state of the game.
Another scenario that's a little easier to understand:
A dialogue system. Each piece of dialogue can do a number of things. Shake the screen, automatically skip to the next line, slow down for a section, rainbow text, whatever. I know now that the best solution for this particular problem is to put the entire thing into a serialized text file, and just perform different methods based on what's encountered, but it's a good example of where I run into this sort of problem.

Can I
Make a single class YPicker class with an enum that tells it how to respond to Y requests, and mash every behavior into its own function?
Is that maintainable?
Wait, no because data.
One alternate way (not necessarily better) is that you have a gameobject with a list as a field. On the list, you have checkboxes to make the individual elements either display text, shake the screen, or rainbow text (etc.). Keep pressing the + button to add a new event. Then have the script go through them.
Note that you need to mark the class representing the element as "Serializable"
Yeah, but different behaviors require different kinds of data. Rainbow text needs a frequency, shake the screen needs an amplitude and duration, slowing down requires a speed, ect. You can't put polymorphic data into a list field and still edit it from the inspector.
Do you just want a factory to take a type name instantiate an object?
I was describing a list where each "polymorphic type" would just be the same type, just with different relevant fields. Again, not necessarily good.
Although you might be able to do polymorphism properly with a custom editor.
That's certainly one problem, yes.
Reflection is an imperfect solution, as I've been told it does not work with WebGL, which I'm currently working with.
Yes, in a pure concept, this is what "state" means, but in the conversational context (especially if you use the word "state" when describing a problem in the #archived-code-advanced channel), I'm going to (and did) assume you meant some sort of FSM and was confused when your question didn't match the words you used. I'm not sure that it matters what definition you think of when you think of "what value is stored in a variable", but I certainly would rarely/never use "state" to mean something that didn't mean state in an FSM, which is why I went on at length about it.
As far as "answering what wasn't asked".. I went on for a bit about DRY because you said yourself:
Billy Gamba: Here's the feet slot, for instance. This code is identical in the other slots, but for _slotFeet being a different backing field
... which is where I thought you were going: "how" do I solve this problem and reduce the duplicated code, versus what I thought the question should be, which is "why" this is so important to generalize. And I like to ramble.
Sorry if it came off as condescending - I was attempting to match my explanation to your experience in programming that I perceived based on how you described your problem. (seriously - that wasn't a passive-aggressive apology) - It's hard to read where someone's at knowledge-wise and how you answer a question can either go straight over someone's head or come off as condescending if you miss the mark, which I clearly did.
Nah. I hear state talked about by OOP vs functional programming people way more than I hear it talked about in terms of FSM.
๐คทโโ๏ธ Anyone can use any words they want, really. ๐ I have what I think of as "state" or "stateful" and other people have (and can have) a different opinion on what that means, and that's OK, so long as both parties understand what the other is talking about, and if not, well, Use More Word
blast from the past, there
The ideal here is that creating a new behavior is as simple as creating a new behavior, even if that behavior needs to implement something to make it work with the polymorphic deserializer. Touching other classes would crush maintainability.
if you have a reference to an interface, can't you create a serializable object that derives it with whatever data you want?
The object that references the serializable object cannot be fully serialized, because it doesn't know what that object is.
And I'm sorry if I'm coming to the convo late - why aren't you just making a prefab "generator" singleton (or prefab itself, doesn't matter) that has some configuration information it can read (smartly by "looking around" - ie, biome; or dumbly by telling it specifically what to generate), plopping it in your scene and letting it go to town? The prefab generator could Instantiate() these things however you see fit - drawing them from a SO, having prefabs linked to it in some sort of lightweight object that contains the configuration AND the prefab, or whatever other solution
This is exactly what I'm doing. The problem itself is the configuration information.
Stuffing that information into a bunch of things with inconsistent data structures between each other.
Will all of the possible subclasses be known at compile time? Or will some of them rely upon loading a DLL or something?
They're definitely known at compile time.
Without reflection, though, I can't store any information about those types automatically.
interface IX {}
class A : ScriptableObject { public IX x; }
class B : IX, ScriptableObject {}
are you talking about unity editor-time serialisation, or runtime serialisation?
Anything that gets data into the program without recompilation.
So basically, if it's not written in C#, it's golden.
so, custom runtime serialisation?
Ahhhh wait you want to NEVER write any C#?
Ah okay.
This is kind of the point of the Unity editor. It allows editing of serialized assets outside of C#. Whether or not those assets get lumped into the game files or stored in their normal serialized format after being built isn't my concern (for now.)
public enum EVisualNovelEventType
{
Text = 0,
Animation = 1,
Splash = 2
}
// Write a custom editor.
public class VisualNovelEvent
{
public EVisualNovelEventType eventType;
public string textToDisplay;
public VnAnimation animationToPlay;
public VnSplash splashToDo;
}
public class MyComponent : MonoBehaviour
{
public List<VisualNovelEvent> myEvents;
}
``` ... is a crappy, brittle way of doing it.
Which is exactly what I'm trying to avoid.
are you saying using the editor not acceptable because you need to rebuild to make changes?
I'm saying using the editor is preferred because I won't have to recompile to make changes.
Or edit an existing class.
ok, but you are saying the editor can't deserialise an object that you reference from an interface?
I mean, that's certainly true, and would be a method of solving this problem if it was possible.
and to clarify, webgl is AOT, you can use reflection, just nothing dynamic
you can definitely use interfaces to reference objects in the editor
public class TurretController : MonoBehaviour {
[SerializeReference] public ITurretTargeter targeter;
}
why aren't you just using [Serialize]?
Well, for one thing, there is no [Serialize].
Using [SerializeField], though, gets you this:
sorry, yes, [SerializeField]
Yeah I just saw this as abledbody mentioned [SerializeReference]. https://medium.com/@trepala.aleksander/serializereference-in-unity-b4ee10274f48. Neat.
so that says you can't use [SerializeReference] with MonoBehaviour or ScriptableObject
You can't use them to (de)serialize MonoBehaviour or ScriptableObject.
You can use them as fields on MonoBehaviour or ScriptableObjects.
Yeah, so with some work that could be used to create plain classes that are embedded in the edited object
You can do that with a normal field using [System.Serializable]
It seems like you may need a custom property drawer to support the interface
since it's in the editor you can use whatever reflection you want
Oo, editor only reflection.
I am certain we use interfaces like that so I'm trying to find if we're using a special property drawer or something
what unity version btw?
2020.3.32f1
i don't think pooperty drawers support interfaces by default
"just use odin"
i'm not a fan of serializereference
Any guides on how to implement my custom version of smart strings? More specifically, I want to implement the usage of code inside the text. I.e: {CustomClass.CalculateValue} should actually call the method/property
Not sure what a smart string is. Any reason you can't use string.Format()?
Isn't smart strings a python thing? .. googling..
i might be thinking of smart enums or something else
I could, but that means that for every keyword that I needed to replace, I'd have to add a specific handler for that
Oh, sorry, that's uh.. built into C# then
prefix your string with $
(Is that what you mean?)
I can't
The string comes from a TextAsset
For instance, a text could be "You have {Player.HP} HP and {GameManager.Currency} Coins"
Ahhh. That explains it.
ohhhhhhhhh you're saying the actual string value has some code that you need to parse and/or execute
Exactly
Wouldn't the existence of $ imply there's a system type for smart strings?
Yeah, I dunno off the top of my head. I'd probably start by rolling my own, get frustrated and then google up a solution someone else has done. ๐
Sounds like what you want is a "tokenizer" @split sundial
Think that's the term you're after
It's a deep rabbit hole
Hmm, I'd say you're right :P
Yeah uh.. what's the use case here, anyway? Like, why does the text have {} with "code" in it?
(seems like a vulnerability nightmare)
Basically, you just need to find ways to make "tokens" out of those bits you want to replace, then find and replace them. Google some implementations of tokenizers for ideas
Yeah, I can imagine it being very similar to a Lexer
A lexer is a part of the code of a compiler, that is essentially responsible for performing the lexical analysis of the code that was written
Now that you mentioned the tokenizer, it is actually very similar to what I'm trying to do
Lexers and tokenizers are the same thing.
Lexers turn text into tokens.
Tokens get used by a parser to create useful information from syntactic structure.
Tokens are instances of lexemes specified in a lexicon.
not sure why they came up so much, when compiling for zaurus, on gcc 2.95
didn't we discuss this?
SmartFormat / handlebars templaters do this
smartformat comes with the unity localization package
Partially, but I wasn't really able to solve my problem
You mean, the libraries?
SmartFormat looks pretty sweet
Isn't this possible with reflection?
Yes, but screw all that imo
Assuming we're just checking for field/property/etc names?
Thanks a lot, those libraries seem to do exactly what I need
@undone coral Docs/wiki are kinda short. What kinds of useful stuff can you do with it?
Yes, but reflection is hella slow
Oh sure but maybe you could just do it once, up front ๐ค
Rather
Parse the text code once
Yeah, but I need to use values that constanly update
Yeah you just build a function out of what the text says at the start
And then call that function every update
Rather than every update parsing the "text code" again
Like currency (in my game, it might update even every frame)
If it's every frame, then you'd want something that doesn't GCAlloc, too.
you can make custom tag in TextMeshPro. google that up
without custom tag, you can hack your way with the built-in <link> tag
Hi. Architecture question. I have a scene with NPCs. roaming around. I have a CCTV system that show video from each NPC. The CCTV show also the stats of each NPC. I can also select NPC through the real world and through the CCTV. I have a NPCs manager (songelton) that stores all the NPCs.
How would you suggest I architect such a system? How to communicate with the CTV system (back and forth)?
raycast from cctv to get info or want to interact with that NPC
Hello, i'm trying to use Physics2D.RaycastAll to get a list of all colliders in contact with the ray ordered by contact distance. The problem is when a collider is completly crossed by the ray. I would like to get the distance of the "contact enter point" and the "contact exit point". Is it possible to get this info ?
Is it possible to convert a binary data to a int or text?
Don't cross-post
hi guys i am having problem with unity ads when i click on the button the add display but when i close it or skip it it again takes me to the screen where i have click on the button
hey guys, this is quite specific i know but would anyone have a single idea on how to make backrooms-style procedural generation? haven't got the slightest clue and all the help ive got are a few vague pointers like 'create access points'
would be very useful if someone knew, but of course i understand this is quite specific
In my 2D game, I'm trying to rotate a point using this code:
Vector2 targetPosition = new Vector2(currentPosition.x, currentPosition.y + 5f);
targetPosition = Quaternion.AngleAxis(90, new Vector3(currentPosition.x, currentPosition.y, 1)) * targetPosition;
Debug.DrawLine(currentPosition, targetPosition, Color.white, 50.0f);
I can see a line rotated around 70ยฐ and not 90ยฐ. Could you please tell me what is wrong ?
anyone knows how to make game asset responsive to the different screen sizes in unity
Don't cross-post. 3 times.
sorry
the rotation you did is local, not world
the axis you are using is a surprise
a lot of what you're doing doesn't make sense
what is your goal?
do you mean to rotate about the z axis?
backrooms style?
Yes I want to rotate around the z axis, because it's a 2D game
yes, generation similair to that of the backrooms (level 0 to be exact)
Is it better performance-wise to have the local variable outside the while loop or inside? it will be updated always in the while anyway but im not sure if every loop its being reassigned on the memory or not ```cs
private IEnumerator Timer(int seconds)
{
TimeSpan ts;
WaitForSecondsRealtime second = new(tickRate);
while (enabled && seconds >= 0)
{
ts = TimeSpan.FromSeconds(seconds);```
I have a small compass needle Ui image that I want to rotate on the Local Z axis, to point towards a specific transform.position based on the position of the player
I dont know where to start or what to even search online to find the answer
๐ค Smells like a trig problem
I don't know trig, I phone my math nerd dad for all the trig questions 
Yeah I think i found some answers online they all use atan2, some use quaternions but I cant seem to adapt it to work for my situation (pointing the needle from the player to the target object on local Z)
So... first, this type of optimization, if it even did something, would be relevant on the, like, nanosecond timescale. If it did anything, it would probably be hundreds of thousands of times smaller than your actual problem.
That said, I tried the following code in a dotnet IL inspector, and the method bodies compiled identically, so the CPU will run the same instructions in either situation (unless I made a mistake somewhere).
It makes sense, though. CPUs don't have loops or scope. They have strings of instructions, and jump around in memory between them.
well my logic behind putting the variable outside the loop is that it gets generated into the memory, right?
and when it ends on the body, it gets removed
so logically speaking if the variable is created inside the loop, it will constantly put and remove iti n the memory; right?>
every time it loops back in the while body
If this was C++ and it had a non-trivial destruction, then different constructors would be called, yes.
Er... is that the case? Hmm. Nah. It is. One would necessarily copy-assign I think.
so me putting it outside the loop is the right way then?
No
๐ค
This is not C++ (where someone can put weird side-effects in their code that may or may not be elided by the compiler). This is C#. The IL produced is identical.
so i can safely put it inside and save a line
Putting it outside of the loop is definitely not incorrect and seems more logical for me.
^
More logical for me inside the loop unless you needed it outside the loop because you needed it in a different scope.
Why give yourself more places to screw up.
i mean going 2 + 2 + 2 is hardly an easy thing to screw up
its a tiny code
and it looks more logical to me
This is correct
Putting at a higher scope strongly communicates to the reader that it's needed in that scope (but it's obviously not)
It's very wrong
thats not the reason for putting it outside though
its a IEnumerator with a while loop
would u still put the actual variable inside the while loop, or have it "created" once outside at the start o the IEnumerator
Oh that's a different question
private IEnumerator Timer(int seconds)
{
TimeSpan ts;
WaitForSecondsRealtime second = new(tickRate);
while (enabled && seconds >= 0)
{
ts = TimeSpan.FromSeconds(seconds);```
i put ts outside so it doesnt get "created" every new loop; i assume its a correct way
I'm assuming that when the function is re-entered that the stack frame would need to be setup identically.
Yeah that's not how that works
Every time you do TimeSpan.FromSeconds it gets "created" in the way you are thinking
idk , sounds logical
but no like
you know how a variable gets a memory assigned to it, right?
The position of the declaration is not changing anything
The main point that I was trying to say is that this would be on the order of nanoseconds (modifying the stack) if the compiler even did diverge in instructions anyway.
You're worried about the speed at which the declaration is done?
A struct local is stack-allocated.
You need to write good, readable code first, and worry about nanoseconds of performance second
but does it get removed and readded each loop if its inside the while ?
instead of just the value changed
The interpreter probably makes it the same anyways
Unless we're talking omega-hot code you should prioritize readability/form
hmm
Just imagine if you were declaring every single loop variable on the outside, in all of your code, forever
It's just messy and looks weird
that kind of logic still confuses me
And oftentimes will result in those variables persisting longer than they should
thats eventually going to start adding up
0.0000000001 * 100000 is still a very small number
heh
What will add up more is the extra dev time negotiating with weirdly written code
The IEnumerable is a heap object. Each time you access it, assuming it's a cold memory fetch, is on the order of ~200 cycles.
hey, i like knowing whats exactly going on in there
So just starting the function is like 100ns.
When you exit the loop, ts is still held--why? Do you need it?
If not, it shouldn't be held
when i exit the loop, the function ends at the same frame
For now
i use the IEnumerator as a start, loop, and end
"The function will end and clean up my mess" is not a good reason to make a mess ๐
start is before while, end is after
both will run once
while its looping its going to be using it constantly
So in practice we're talking about a minor mess to begin with. It's unlikely to cause an issue, because the person who could mess with it would necessarily need to be messing with the internals of that function.
Yes in this particular case it's "harmless"
But reinforcing bad habits is never harmless ๐
But, that said, declaring inside is defensive against random person being like "Hey I did something, but then you changed this other thing. Fix it."
Why did they do that? Because you didn't stop them.
Because with enough users, any perceivable aspect of your system will be depended upon by someone.
(That's a Google C++ team thing btw https://www.hyrumslaw.com/)
cant deny google team makes stuff that work
they have performance issues though ๐
But yeah chances of someone relying upon the location of a local variable is very very very small lol.
fair enough; guess ill just put it in the while loop and save a line of code
I can point to some good Google software. I can point to some fast Google software. I can point to some bad Google software. I can point to some slow Google software. I can point in like a thousand different directions.
Guys how do I do this functionality? If I have both App X and Y(owned by me) how do I let users in App X when they purchase an event on a calendar day, recieve a link that will allow to them to enter the event on App Y on that specific date? What is this functionality concept called?
@low cove my name please so I don't miss it as there are many chats in here.
readability and simplicity it is then 
@paper fiber You will need to specify platform(s). You could be talking about deep links, universal links, custom protocols, etc.
mobile deep linking: https://en.wikipedia.org/wiki/Mobile_deep_linking
Actually one funny example -- I've helped out the Yandere Simulator guy in the past, and there's countless YouTube videos of people (who have no idea what they're doing) claiming that a very long update function is the cause of the performance slowdowns. If you actually profile it, though, all 100-ish calls of that function per frame (once per NPC) sum up to less than a millisecond, and most of that is blocking calls into physics and animation.
People will then counter with like "But if I delete all the NPC it gets faster" and it's like yeah you just deleted a few thousands bones animated with the legacy animation system, a few hundred physics objects, a few hundred rendered meshes...
lmao
Like -- we're not stupid we can look at the profiler and see what the actual problem is lol.
have u seen the yandere simulator code? its disgusting xD
even i wasnt taht bad in the first few years of programming
I've seen it, yes. YandereDev is using my GitHub.
I've helped him out with a handful of things, but it's difficult when everything I do needs to stop his progress, and I worked full-time on other stuff.
Yup.
I haven't touched it in about 2 years... I started my covid layoff helping him out (as well as a couple other groups). My involvement kind of diminished since then. I still maintain the most recent launcher.
i see
so u actually helping him after ive seen the code
hopefully its better now ๐
In terms of performance? Was never a problem.
no in readability and stuff
Yeah he's aware that it's difficult to change.
from what i remember there was just lines upon line sof duplicate codes one after another with a tiny difference
crazy
I mean it's by far not the worst code that I've seen lol.
i bet my gui code is worse back from 2010
new Rect on every new UI element ๐
in the OnGUI method*
It is what it is. Ideally systems would be made with these things in mind:
- readability
- easy to change
- easy to write cleanly
... in that order.
That order because you're going to need to understand it much more than you'll need to touch it, and chances are writing it once is not a significant amount of time.
i just write the code as best as possible in terms of flexibility and performance
that way when im done with it i just dont need to touch it anymore
like this clock im making 
get some Action variables in case i want to hook it up to things, and thats it
so specify the axis of rotation as Vector3.forward for AngleAxis
a quaternion * a SPACE space vector is always a SPACE rotation (so world space if it's a world vector, local if it's local, whatever if it's whatever)
does that make sense?
Possibliy? basically its a link that will given to user X on App Y. So that on the date of event starting, the user is able to be there.
so is that Deep links?
@blissful sedge me so I could see
this is clunky. also, don't reinvent "utilities for coroutines"
that exists
if you want a library of helpful utilities for coroutines, really async methods, use unitask
this particular implementation may be flawed. it's not clear if after setting enabled = false, you will get 0 or 1 additional executions of the effect of the timer
im confused what u mean by utilities for coroutines
hmm...
well you're writing something called Timer
ive tested the timer, seems to work correctly
it sounds like you both want a general purpose timer or... not
its this
hmm
theres 6 separate digits
the implementation will be flawed
well i haven't seen all the code yet
well hmm
it depends on what interacts with the timer
here let me put it out in pastebin
well im happy with the clock, but the timer and stopwatch methods are very stiff...
A tool for sharing your source code with the world!
each digit has the SlideDigit class which does the position calculation and movement
@undone coral i was going transition the other 2 methods to the same way i did the clock one, but i need to check how to get the DateTime.Now format
I managed to come up with a solution to a UI image compass needle rotating towards an object (red diamond item), based on camera angles. problem is, when I tilt the camera up like in the video, the needle flips around 180 degrees so its the wrong side. I have noticed that when I tilt the camera up, the needleTargetAngle climbs to 180 and then swaps all the way back to 0 and climbs up from there, I feel like this is the cause of my problem but im not sure what I can do to fix it
Vector3 closestItemPosition = new Vector3(closestItem.transform.position.x, 0.0f, closestItem.transform.position.z);
Vector3 needleTargetLocalPosition = Camera.main.transform.InverseTransformPoint(closestItemPosition);
float needleTargetAngle = -Mathf.Atan2(needleTargetLocalPosition.x, needleTargetLocalPosition.y) * Mathf.Rad2Deg + 180;
compassNeedle.eulerAngles = new Vector3(0, 0, needleTargetAngle);
so the closestItem is the red diamond in the video, compassNeedle is the spinning needle at the bottom
What is the best way to get a skinned meshes index's, verticies, and normals per frame on the CPU? Looking to optimize my BVH refitter through any means possible as currently it takes 80ms on the CPU for a 30k triangle mesh which isnt ideal
It might be faster to do the skinning yourself. By default, skinning is done in compute shaders so it's never stored on the CPU. I think you can force CPU skinning, but I don't know if that speeds up BakeMesh, which is what I assume you're using now?
Yeah Iโm using bakemesh every frame which is faster than I thought then I get the data through GetIndices(I), getVerticies, etc.
Then transforming them all, then converting them to barycentric coordinates
Does performance change if you disable this?
Hmmm Iโll have to see, not at home atm(just left) but I will try!
But I donโt think it will since doesnโt bakemesh copy the deformed mesh back to the cpu? And then Iโm just accessing the data how I would any other mesh
Either way BakeMesh never took long to do every frame(at most a few ms)
The actual accessing and copying of the data from the mesh after bakemesh using getvertices, getindices, and getnormals always took way more time
you can't work in euler angles
you can try pointing the transform at the target. in 3d, transform.forward = target works. what do you think it is for 2d?
is there alternative
any guesses?
no
are u saying euler angles wont work because its 3d and this is 2d
the recttransform does have a Z rotation ๐ค
Ok so can confirm, no turning that off does not improve performance
Might just move it to the GPU, but I have no experience with vertex buffer targets that would allow me to access the mesh from a compute shader
are there any examples of its use I can find?
and is there any way to combine multiple graphics buffers? into one large one?
okay well why would this work?
transform.right = target
transform.forward = Vector3.forward;
what is this doing
what is the idea
Figured it out, -Mathf.Atan2(needleTargetLocalPosition.x, needleTargetLocalPosition.y shouldnt have been y, should have been z
Vector3 needleTargetLocalPosition = Camera.main.transform.InverseTransformPoint(closestItem.transform.position); //Calculate closest item transform relative to main camera
float needleTargetAngle = -Mathf.Atan2(needleTargetLocalPosition.x, needleTargetLocalPosition.z) * Mathf.Rad2Deg;
Quaternion needleTargetRotation = Quaternion.Euler(-70, 0, needleTargetAngle);
compassNeedle.transform.rotation = Quaternion.Lerp(compassNeedle.transform.rotation, needleTargetRotation, compassNeedleSpeed * Time.deltaTime);
doing it a cleaner way with quaternions and its lerped
idk bro
Hey does the data of a vertex buffer gotten from a skinned mesh renderer represent the transformed vertices from the skinned mesh? how can I get these?
Im not much understanding how this works, but I know im having trouble getting the vertices back from the compute shader
{
while (isTalking == true){
audioSource.PlayOneShot(voice);
yield return new WaitForSeconds(.065f);
if (isTalking == true){
audioSource.Stop();
}
}
}```
is there a way to ensure the speed the audioClip repeats when running is 100% consistent? because right now the audio will skip randomly or not play perfectly, i'm thinking something to do with time.DeltaTime to make everything framerate independent or scheduling start and end times but i don't fully understand how any of that stuff works yet or how to implement anything properly. for context im trying to make a typewriter audio effect to go with the text itself which is why it plays so quickly
Think you need to make sure the clip is in wav format or you get timing issues like looping not working, might be worth a shot
theyre all .wav unfortunately
Also feel like that if should be a while, seems like you're meaning to wait for something to stop talking
Then again it's a one shot anyway, so don't really understand its purpose
yeah, hardcoding the length of time to wait seems awkward
so its a oneshot just so i can choose between voices quicker atm but play would the same thing here
you can't loop audio in an ienumerator
you have to use the audio mixer and/or timeline to achieve this
Oh I see what's going on I think, you keep restarting the clip over and over
yes
I think you're cutting yourself off
intentionally
Ah, ok
it will never loop correctly this way
Shouldn't that last one be isTalking == false too?
your audio clip isn't exactly a multiple of your variable frame rate. there will be a pause between the clip ending and starting
๐ฅบ
did you try my solution
no this is just to check to make sure isTalking is still true after .065 delay because if its not then i dont want it to stop the audio so it can finish the clip on the last character
im lost so what should i do
you have to use the audio mixer and/or timeline to achieve this
Ah, Hrm
like the mixer in the editor?
use the timeline package.
it sounds like you are authoring a cinematic (in the metaphorical, narrow game sense of the word)
it's going to replace all thes tuff you've done so far to reinvent timeline anyway
Sounds like just text sound effects to me
๐ฅบ
the timeline package lets you declare looping audio
so that it loops correctly
you can use audioSource.clip.length for the time
im literally just trying to replicate undertale dialogue audio for a fan game btw
you can't loop audio using an IEnumerator or by attempting to recreate a loop
why not? ๐ฎ
i think what doctorpangloss is saying is that you shouldn't loop audio through code like that. sure it's totally possible but using Timeline will yield better results
there's a separate audio thread where you can do this, but it's very advanced
that is how Timeline loops audio and why it sounds correct when timeline loops audio
most of the ones ive seen aren't perfect, and the few that are were not in unity
it's okay
I don't loop audio in an IEnumerator but I disable the source once it reaches the end:
Play();
yield return new WaitForSeconds(clip.length);
gameObject.SetActive(false);
i have helped as much as i can
I have a quick generics/inheritance/casting question. I can't figure out what to google, even though I am sure the answer is out there already.
interface ISomeInterface { }
class SomeClass : ISomeInterface { }
class Container<T> where T : ISomeInterface { }
public Container<ISomeInterface> GetContainer()
{
return new Container<SomeClass>(); // Can't convert expression compile error. Why? I *almost* know why, but it isn't quite clicking why or how to 'fix' it.
}
yeah ill see what i can do with that, just never done stuff with it before but cant be too hard
because c# doesn't support this as a matter of how it implements generics
thx ill look into what youve suggested
the right way to interpret c# generics is
public Container__ISomeInterface GetContainer() {
return new Container__SomeClass();
}
and c# doesn't generate Container__SomeClass : Container__ISomeInterface
if you attempt to do that yourself you'll discover why its tricky
Right... well I got that by the compiler error ๐
I guess the only way around it would be to use generics for the method too?
there are many ways to get around this. one is
Pft, this architecture is getting too complex with too many layers :/
Well thanks, back to the drawing board.
java supports covariance which is the thing you were looking for
you can actually cast it directly
did you try doing (Container<ISomeInterface>)Container<SomeClass>();
Yeah
you need to use the out keyword
sorry my bad
you can achieve what you want
is this helpful @urban warren ?
(Reading, second)
Yeah that looks like it works
Though I don't fully understand. And I think I might need to still look at rearchitecting the code as it is getting hard to follow now, and this wouldn't help haha
But thank you very much! This is cool and good to know!
it's something something variant types lol
it isn't super material
it's just awkward syntax in c# compared to yava
i'm sure someone snooty knowledgable will explain the reason why
c'mon guys i'm just razzing you
First time seeing an actual definition for these
Pangloss, you able to give a shortbus example of covariance vs contravariance?
๐
it's saying that covariance is when you want to prove something is something else
Seems like Covariance in this context lets you make things return more types of things, what is contravariance then?
and contravariance is when you want to prove something is NOT something else
Oh, interesting. Thanks
really type narrowing
for example
real world example
okay, i would say the best real world reason this exists is to indicate that an interface "internalizes" another type (the contravariant type)
and that you don't want the interface to ever look like the type in T
it's way more common for delegates
why? because then you can implement multiple copies of this interface (with different contravariant types) and they will not conflict
Hrm. Interesting. Generics still make my head spin
so here's a real world example
multiple copies of this interface (with different contravariant types)
I don't understand what this means though lol
okay
it's for like
imagine you're developing a node editor
and you want to model how something can accept different values, like colors, text or lists of vectors
Sounds like this would be for having INode, which returns a node, then IFloatNode which returns a FloatNode or something?
the node would implement the same interface IAcceptsInput<in T> for those three different types
it would implement IAcceptsInput<Vector3>, IAcceptsInput<Color>, IAcceptsInput<IEnumerable<Vector3>>
whereas trying to do this with IList<Vector3> and IList<Color> and you will see it's very painful
this is why IComparable is contravariant
it will also ensure it does the right comparison when it implements multiple types it can compare against
Interesting. Thanks for the explanation. Makes a bit more sense now
i can find a lot of stupid fake examples on stackoverflow
but i think this is the most practical reason it exists
this sort of behavior and event handlers
like ensuring the narrowest (most concrete) type's event handler is used
when you do something like AddEventListener<in T>(string name, Action<T> handler)
indeed that's why Action is in T in its definition
To make sure it uses the type you specify, instead of a more derived type? Or is it a less derived type. Not sure
i think so it uses the most derived type it can
Cool. Didn't know we could influence that
so that if you do
Action<X> action = (someArg) => {...}
it seems obvious someArg is X but you can easily call action with something that derives from X
it wants to assume the arg is what it is
when it's being passed around in potentially other places
as callbacks for example
i think...
it's definitely a developer experience thing with the delegates.
Hrm, yeah, so in this case you'd implement ICovariant or IContravariant to determine which X it uses there?
you might have multiple delegates of the same shape. you definitely do with actions all the time
so it's very similar energy
it means you can do something like event += action1; event += action2;. do you see how that's like adding multiple interfaces?
and you need a way to guarantee they won't conflict with one another?
it's not really the same but it's the same idea
Kinda sorta, seeing that there's more room for error there than I thought at the very least
But yeah, you wanna make sure you're using the X you want, not some other type related to X is the gist
yeah
the constraint it places on interfaces makes that syntactically possible
it prevents you from declaring T Get(), which would not work if you imeplemented an SomeInterface<Vector3> and SomeInterface<bool>
Yeah. I'm too noob with generics to follow past that, but it's something nice to be aware of in the future when I am working with them
Vector3s can't be converted to a bool and vice versa
so T Get would not work
well i use this in java all the time but it's much more intuitive
Yeah you were saying that
In a indexbuffer graphicsbuffer, whats the format of it? aka, how do I successfully read proper values from it?
I have 1 loggger in my iOS app, one in memory which is the one i have been using till now...
I's a simple List of strings.... whennever an exception or error happens i send that list in log format.
However, i'd like to keep info between different runs so i need to write on disk....
Should i use a simple StreamWriter to do so? or there are better approaches? (im not sure how expensive is to write in to a log file i guess not too much)
var myLog= new StreamWritter(Path);
public void LogThis(string this){
myLog.WriteLine(logLine);
}
onDestroy()
{
myLog.Close();
}
simple as this?
or maybe theres a good 3d party library out there to use?
hey guys, where do I start with trying to add my own buttons to these:
I dont even know what to google
cheers bro
While I'm not entirely familiar with Unity best practices, for C# in general:
- Use StreamWriter with a 64k buffer when writing really large strings all at once for great performance
- Use File.AppendAllText for large quantities of smaller writes as it performs around 25% faster than streamwriter in this case
Hey guys. I'm trying to make a Pickup Script and the way I have it setup is, I have the script attached to each item that I want to be able to pick up and when I go to pick it up, it does appear where I want it to however the rotation isn't correct.
The code either isn't rotating it correctly or they're constantly rotating different each time/way that I pick the item up.. I'm sort of at a loss here because I've been on this for 3 days now and it's hindering my development as it's a pretty crucial part of the game.
If anyone could help me out it'd be greatly appreciated.
The model that I made that's being picked up I believe was exported and imported correctly so I don't believe that should be the issue.
I tried asking in #archived-code-general but I've had two people try to help out and they seemed clueness too as to why it wasn't working, so I figured it might be something a little more complex.
For reference, I have a Raycast that sends 'OnClicked' to any item it hits, and my 'OnClicked' function looks like:
void OnClicked()
{
itemIsBeingPickedUp = true;
GetComponent<Rigidbody>().isKinematic = true;
this.transform.parent = GameObject.Find("HandPosition").transform;
this.transform.position = GameObject.Find("HandPosition").transform.position;
print("Item Name: " + this.name);
if(this.name.Contains("mnnnned"))
{
print("Model is equipment, applying custom rotation stuff.");
// transform.LookAt(Camera.main.transform.position);
// transform.forward = Camera.main.transform.position;
// transform.rotation = originalRotation;
// transform.LookAt(Camera.main.transform);
transform.rotation = Quaternion.FromToRotation(Vector3.up, Camera.main.transform.position);
// transform.rotation = GameObject.Find("HandPosition").transform.rotation;
}
GetComponent<BoxCollider>().enabled = false;
}
Don't crosspost @mystic swift
Alright.
Hey guys I'm using mirror + fizzysteamworks, and I'm trying to make a leave button in the lobby. I think I got it working so far, but when the host leaves he can't start another hosted-game again. I think this might be because he's still hosting the previous one. So I was wondering if anyone know how to completly destroy a lobby and force the players back to main menu when the host leaves OR to switch the host to another player and refresh the lobby to that of the players. Steamworks actually has a command for this called SetLobbyOwner: bool SetLobbyOwner( CSteamID steamIDLobby, CSteamID steamIDNewOwner );
But I don't know how to use it since I'm not that familiar with network coding, so that's why I thought comepletly wiping the lobby and forcing the players back to main menu would be easier?
Can anyone help me please?
NetworkManager.singleton.StopHost();
Or if it's not a listen server,
NetworkManager.singletop.StopServer();
I'm not sure about the FizzySW though
What is the ideal rotation look like in your head?
I.e. what are the expect results?
@next marsh It's a Thermometer, so I want the nozzle facing out the ways towards where I'm looking.
What worked for me was changing the local rotation to a hardset value, but that's probably not ideal long term.
So I can use this command to wipe the lobby and force everyone back to main menu?
That'll close the lobby and all players will time out. Use StopClient(); to disconnect an individual player
Do you have an example script perhaps? Because I'm really weak at coding and I wouldn't know where to start with this
This is for unity networking tho
Does it work for steamworks.NET
I'm not sure, for that you should check in the official discord for it
The Fizzy discord
I'll see if I can come up with something
Is it related to setting the parent by chance?
I tried to use it as "singleton.StopHost();" but the code gives the following error:
Severity Code Description Project File Line Suppression State
Error CS0103 The name 'singleton' does not exist in the current context Assembly-CSharp D:\VRGame\Horror\Assets\Scripts\Network\LobbyController.cs 218 Active
this error now :p
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'NetworkManager.StopHost()' Assembly-CSharp D:\VRGame\Horror\Assets\Scripts\Network\LobbyController.cs 217 Active
In Mirror NetworkManager.singleton.StopHost() is correct
Do you have a class named NetworkManager?
yes
Your own one?
Does it derive from Mirror's NetworkManager?
Yes I think so, tutorial was from Zyger, using mirror and steamworks API
You think, it's your class
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
using UnityEngine.SceneManagement;
using Steamworks;
public class CustomNetworkManager : NetworkManager
{
[SerializeField] private PlayerObjectController GamePlayerPrefab;
public List<PlayerObjectController> GamePlayers { get; } = new List<PlayerObjectController>();
static int[] arr = { 1, 2, 3, 4, 5 };
List<int> uniqueID_List = new List<int>(arr);
public override void OnServerAddPlayer(NetworkConnectionToClient conn)
{
if(SceneManager.GetActiveScene().name == "Lobby")
{
PlayerObjectController GamePlayerInstance = Instantiate(GamePlayerPrefab);
GamePlayerInstance.connectionID = conn.connectionId;
GamePlayerInstance.PlayerIdNumber = GamePlayers.Count + 1;
GamePlayerInstance.PlayerSteamID = (ulong)SteamMatchmaking.GetLobbyMemberByIndex((CSteamID)SteamLobby.instance.CurrentLobbyID, GamePlayers.Count);
NetworkServer.AddPlayerForConnection(conn, GamePlayerInstance.gameObject);
int i = Random.Range(0, uniqueID_List.Count);
GamePlayerInstance.UniqueID = uniqueID_List[i];
uniqueID_List.RemoveAt(i);
/*GamePlayers.Add(GamePlayerInstance);*/
}
}
public override void OnServerDisconnect(NetworkConnectionToClient conn) //for leaving the server (add leave button in lobby)
{
foreach(PlayerObjectController GamePlayerInstance in GamePlayers)
{
if(GamePlayerInstance.connectionID == conn.connectionId)
{
GamePlayers.Remove(GamePlayerInstance);
uniqueID_List.Add(GamePlayerInstance.UniqueID);
break;
}
}
}
public void StartGame(string SceneName)
{
ServerChangeScene(SceneName);
}
}
Not really "my class" I practicly just copy pasted it
So you meant to say "No"
Okรฉ, no
Hmmm
Wait haha, I know see I wrote something next to Onserverdisconnect
//for leaving the server (add leave button in lobby)
I might have wrote it their when I was following the tutorial... Don't really remember anymore since it was quite long ago
Oh no, I can't even put that on a button for some reason
hey guys, looking for advice. I'm looking to get into multiplayer programming and am curious about the transport level. I am not familiar with server in/outs, anyone can sort of show me a path I can follow to learn?
Like this or do I need to add something in my networkmanager first?
If you want to StopHost, that's how you do it
It still doesn't work tho. I can leave the lobby as the host but when I try to make another lobby again it stops me. When I check the lobby list I still see my lobby in the list ๐ฆ
Is that not the fault of Steamworks not Mirror?
Call LeaveLobby
It requires the CSteamID of the lobby you want to leave
do I need to learn how the internet works?
Yeah I know about LeaveLobby, but again I don't know how to implement it to the code. (I'm sorry, multiplayer is still to hard for me)
This is the entire lobbycontroller script
Where I put the "Leave button" function
give me a sec then
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.
I tried putting the leave button in there, all the way at the bottom
Ok
When I run it, it works fine as single player atm
I leave the lobby and the main menu scene opens again
But as the host, the lobby keeps existing under your name so you can't start a new one again
Close the lobby when you return to the main menu
I was looking for 2 options: Or destroy the whole lobby and force the players back to main menu when host leave, or do host migration and close the lobby when everyone leaves
Yeah well, I don't know how since I can't find a function in mirror for destroying a lobby when the host leaves
Because lobbies are not a Mirror thing, they are a Steamworks thing
Same, can't find one for those either, only LeaveLobby()
But that doesn't change the fact that when host leaves the lobby isn't migrated to another host or the lobby doesn't stop existing
You can migrate it, it's another method
Well that's the part I don't know how to reference to
Well you have a lobby, so surely you can get all the people in it
You could sort them by ping, or pick one at random and use them as the new lobby owner
Yes, you can get them by index, so you could run a for loop to the lobby's member count or something
i think if you are running into these errors, you are too early in your journey for this
try photon instead
cygames makes a logger for unity that works well
Where do I get the transforms needed to transform vertices from a skinned mesh to world space?
i think we need to find you some code to reference
that interacts with skinned meshes
i know just the one
oh?
Ive almost got it all done here, just on the final bit where I need to transform objects into world space as currently all vertices are centered around 0,0,0)
oooo thanks!
I think photon with be as difficult for me as mirror tho
it at least has working examples
i personally think mirror is really overrated
I mean, I've been coding it now for 2 months so I'm not gonna turn to photon
I prefer Mirror to Photon but eh
what kind of game is it?
no I havent thanks!
4vs1 horror game, ... like deadbydaylight or something?
1 player is the monster, 4 players need to escape the maze
Not a shooter, like an escape room with a monster behind you
But it is indeed first person
it's tough
i'm not sure what the best multiplayer FPS unity asset store asset is anymore
ohhhh wait ok so I see I need to access the bones transforms to determin the transform I need to move multiple skinned meshes for a single armerature to their proper place
Is there an easy way to do this if I have the vertexbuffer
i would do exactly what those two source examples would do
because it's so arcane
alright fair sorry, just was wondering if there was something easy since im on the final stretch here lol
And I dont know how the index buffer and vertex buffer can be used to relate to bones
OH its a seperate frickin buffer called blendweight and blendindices
welp time to spend another 4 hours figuring out how to properly read from those...
god ok im basically manually skinning now alright
ill need the sources at least to find out how blend weights + blend indices interact, it cant be a simple lerp can it?
remind me what your objective is again
refit(update the AABB's max and mins for every node depending on the triangles they contain) a bounding volume hierarchy (tree of AABB's) every frame for an animated skinned mesh
wait are skinned vertex's graphics buffers pack the blend weight and blendindices in there too?
you're like the chihuahua doing math meme
thats how its felt when I try and figure out how to read from a graphics buffer in a compute shader for like 4 hours
it is really arcane
i don't know anything about it
but i read enough code that my lizard brain kicks in
if i've seen it before
which is in keijiro's package
i linked you
@honest hull https://github.com/keijiro/Smrvfx/tree/002fa4980b1df97075760f69e09f71faf630ca53/Packages/jp.keijiro.smrvfx
ohhhh thanks!
main problem, they dont seem to use a graphics buffer, and currently im wondering if the graphics buffer stores blend weight and blend index
could someone briefly explain to me how async/await works and in what real situation is it used? ive been trying to learn about it but it's just weird for me
I find this asset to be very interesting. However cybersecurity its not my forte.
Could loading data at runtime such as 3D models and textures leave a door open to hackers to inject malicios programs on users of a game who use this asset?
For example in games like VRChat this technology is used to load avatars at runtime to all users in multiplayer. But I know that game has a ton of vulnerabilities, not sure if loading data at runtime is one of them. https://assetstore.unity.com/packages/tools/modeling/trilib-2-model-loading-package-157548#description
i suppose anything that loads external data has similar issues
just realized I was trying to do somethign way more complicated
I was about to recreate mesh skinning
but what I really need is the root node I believe and multiply that matrix, and then all matrixs leading to that? or is there something similar to get the offset of a skinned mesh on an armeture?
wait not root bone
which bone do I need?
I think I need the chain of the root bone all the way to the top
problem is
I dont have a way of getting the root bone of a skinned mesh
but wait not even the root bone
ughh
wait yes the root bone
Any clue how I can get that?
https://www.youtube.com/watch?v=WY-mk-ZGAq8 maybe this could help you a lil?
The C# async / await workflow can simplify your code and give you more granular control over your game in Unity.
Learn how to convert your current coroutine workflow, what a task is, how to run sequential and synchronous code and how to return data from an asynchronous function.
UniTask: https://github.com/Cysharp/UniTask (Provides an efficien...
yo guys
when i open my unity project
it just shows game
and it is blue
the entire screen
- wdym
- how is this related to advanced code in any way?
mb took me 5 hours to figure out i had the game console on maximum size
Hey!
I'm trying to start two time-sensitive processes at the same time. Right now, there is a delay between the two processes after they have started. How do I start them at the same time?
Show how you start them
They are currently started in a simple for loop, and I'm curious if I should simply make the function async and go from there.
I also need to have them sync up at points, and am wondering if I should use some common accessible variable to sync them up.
what is their role
oh
you don't mean processes in the sense
by time sensitive do you mean audio?
Async/await is basically this:
// YOU WRITE THIS
public async Task DoSomeStuff()
{
await First();
await Second();
}
// BUT THE COMPILER SORT OF DOES THIS.
class Blahblahblah
{
public enum EFunctionState {
initial,
afterFirstAwait,
afterSecondAwait
}
private EFunctionState currentState = EFunctionState.initial;
operator() { // This is a C++ thing but it basically means that you can call an object like a function.
switch (currentState) {
case EFunctionState.initial: return PartOne();
case EFunctionState.afterFirstAwait: return PartTwo();
case EFunctionState.afterSecondAwait: return PartThree();
}
}
public Task PartOne()
{
var returnValue = First();
currentState = EFunctionState.afterFirstAwait;
return returnValue;
}
public Task PartTwo()
{
var returnValue = Second();
currentState = EFunctionState.afterSecondAwait;
return returnValue;
}
public void PartThree()
{
}
}
The benefit is that you can keep all the function state inside the function until it completes, which can be paused and resumed at each await point. That resume condition can be anything -- waiting for a user to click a button, waiting for a file to download, waiting for a thread to finish, whatever.
The main goal is to make code linear again, as opposite to adding callbacks that call callbacks that call callbacks etc. (Or polling for stuff every Update()).
It also has a bit of maintainability advantage:
- Exceptions work.
- There are times where code (especially for websites) will download from this server, download from that server, callback into user code, download from another server, callback into user code again, call to a database, then update a table. If you do callback hell, then those two "callback into user code" need to return instantly. If they were async events, then you can have your own async code inside it that just delays the whole pipeline until you're done.
Is it correct that unity doesn't offer a function to restart the game? Id like to reload the game when internet drops and all i've seen for solutions is to load the main menu scene again but thats not what i want. i want it to fully restart the game and show the start splash screen too
no, it does not. this is tricky to engineer from scratch
I don't know how to show the splash screen again, but you're kind-of on your own if you have data that's not associated with an open level.
easiest approach: you can ask the OS to launch a new copy of your game. then exit your current one
Steam Will Not Like That
My game is mobile to start but will be ported to steam so id like as little hiccups as possible. I guess i could just try this for mobile and then check if platform isnt mobile to do some other fix
Would Apple let users launch apps from other apps? I think they only allow cross-app links.
But yeah you're probably better off just managing your internal state in a more encapsulated way.
thanks
hey so why does this:
for(int i = 0; i < 1; i++) {
for(int i2 = 0; i2 < 1; i2++) {
ReverseStackNode = ReverseStack[i];
if(NodePair[i2].PreviousNode == i) {
ReverseStackNode.Children[NodePair[i2].InNodeOffset] = i2;
}
ReverseStack[i] = ReverseStackNode;
}
ReverseStackNode = new Layer();
ReverseStackNode.Children = new int[8];
}
Cause all 360 entries of ReverseStack to be written to? with the same values for every I may add
this is driving me nuts
Ohhhh, this kinda makes more sense now, thanks! So if I understand this correctly, if I have two functions (let's say One(); and async Two(); ) with the first one activating the second one, the code in the first one activates synchronously, and in the second one it pauses whenever there is the await keyword
So
public void One()
{
Two();
}
public async void Two()
{
await Something();
}
``` ???
assuming I want to await user input, how would the syntax look for it?
Yeah
Okay if you want to wait for user input... then that would be a bit challenging. That's into manual mode (unless UniTask or something has something simpler).
Basically, you manually create the Task<> from a TaskCompletionSource, and you call SetResult() from whatever.
So imagine you have a dialog result.
public async void Two()
{
// Dialog has not been shown to the user yet.
if ((await ShowDialog()) == SomeOkEnum)
{
// The user closed the dialog by this point by clicking Ok.
}
else
{
// The user closed the dialog by this point by not clicking Ok.
}
}
But getting ShowDialog() to work is a bit of a pain in the butt, and it's subtly different if you do it in C#, Swift, JavaScript, etc.
Involves TaskCompletionSource<> and stuff.
use unitask for async in unity. its examples will help you understand how to use async in unity. for user inputs, create a var input = new UniTaskCompletionSource<string>() for e.g. a string user input, then input.TrySetResult("the result"); elsewhere in yoru code
@gilded inlet https://github.com/Cysharp/UniTask
This is the way, we used to have something similar for popups, works really well but you have to architecture your game around it a little
Kind of a dumb q but not at an IDE to test - does Unity's reflection work on inherited classes? Specifically does an 'Update' in a parent class get called if it's also called in a child class?
Update in the inheriting class gets called first (and only). If you want the base class to call it, you have to call base.Update I believe
But yeah, you can override Awake, update, etc
yes. yes.
No, no.
Unity doesnt 'call' it on the base class, you have to do this yourself. If you omit base.Update(), it wont be called.
I'm writing some Unit Tests and I would like to prevent [RuntimeInitializeOnLoadMethod] from running in the context of the test, any idea how?
RuntimeInitializeOnLoadMethod is after awake if I'm not mistaken, so you can put a guard-clause to the method tagged with that attribute
yep
note that the default RuntimeInitializeOnLoadMethod is after scene loaded, unless you do it like this [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
I have cors errors when doing this
cors usually handled from back end / server side
Yep adjust your server accept headers if you have access to the config, or request a change to your provider
Nope, it's before everything, even [SetUp]
All of them
this is my cors error, something about redirects? unitywebrequest cant handle those?
Every single one of them runs before Setup
can anyone help me with Obi asset?
i have a obi fluid and trying to make a count on collision
it somehow works then stop counting
Hi!
I've implemented a source generator (https://docs.unity3d.com/Manual/roslyn-analyzers.html) in Unity and it works when I run the game in the editor, but when I build the game it says the name 'foo' does not exist in the current context.
Are there some things I have to further set up?
I've built the library to assets folder, set turned unchecked any platform and disabled standalone and editor.
I've set the tag to 'RoslynAnalyzer' and it works perfectly fine in the editor, but when I build it says
The name 'foo' does not exist in the current context.
you make a source generator, yet you don't know what that error is? ๐
I know what the error is .. I just don't know why it happens because it works in the editor without any issues and it loads up fine.
Just when building, it seems to not actually "use" the source that is being generated.
But skip it.
What platform are you building?
Windows
Weird
Wait, it may be .. Hold up.
Btw you should uncheck all platforms not just editor and standalone
Hmm, and your SG is targeting .NET Standard 2.0 and using the supported package?
If so then Iโm out of ideas, I gave SG a go the last few days, worked fine but ended up not using them because SG is SG.
anyone?
Probably missed it, but CORS errors are usually due to the server config, not the client.
Check the server settings or request a change if you don't have access to them.
@novel plinth // I can make a reproducible example later
no, don't... and I believe most of the dudes here wouldn't run it on their rig anyway...
we all just bunch of random people here
Did you successfully build it as well?
Yes.
Odd.
thanks a lot i found my answer but it keeps counting now how do i make it count for time contact
Depending on what you are using SG for, you may consider using an editor script instead.
Yeah, I don't think I can.
Although it was worth a try.
Fair. Anyways, time to figure out how the hell do I work around that. Damn you, Unity
it's most likely not on unity's side but on server side instead
pure c# question: if I have record Person(string name) and record AgedPerson(string name, int age) : Person(name), is there any way to create an AgedPerson from a Person like AgedPerson myAgedPerson = myPerson with {age:30}, or do I just need to call the constructor with all the fields (there are more fields in my real case)?
Server side? What?
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos. Certain "cross-domain" requests, notably Ajax requests, are ...
As in the server that is hosting your webgl game
there is no hosting
no multiplayer
just editor, my code and tets runner
not published, not built
The test runner starts up a minimal web server to host the game
I think there may have been some confusion here? Wokarol was asking about unit tests and [RuntimeInitializationOnLoadMethod]; Patty was asking about CORS errors. I think that got mixed up a bit
Unless... it's in editor tho
I'm not running those test in a build
Oh, that could happen. Yeah, it fits
I guess my only solution it to ignore the problem and pretend this method is never run
My mistake
quoted the wrong post
No problem
Resolved the error, it was just working directory issue 
hello
if there are 2 colliders on a gameobject
how do i only check collisions for one of those colliders
The colliders should be on separate child objects and you put a script on the particular child you're interested in
Also don't crosspost
oh alright thank you
my bad
i though i deleted the other messages
if you're insisting on using two colliders in one object without utilizing the layer, you can put different type of colliders and check it's type
void OnCollisionEnter2D(Collision2D col)
{
if (col.collider.GetType() == typeof(BoxCollider2D))
{
}
else if (col.collider.GetType() == typeof(CircleCollider2D))
{
}
}
Hey,
I saw a chess ai project in github and the person who built it wrote this:
public void NPCMove()
{
// Start the StopWatch
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
// New State History Stack
History = new Stack< State>();
/* --------------------- Sense --------------------- */
ActualChessmansReference = BoardManager.Instance.Chessmans;
ActualWhiteKing = BoardManager.Instance.WhiteKing;
ActualBlackKing = BoardManager.Instance.BlackKing;
ActualWhiteRook1 = BoardManager.Instance.WhiteRook1;
ActualWhiteRook2 = BoardManager.Instance.WhiteRook2;
ActualBlackRook1 = BoardManager.Instance.BlackRook1;
ActualBlackRook2 = BoardManager.Instance.BlackRook2;
ActualEnPassant = BoardManager.Instance.EnPassant;
ActiveChessmans = new List<Chessman>();
Chessmans = new Chessman[8, 8];
...
Anyone knows what the stopwatch used for?
cool! so what's the problem?
I edited the question ๐ accidently pressed enter ๐
A chess clock consists of two adjacent clocks with buttons to stop one clock while starting the other, so that the two clocks never run simultaneously. Chess clocks are used in chess and other two-player games where the players move in turn, and in some legal settings where each side is allotted a specific amount of time for arguments. The purpo...
most probably that?... I'm not a chess player but I watched some grandmasters played and they used that
a stopwatch is often used to time how long a piece of code takes to run - it will take a note of the current time, and can be called again later to see how much real time has elapsed since it started
With that little context it's hard to say, probably for benchmarking, it's mostly used for that
It could be used as the clock
yeah, people rarely used Diagnostic class for ingame purposes
I think you are right, I looked for all the references for this variables and it called for start, stop, and access the elapsed milliseconds to debug.log at some point, thanks ๐
I have another question about this project ๐
(Chessman chessman, (int x, int y) oldPosition, (int x, int y) newPosition, bool isMoved) movedChessman;
What is that line means? what kind of variable is that?
it's a tuple (of tuples)
(int x, int y) pair
is similar to
struct Pair
{
int x;
int y;
}
Pair pair;
Does anyone have experience with writing a list of vector3's to a texture2D?
Kinda stuck on step 2
Are you doing this so you can access this list in a shader?
Yes, In a VFX graph actually
Are you aware of SetGraphicsBuffer and the Sample Buffer node?
Nope I don't think so.
But I have it working already with the 'set position:mesh' node but that's not really what I want
I have an object in the scene and it can move, but I want to have it's first position to be shown with a vfx hologram thing. So I just want to draw a line from each vertex (the vertices are assigned in an array) to the ground position.
Like here
You can avoid copying the vertices into a separate list and just pass the mesh vertex buffer directly to the VFX Graph, like this example:
https://docs.unity3d.com/ScriptReference/Mesh.GetVertexBuffer.html
I have a center point and each line needs to go to a vertex. But If I move this object or delete it, I still want to show it. But I don't want to work with the regular mesh since I scale the object quite a lot
This example is passing it to a compute shader with SetBuffer, but you would just replace it with visualEffect.SetGraphicsBuffer(propertyName, vertexBuffer)
Are you scaling the raw mesh or just scaling the transform?
That has no effect on the underlying mesh
The shader responsible for drawing the mesh receives the mesh data and the transform data and combines them in the shader, it doesn't modify the mesh data.
oh okay I see! thanks for the help. I'll try it out ๐
https://dl.dropboxusercontent.com/s/v00igfvd1qv8638/Unity_OJv8kgzE1O.mp4
Anyone here know how to properly schedule for a mesh to be drawn in a command buffer, using deferred rendering?
Basically i have Graphics.DrawMesh, but i know my meshes beforehand so id like to schedule it. Struggling on finding the right points to inject draw calls. With a custom shader i've been able to fix up the stencil state so this is no issue anymore: https://forum.unity.com/threads/stencil-buffer-problems-using-commandbuffer-drawmesh-with-deferred-rendering.527591/
But now as you can see RT3, which is reflections, isnt filled.
https://pastebin.com/Jj2JTTBh Code is very simple atm, havent even gotten to the shadowy bits yet
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.
Also considered forcing it to be drawn in forward-opaque, but i dont think there is a handle to fix the depth in forward-depth pass
(builtin render pipeline)
Are you trying to avoid Graphics.DrawMesh because you're worried that calling that every frame will have worse performance than adding a command buffer to a camera?
Essentially yes
Atm i have a bottleneck of nearly 2ms calling Graphics.DrawMeshInstancedIndirect, i thought scheduling all in advance would be faster
Are you including all the time spent preparing the data for the DrawMesh call in those 2ms or is it literally just that method call taking 2ms?
Gathering data as well, but considering my meshes dont change (directly, e.g. its instanced-indirect) that could be avoided completely
But good point, profile first.
Here is an example scene with 24 objects to draw, using commandbuffer. 0.04ms, vs drawmesh.. 0.03ms!
In the complete example it might still be faster, but thanks for pointing out the overhead isnt that bad actually.
Hello, I have a working project with async and await code
If I add an assembly definition it says me errors about the missing of await function
like this: Assets\Web3Unity\Scripts\Library\EVM.cs(23,5): error CS1061: 'UnityWebRequestAsyncOperation' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'UnityWebRequestAsyncOperation' could be found (are you missing a using directive or an assembly reference?)
and like this: Assets\Web3Unity\Scripts\Library\WebGL\Web3GL.cs(50,13): error CS1061: 'WaitForSeconds' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'WaitForSeconds' could be found (are you missing a using directive or an assembly reference?)
I searched online and I found results about the .net 4.x update that contains the definition that previous library doesn't
but that isn't my problem, because I'm using .NET Standard 2.1 and it was working with it before the creation of assembly definition
Having a weird issue here. Does unity not allow switch struct format? This, for example, is valid in Visual Studio:
private void DoPayout(Bet.BetResult result)
{
int payout = result switch {
VCasino.Bet.BetResult.Win => currentBet.BetAmount,
VCasino.Bet.BetResult.Loss => currentBet.BetAmount * -1,
_ => 0,
};
CurrentMoney += payout;
}
but Unity throws a tantrum:
What version of Unity are you on?
2019.4.31f1
Dang, it looks like switch expressions aren't allowed in 2019. I'm upgrading it to 2020 and seeing if it takes it
could you please let me know if that was the issue?
I think u should use 2021
Experienced it, that is indeed the issue. VS reports correct syntax because god-knows-why, while Unity doesn't like it. It probably has to do with the SDK VS uses being different than the one in Unity
Or the fact that not all of the features of one C# version are enabled in Unity
If I try to use a language feature not supported by current Unity version, I would get an error clearly stating it.
Or at least that's the case for VS Code, weird that you guys aren't getting that in VS.
Afaik 2021 supports c# 8
Yep, can also see that from the csproj it generates.
did you guys encountered A failure occured while executing com.android.build.gradle.internal.tasks and still receiving the error after adding in gradle.properties org.gradle.jvmargs=-Xmx4608m
It was not. Same error.
that switch statement requires 2021
you should try reinstalling the editor with the android tooling built in
๐ฆ
you need to reference the unity web request packages in your assembly definition
are you using unitask?
no, I'm using an AsyncAwait library
and I found that i was missing the asmdef for it
solved it. thx
hmm
you should use unitask
what library is "AsyncAwait"
"Web3Unity" very concerning...
this is from chainsafe
Bridging Unity games to the blockchain.
I found it very helpfull to interface my webgl build to metamask and other web3 services
Yo, hello there. Is there perhaps some recommended way of handling for example weapons with scriptable objects? Specifically having a system where you can bind 3 weapons of your choosing to slots and when you press the key 1-3 it equips said weapon but it also lets you press a holster button.
I made 3 systems like this that work as intended but none of them is very "efficient" seen as there's been quite a bit to write.
First method was completely without scriptable objects, hard-coding everything. Second version was using scriptable objects and instantiating the weapon and parenting, positioning dynamically (not too great because you can also change chars and some chars have different proportions). Third method/current method is using scriptable objects for the stats and all that and then checking what scriptable object is in which slot and then enabling/disabling the needed weapons on the chars. Thanks!
create prefabs for your weapons, and attach components to them
don't overthink this
you can create a scriptable object for a weapon, but it's only going to be referenced in one place - the weapon prefab - so instead, define it there
Aye, gonna look further into it. I only know that instantiating might be very much more troublesome because it'd be quite a few empty objects acting as slots on different chars. I've got another idea just now tho.
You see, the main issue in general is that you can't really directly attach anything from the 3D scene onto a scriptable object. You can and it works but you'll get a "Type Mismatch" in the box. So idk. lol
If I can please 3x get some help from someone who has advanced knowledge of Assembly definitions.
I'm using a asset from the asset store that utilizes Assembly definitions, but because of that, I cant call anything from my core PlayerController class which is a BIG DEAL
A simplification is that the asset allows for an inventory system, the inventory system has a item system embedded within it's own namespace, but the item is picked up upon collision, nothing more. What I want is to collide and then the item script waits for an input through the PlayerController colliding.
is your PlayerController script inside an Assembly Definition as well?
No, just the basic "assembly-csharp"
I've been much too scared to even mess with Assembly definitions
have you tried adding 'using NameOfNameSpaceOfAssemblyDefinition' in your player script?
Short answer: no; but only because I'm assuming I'll lose connection to all the other scripts like my "Vitals" and stuff. Is that just the solution, to add the namespace to all scripts, or inversely remove namespace from the assets?
This is in the documentation for the asset, but it's so vague when it comes to what I should truly do
You don't lose anything, if you want to use TextMeshPro you have to add 'using TMPro' at the top. The same should work for your asset store things
Ok, cool. Let me try that real quick
OH!
Wait I see what you mean, adding it to the C# references
I didn't even think of those two being connected
Wow
so it worked?
Ok, I believe we are on the right track, but the problem is that I'm trying to call the PlayerController class from within the Asset's personal namespace
'The type or namespace name 'PlayerController' could not be found (are you missing a using directive or an assembly reference?)'
But how am I supposed to reference it if it doesn't have a namespace, or can I somehow call all scripts in the default 'assembly-csharp'
ah wait
you should make a new script that inherits from the class you want to use:
public class MyInventoryScript : TheirInventoryScript
{
}```
and then in there you change the code to how you like it
I hope the base class has virtual methods, try writing
'override' and see if it suggests a collision method
ye it should
Yeah, pretty much all the script's functions from the asset are extendable with virtual attached
If you can imagine, that 'Pick' function I'm only trying to invoke if(collider.GetComponet<PlayerController>() && collider.GetComponet<PlayerController>().InputFunctionOfSomeSort())
Idk, some weird psuedo code, but I can't even get to prototyping if I can't even call the PlayerController, so let me try to make the Extension script and I'll get back to you
It worked! I suppose it all makes sense, just call the nameSpace through a separate script within the PlayerControllers nameSpace.
I appreciate it, couldn't seem to find any forum posts with that niche problem, thank you again.
just make sure you replace the scripts on the items that can be picked up with the new script, or make a new item entirely
hey guys, I wanna make a game like Stone Miner but I cant figure out how to make deformable mesh I've looked some assets on unity asset store but they are all working with unity physics.(If a drop an object it works but if I drag and drop objects it doesnt work). Do you know any assets or scripts make an deformable asset on colission work smoothly.
https://assetstore.unity.com/packages/tools/physics/impact-deformable-4799#description this one doesnt work on my project
