#archived-code-advanced

1 messages ยท Page 187 of 1

grim oxide
#

It sounds like this is just a way to pass a value type by reference instead? What would that even mean ? quinThinking

misty glade
#

@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

grim oxide
#

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

misty glade
#

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

grim oxide
#

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? quinWTFF

novel wing
#

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

grim oxide
#

I thought that was definitionally impossible for value types ๐Ÿค”

misty glade
#

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

grim oxide
#

Is it wrapping it for me behind the scenes?

novel wing
misty glade
#

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

grim oxide
#

This is like the opposite of what i need then.

#

or just different

novel wing
scenic forge
#

ref isnโ€™t a bad thing, not sure where that idea comes from. Itโ€™s not common sure but itโ€™s not bad.

grim oxide
#

I'm pretty sure it's bad ๐Ÿ˜›

misty glade
#

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

grim oxide
#

It smells bad

misty glade
#

It's not bad, it's just.. you need to know where you're using it

scenic forge
#

Btw in terms of performance, anything larger than 4 bytes passing by ref is much faster and takes up less stack.

grim oxide
#

@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

misty glade
#

I'm not at all confused.. I see how you're implementing it with your getter/setter...

scenic forge
#

Itโ€™s actually a very common performance optimization to do when passing large structs.

#

But thatโ€™s kind of a side topic.

misty glade
#

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

grim oxide
misty glade
#

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

grim oxide
#

I can just do it with a list, with indices

misty glade
#

then you find a bug...

grim oxide
#

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

novel wing
grim oxide
#

Yea

misty glade
#

i don't really know what the serialization issue is, but ... a dictionary is a list with enum indicies, basically

grim oxide
#

Ease isn't the issue, I'm trying to find the best/cleanest answer

misty glade
#

I mean, sort of, but it seems to be the right data structure for your issue..

grim oxide
#

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

misty glade
#

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

grim oxide
#

This is why I was avoiding a collection in the first place

#

Now of course I could make a custom editor quinDespair

novel wing
#

This is for some kind of inventory right?

grim oxide
#

See, no perfect answer ๐Ÿ˜›

#

Yes

novel wing
#

How do you store an item

#

ScriptableObject?

grim oxide
#

ItemState is an object that has a reference to a ScriptableObject ItemData, ItemState has stuff like durability

#

ItemData defines what the item is

novel wing
#

What is ItemState, normal c# object?

grim oxide
#

Yes, [Serializable]

#

Tying items to whole gameobjects seemed really insane

#

For ones that are stored

novel wing
#

Would it be possible for you to use the ItemData directly?

#

You can create a ScriptableObject instance at runtime

grim oxide
#

What do you mean exactly, it's free to view for anyone with a reference to the ItemState

#

Go on...

novel wing
#

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

misty glade
#

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

grim oxide
#

You mean like have some serializable fields excluslively for the inspector that populate the slots on Awake or so?

misty glade
#
private Dictionary<SlotType, EquippedItem> EquippedItems = ...;
public EquippedItem FootItem => EquippedItems[FootSlot];
grim oxide
undone coral
#

if you want a serializable dictionary get one from odin

grim oxide
#

Things-spawning-with-items don't need those items to have unique state on spawn

#

The generic initial state is fine

misty glade
#

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
#

looks great

misty glade
#

(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)

undone coral
#

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?

misty glade
#

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

undone coral
#

it's interesting

#

i sort of get what's going on

misty glade
undone coral
#

yeah

#

sick

misty glade
#

yeah - forgive the developer art obviously.. we're hoping to hire an artist this week

undone coral
#

that gray grid is the only thing that's breaking "Rules of Mobile Games" for me (#1 only 1 screen)

misty glade
#

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)

undone coral
#

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

misty glade
#

ah, gotcha

#

I'll mention it to our UIUX guy.. we tried cramming it all on one screen and it was pretty sloppy feeling

undone coral
#

you'd have to make it less important from a gameplay perspective somehow

#

which i'm not sure is possible

misty glade
#

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

undone coral
#

i'm getting some puzzle fighter vibes from what i see in the current gameplay

misty glade
#

right?

#

it's a cool idea/design

undone coral
#

yeah

misty glade
#

(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

undone coral
#

sick

grim oxide
#

@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" quinThinking

honest hull
#

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?

honest hull
#

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

misty glade
# grim oxide <@205740708970102784> meant to ask--you mentioned FSM--is the term "state" only ...

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.

kindred wyvern
#

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?

kindred wyvern
#

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?

grim oxide
# misty glade Typically a FSM means .. something that has a fixed number of states, and typica...

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

grim oxide
#

This is something I struggle with myself because I simply love to overengineer stuff like that

#

So YMMV

kindred wyvern
#

Assume it's a lot. This is a fake scenario.

grim oxide
#

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)

kindred wyvern
#

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.

grim oxide
#

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 ๐Ÿ˜›

kindred wyvern
#

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.

grim oxide
#

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? quinThinking

#

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?

kindred wyvern
#

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.

#

Think_Cat
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.

red osprey
#

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"

kindred wyvern
umbral trail
#

Do you just want a factory to take a type name instantiate an object?

red osprey
kindred wyvern
misty glade
# grim oxide > State typically doesn't mean the value you place in a variable here, which is ...

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.

red osprey
misty glade
#

๐Ÿคทโ€โ™‚๏ธ 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

kindred wyvern
#

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.

umbral trail
#

if you have a reference to an interface, can't you create a serializable object that derives it with whatever data you want?

kindred wyvern
#

The object that references the serializable object cannot be fully serialized, because it doesn't know what that object is.

misty glade
#

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

kindred wyvern
#

Stuffing that information into a bunch of things with inconsistent data structures between each other.

red osprey
#

Will all of the possible subclasses be known at compile time? Or will some of them rely upon loading a DLL or something?

kindred wyvern
#

They're definitely known at compile time.

#

Without reflection, though, I can't store any information about those types automatically.

umbral trail
#
interface IX {}
class A : ScriptableObject { public IX x; }
class B : IX, ScriptableObject {}
#

are you talking about unity editor-time serialisation, or runtime serialisation?

kindred wyvern
#

Anything that gets data into the program without recompilation.

#

So basically, if it's not written in C#, it's golden.

umbral trail
#

so, custom runtime serialisation?

red osprey
#

Ahhhh wait you want to NEVER write any C#?

kindred wyvern
#

No.

#

I don't want to write my static data in C#.

red osprey
#

Ah okay.

kindred wyvern
#

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.)

red osprey
#
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.
kindred wyvern
#

Which is exactly what I'm trying to avoid.

umbral trail
#

are you saying using the editor not acceptable because you need to rebuild to make changes?

kindred wyvern
#

I'm saying using the editor is preferred because I won't have to recompile to make changes.

#

Or edit an existing class.

umbral trail
#

ok, but you are saying the editor can't deserialise an object that you reference from an interface?

kindred wyvern
#

I mean, that's certainly true, and would be a method of solving this problem if it was possible.

umbral trail
#

and to clarify, webgl is AOT, you can use reflection, just nothing dynamic

#

you can definitely use interfaces to reference objects in the editor

kindred wyvern
umbral trail
#

why aren't you just using [Serialize]?

kindred wyvern
#

Well, for one thing, there is no [Serialize].
Using [SerializeField], though, gets you this:

umbral trail
#

sorry, yes, [SerializeField]

red osprey
umbral trail
#

so that says you can't use [SerializeReference] with MonoBehaviour or ScriptableObject

red osprey
#

You can't use them to (de)serialize MonoBehaviour or ScriptableObject.

#

You can use them as fields on MonoBehaviour or ScriptableObjects.

umbral trail
#

Yeah, so with some work that could be used to create plain classes that are embedded in the edited object

kindred wyvern
umbral trail
#

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

kindred wyvern
#

Oo, editor only reflection.

umbral trail
#

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?

kindred wyvern
#

2020.3.32f1

undone coral
#

i don't think pooperty drawers support interfaces by default

#

"just use odin"

#

i'm not a fan of serializereference

split sundial
#

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

kindred wyvern
#

Not sure what a smart string is. Any reason you can't use string.Format()?

misty glade
#

Isn't smart strings a python thing? .. googling..

#

i might be thinking of smart enums or something else

split sundial
#

I could, but that means that for every keyword that I needed to replace, I'd have to add a specific handler for that

misty glade
#

Oh, sorry, that's uh.. built into C# then

#

prefix your string with $

#

(Is that what you mean?)

split sundial
#

I can't

#

The string comes from a TextAsset

#

For instance, a text could be "You have {Player.HP} HP and {GameManager.Currency} Coins"

kindred wyvern
#

Ahhh. That explains it.

misty glade
#

ohhhhhhhhh you're saying the actual string value has some code that you need to parse and/or execute

split sundial
#

Exactly

kindred wyvern
#

Wouldn't the existence of $ imply there's a system type for smart strings?

misty glade
#

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. ๐Ÿ™‚

unkempt nova
#

Sounds like what you want is a "tokenizer" @split sundial

#

Think that's the term you're after

#

It's a deep rabbit hole

split sundial
#

Hmm, I'd say you're right :P

misty glade
#

Yeah uh.. what's the use case here, anyway? Like, why does the text have {} with "code" in it?

#

(seems like a vulnerability nightmare)

unkempt nova
#

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

split sundial
#

Yeah, I can imagine it being very similar to a Lexer

unkempt nova
#

Never heard of a lexer, but lex implies lexicon, so I think we're on the same page

split sundial
#

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

kindred wyvern
#

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.

undone coral
#

i remember yacc

#

and lex

#

and yalr

kindred wyvern
#

Tokens are instances of lexemes specified in a lexicon.

undone coral
#

not sure why they came up so much, when compiling for zaurus, on gcc 2.95

undone coral
#

SmartFormat / handlebars templaters do this

#

smartformat comes with the unity localization package

split sundial
split sundial
undone coral
#

yes

#

i used a handlebars formatter in my own game

unkempt nova
#

SmartFormat looks pretty sweet

grim oxide
unkempt nova
#

Yes, but screw all that imo

grim oxide
#

Assuming we're just checking for field/property/etc names?

split sundial
unkempt nova
#

@undone coral Docs/wiki are kinda short. What kinds of useful stuff can you do with it?

split sundial
grim oxide
#

Oh sure but maybe you could just do it once, up front ๐Ÿค”

#

Rather

#

Parse the text code once

split sundial
#

Yeah, but I need to use values that constanly update

grim oxide
#

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

split sundial
#

Like currency (in my game, it might update even every frame)

red osprey
#

If it's every frame, then you'd want something that doesn't GCAlloc, too.

novel plinth
#

without custom tag, you can hack your way with the built-in <link> tag

subtle silo
#

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)?

normal moth
#

raycast from cctv to get info or want to interact with that NPC

thorny onyx
#

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 ?

tired tartan
#

Is it possible to convert a binary data to a int or text?

fresh salmon
#

Don't cross-post

crystal ravine
#

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

regal olive
#

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

thorny onyx
#

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 ?

crystal ravine
#

anyone knows how to make game asset responsive to the different screen sizes in unity

crystal ravine
#

sorry

undone coral
#

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?

thorny onyx
regal olive
thick birch
#

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);```
lusty oak
#

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

grim oxide
#

๐Ÿค” Smells like a trig problem

#

I don't know trig, I phone my math nerd dad for all the trig questions moon2LOLE

lusty oak
#

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)

red osprey
# thick birch Is it better performance-wise to have the local variable outside the while loop ...

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.

thick birch
#

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

red osprey
#

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.

thick birch
#

so me putting it outside the loop is the right way then?

red osprey
#

No

thick birch
#

๐Ÿค”

red osprey
#

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.

thick birch
#

so i can safely put it inside and save a line

somber swift
#

Putting it outside of the loop is definitely not incorrect and seems more logical for me.

thick birch
#

^

red osprey
#

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.

thick birch
#

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

grim oxide
#

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

thick birch
#

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

grim oxide
#

Oh that's a different question

thick birch
#
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

red osprey
#

I'm assuming that when the function is re-entered that the stack frame would need to be setup identically.

grim oxide
#

Every time you do TimeSpan.FromSeconds it gets "created" in the way you are thinking

thick birch
#

but no like

#

you know how a variable gets a memory assigned to it, right?

grim oxide
#

The position of the declaration is not changing anything

red osprey
#

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.

grim oxide
#

You're worried about the speed at which the declaration is done?

red osprey
grim oxide
#

You need to write good, readable code first, and worry about nanoseconds of performance second

thick birch
#

instead of just the value changed

grim oxide
#

The interpreter probably makes it the same anyways

#

Unless we're talking omega-hot code you should prioritize readability/form

thick birch
#

hmm

grim oxide
#

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

thick birch
#

that kind of logic still confuses me

grim oxide
#

And oftentimes will result in those variables persisting longer than they should

thick birch
#

thats eventually going to start adding up

red osprey
#

Not really.

#

Here's an example.

grim oxide
#

0.0000000001 * 100000 is still a very small number

thick birch
#

heh

grim oxide
#

What will add up more is the extra dev time negotiating with weirdly written code

red osprey
#

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.

thick birch
#

hey, i like knowing whats exactly going on in there

red osprey
#

So just starting the function is like 100ns.

grim oxide
#

When you exit the loop, ts is still held--why? Do you need it?

#

If not, it shouldn't be held

thick birch
#

when i exit the loop, the function ends at the same frame

grim oxide
#

For now

thick birch
#

i use the IEnumerator as a start, loop, and end

grim oxide
#

"The function will end and clean up my mess" is not a good reason to make a mess ๐Ÿ˜›

thick birch
#

start is before while, end is after

#

both will run once

#

while its looping its going to be using it constantly

red osprey
#

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.

grim oxide
#

Yes in this particular case it's "harmless"

#

But reinforcing bad habits is never harmless ๐Ÿ˜›

red osprey
#

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.

thick birch
#

cant deny google team makes stuff that work

#

they have performance issues though ๐Ÿ˜„

red osprey
#

But yeah chances of someone relying upon the location of a local variable is very very very small lol.

thick birch
#

fair enough; guess ill just put it in the while loop and save a line of code

red osprey
#

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.

paper fiber
#

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.

thick birch
#

readability and simplicity it is then hannzaSip

red osprey
#

@paper fiber You will need to specify platform(s). You could be talking about deep links, universal links, custom protocols, etc.

red osprey
# thick birch readability and simplicity it is then <:hannzaSip:650760974227210280>

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...

thick birch
#

lmao

red osprey
#

Like -- we're not stupid we can look at the profiler and see what the actual problem is lol.

thick birch
#

have u seen the yandere simulator code? its disgusting xD

#

even i wasnt taht bad in the first few years of programming

red osprey
#

I've seen it, yes. YandereDev is using my GitHub.

thick birch
#

oh hannzaSip

#

whats he using?

red osprey
#

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.

thick birch
#

gotcha

#

is he still working on that game?

red osprey
#

Yup.

thick birch
#

oof

#

last ive seen it was like 2017

#

or 2018

red osprey
#

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.

thick birch
#

i see

#

so u actually helping him after ive seen the code

#

hopefully its better now ๐Ÿ˜„

red osprey
#

In terms of performance? Was never a problem.

thick birch
#

no in readability and stuff

red osprey
#

Yeah he's aware that it's difficult to change.

thick birch
#

from what i remember there was just lines upon line sof duplicate codes one after another with a tiny difference

#

crazy

red osprey
#

I mean it's by far not the worst code that I've seen lol.

thick birch
#

i bet my gui code is worse back from 2010

#

new Rect on every new UI element ๐Ÿ‘€

#

in the OnGUI method*

red osprey
#

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.

thick birch
#

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 hannzaSip

#

get some Action variables in case i want to hook it up to things, and thats it

undone coral
#

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?

paper fiber
#

so is that Deep links?

#

@blissful sedge me so I could see

undone coral
#

that exists

#

if you want a library of helpful utilities for coroutines, really async methods, use unitask

undone coral
thick birch
undone coral
#

well you're writing something called Timer

thick birch
undone coral
#

it sounds like you both want a general purpose timer or... not

thick birch
#

its this

undone coral
#

hmm

thick birch
#

theres 6 separate digits

undone coral
#

the implementation will be flawed

thick birch
#

if its a timer, it will count it down

#

from a set time

#

how come flawed

undone coral
#

well i haven't seen all the code yet

thick birch
#

well hmm

undone coral
#

it depends on what interacts with the timer

thick birch
#

here let me put it out in pastebin

undone coral
#

it's okay

#

i think this is pretty low stakes

#

go with what you have ๐Ÿ™‚

thick birch
#

well im happy with the clock, but the timer and stopwatch methods are very stiff...

#

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

lusty oak
#

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

honest hull
#

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

sage radish
honest hull
#

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

sage radish
honest hull
#

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

undone coral
undone coral
lusty oak
undone coral
#

what is the equivalent of transform.forward = target for 2d?

#

nvm

undone coral
lusty oak
#

no

lusty oak
#

the recttransform does have a Z rotation ๐Ÿค”

honest hull
#

are there any examples of its use I can find?

honest hull
#

and is there any way to combine multiple graphics buffers? into one large one?

undone coral
# lusty oak no

okay well why would this work?

transform.right = target
transform.forward = Vector3.forward;
#

what is this doing

#

what is the idea

lusty oak
#

Figured it out, -Mathf.Atan2(needleTargetLocalPosition.x, needleTargetLocalPosition.y shouldnt have been y, should have been z

lusty oak
#
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

lusty oak
honest hull
#

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

ember torrent
#
    {
        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
unkempt nova
#

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

ember torrent
#

theyre all .wav unfortunately

unkempt nova
#

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

gray pulsar
#

yeah, hardcoding the length of time to wait seems awkward

ember torrent
#

so its a oneshot just so i can choose between voices quicker atm but play would the same thing here

undone coral
#

you have to use the audio mixer and/or timeline to achieve this

unkempt nova
#

Oh I see what's going on I think, you keep restarting the clip over and over

unkempt nova
#

I think you're cutting yourself off

ember torrent
#

intentionally

unkempt nova
#

Ah, ok

undone coral
#

it will never loop correctly this way

unkempt nova
#

Shouldn't that last one be isTalking == false too?

undone coral
#

your audio clip isn't exactly a multiple of your variable frame rate. there will be a pause between the clip ending and starting

#

๐Ÿฅบ

ember torrent
undone coral
ember torrent
undone coral
#

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

unkempt nova
#

Sounds like just text sound effects to me

undone coral
#

๐Ÿฅบ

#

the timeline package lets you declare looping audio

#

so that it loops correctly

fickle mango
undone coral
#

no guys

#

please

#

i'm begging you

ember torrent
#

im literally just trying to replicate undertale dialogue audio for a fan game btw

undone coral
#

you can't loop audio using an IEnumerator or by attempting to recreate a loop

fickle mango
#

why not? ๐Ÿ˜ฎ

unkempt nova
#

Weird, see it done all the time

#

He's not trying to loop it per se

undone coral
#

it's okay. do what you need to do

#

i have given the answer

thin mesa
#

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

undone coral
#

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

ember torrent
undone coral
#

it's okay

fickle mango
#

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);

undone coral
#

i have helped as much as i can

urban warren
#

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.
}
ember torrent
undone coral
ember torrent
undone coral
#

if you attempt to do that yourself you'll discover why its tricky

urban warren
undone coral
#

there are many ways to get around this. one is

urban warren
#

Pft, this architecture is getting too complex with too many layers :/
Well thanks, back to the drawing board.

undone coral
#

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>();

undone coral
#

you need to use the out keyword

#

sorry my bad

#

you can achieve what you want

#

is this helpful @urban warren ?

urban warren
#

(Reading, second)

urban warren
#

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!

undone coral
#

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

unkempt nova
#

First time seeing an actual definition for these

#

Pangloss, you able to give a shortbus example of covariance vs contravariance?

undone coral
#

๐ŸšŒ

#

it's saying that covariance is when you want to prove something is something else

unkempt nova
#

Seems like Covariance in this context lets you make things return more types of things, what is contravariance then?

undone coral
#

and contravariance is when you want to prove something is NOT something else

unkempt nova
#

Oh, interesting. Thanks

undone coral
#

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

unkempt nova
#

Hrm. Interesting. Generics still make my head spin

undone coral
#

so here's a real world example

unkempt nova
#

multiple copies of this interface (with different contravariant types)
I don't understand what this means though lol

undone coral
#

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

unkempt nova
#

Sounds like this would be for having INode, which returns a node, then IFloatNode which returns a FloatNode or something?

undone coral
#

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>>

unkempt nova
#

Oh I see

#

I forget interfaces can be generic too

undone coral
#

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

unkempt nova
#

Interesting. Thanks for the explanation. Makes a bit more sense now

undone coral
#

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

unkempt nova
#

To make sure it uses the type you specify, instead of a more derived type? Or is it a less derived type. Not sure

undone coral
#

i think so it uses the most derived type it can

unkempt nova
#

Cool. Didn't know we could influence that

undone coral
#

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.

unkempt nova
#

Hrm, yeah, so in this case you'd implement ICovariant or IContravariant to determine which X it uses there?

undone coral
#

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

unkempt nova
#

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

undone coral
#

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>

unkempt nova
#

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

undone coral
#

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

unkempt nova
#

Yeah you were saying that

honest hull
#

In a indexbuffer graphicsbuffer, whats the format of it? aka, how do I successfully read proper values from it?

stuck onyx
#

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?

fervent parcel
#

hey guys, where do I start with trying to add my own buttons to these:

#

I dont even know what to google

next marsh
mystic swift
#

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;
    }
humble leaf
#

Don't crosspost @mystic swift

mystic swift
#

Alright.

kind flare
#

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?

next marsh
#

NetworkManager.singleton.StopHost();

#

Or if it's not a listen server,
NetworkManager.singletop.StopServer();

#

I'm not sure about the FizzySW though

next marsh
#

I.e. what are the expect results?

mystic swift
#

@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.

kind flare
next marsh
#

That'll close the lobby and all players will time out. Use StopClient(); to disconnect an individual player

kind flare
#

This is for unity networking tho

next marsh
#

I'm not sure, for that you should check in the official discord for it

#

The Fizzy discord

next marsh
next marsh
kind flare
# next marsh I'll see if I can come up with something

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

next marsh
#

Ah just cut singleton then

#

NetworkManager.StopHost();

kind flare
#

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

shadow seal
#

In Mirror NetworkManager.singleton.StopHost() is correct

#

Do you have a class named NetworkManager?

kind flare
#

yes

shadow seal
#

Your own one?

kind flare
#

I got a custom script networkmanager

#

Not really, got it from a yuoutube tutorial

shadow seal
#

Does it derive from Mirror's NetworkManager?

kind flare
#

Yes I think so, tutorial was from Zyger, using mirror and steamworks API

shadow seal
#

You think, it's your class

kind flare
#
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

shadow seal
kind flare
#

Okรฉ, no

next marsh
#

Hmmm

shadow seal
#

Try using your class's name

kind flare
#

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

toxic wraith
#

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?

kind flare
kind flare
# shadow seal

Like this or do I need to add something in my networkmanager first?

shadow seal
#

If you want to StopHost, that's how you do it

kind flare
shadow seal
#

Is that not the fault of Steamworks not Mirror?

#

Call LeaveLobby

#

It requires the CSteamID of the lobby you want to leave

toxic wraith
kind flare
#

This is the entire lobbycontroller script

#

Where I put the "Leave button" function

shadow seal
#

That's your choice

kind flare
#

give me a sec then

kind flare
#

I tried putting the leave button in there, all the way at the bottom

shadow seal
#

Ok

kind flare
#

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

shadow seal
#

Close the lobby when you return to the main menu

kind flare
#

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

shadow seal
#

Because lobbies are not a Mirror thing, they are a Steamworks thing

kind flare
#

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

shadow seal
#

You can migrate it, it's another method

kind flare
#

Yes, thats SetLobbyOwner

#

Also don't know how to use that :p

shadow seal
#

Read the docs

#

It wants a lobby ID and the new owners ID

kind flare
#

Well that's the part I don't know how to reference to

shadow seal
#

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

kind flare
#

I'm using that code in the CustomNetworkManager

undone coral
undone coral
honest hull
#

Where do I get the transforms needed to transform vertices from a skinned mesh to world space?

undone coral
#

that interacts with skinned meshes

#

i know just the one

honest hull
#

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!

kind flare
undone coral
#

i personally think mirror is really overrated

kind flare
#

I mean, I've been coding it now for 2 months so I'm not gonna turn to photon

shadow seal
#

I prefer Mirror to Photon but eh

undone coral
undone coral
#

you can look up its source code

honest hull
#

no I havent thanks!

kind flare
#

1 player is the monster, 4 players need to escape the maze

undone coral
#

hmm

#

like an FPS?

kind flare
#

Not a shooter, like an escape room with a monster behind you

#

But it is indeed first person

undone coral
#

it's tough

#

i'm not sure what the best multiplayer FPS unity asset store asset is anymore

honest hull
#

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

undone coral
#

because it's so arcane

honest hull
#

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?

undone coral
honest hull
#

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?

undone coral
honest hull
#

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

undone coral
#

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

honest hull
#

oh? ok thanks!

#

wait which ones keijiros package?

undone coral
#

i linked you

honest hull
#

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

gilded inlet
#

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

regal olive
#

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

Get the TriLib 2 - Model Loading Package package from Ricardo Reis and speed up your game development process. Find this & other Modeling options on the Unity Asset Store.

undone coral
honest hull
#

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?

undone coral
#

"bone"

#

which bone indeed

honest hull
#

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?

quiet bolt
# gilded inlet could someone briefly explain to me how async/await works and in what real situa...

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...

โ–ถ Play video
jade tiger
#

yo guys

#

when i open my unity project

#

it just shows game

#

and it is blue

#

the entire screen

full zephyr
jade tiger
#

mb took me 5 hours to figure out i had the game console on maximum size

arctic robin
#

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?

arctic robin
#

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.

undone coral
#

oh

#

you don't mean processes in the sense

undone coral
red osprey
# gilded inlet could someone briefly explain to me how async/await works and in what real situa...

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.
wispy epoch
#

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

undone coral
red osprey
undone coral
#

Steam Will Not Like That

wispy epoch
# undone coral 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

red osprey
#

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.

wispy epoch
#

thanks

honest hull
#

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

gilded inlet
red osprey
#

So

public void One()
{
  Two();
}

public async void Two()
{
  await Something();
}
``` ???
gilded inlet
#

assuming I want to await user input, how would the syntax look for it?

red osprey
#

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.

undone coral
flint sage
proper wing
#

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?

unkempt nova
#

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

tribal pivot
#

Unity doesnt 'call' it on the base class, you have to do this yourself. If you omit base.Update(), it wont be called.

bleak marsh
#

I'm writing some Unit Tests and I would like to prevent [RuntimeInitializeOnLoadMethod] from running in the context of the test, any idea how?

novel plinth
#

RuntimeInitializeOnLoadMethod is after awake if I'm not mistaken, so you can put a guard-clause to the method tagged with that attribute

#

note that the default RuntimeInitializeOnLoadMethod is after scene loaded, unless you do it like this [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]

signal moth
#

I have cors errors when doing this

somber tendon
#

cors usually handled from back end / server side

fresh salmon
#

Yep adjust your server accept headers if you have access to the config, or request a change to your provider

bleak marsh
novel plinth
#

huh?

#

what loadType you're using?

bleak marsh
#

All of them

signal moth
#

this is my cors error, something about redirects? unitywebrequest cant handle those?

bleak marsh
#

Every single one of them runs before Setup

foggy dew
#

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

chilly talon
#

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.

novel plinth
#

you make a source generator, yet you don't know what that error is? ๐Ÿ‘€

chilly talon
#

Just when building, it seems to not actually "use" the source that is being generated.
But skip it.

scenic forge
#

What platform are you building?

chilly talon
#

Windows

scenic forge
#

Weird

chilly talon
#

Wait, it may be .. Hold up.

scenic forge
#

Btw you should uncheck all platforms not just editor and standalone

chilly talon
#

Should be all good

scenic forge
#

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.

unkempt nova
fresh salmon
#

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.

bleak marsh
#

@novel plinth // I can make a reproducible example later

novel plinth
#

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

chilly talon
scenic forge
#

Yes.

chilly talon
#

Odd.

foggy dew
scenic forge
# chilly talon Odd.

Depending on what you are using SG for, you may consider using an editor script instead.

chilly talon
bleak marsh
somber tendon
ivory prawn
#

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)?

bleak marsh
somber tendon
sly grove
bleak marsh
#

there is no hosting

#

no multiplayer

#

just editor, my code and tets runner

#

not published, not built

sly grove
#

The test runner starts up a minimal web server to host the game

agile yoke
#

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

bleak marsh
#

I'm not running those test in a build

bleak marsh
#

I guess my only solution it to ignore the problem and pretend this method is never run

somber tendon
bleak marsh
#

No problem

chilly talon
teal bluff
#

hello
if there are 2 colliders on a gameobject
how do i only check collisions for one of those colliders

sly grove
#

Also don't crosspost

teal bluff
#

my bad

#

i though i deleted the other messages

novel plinth
#

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))
     {
     }
 }
steady matrix
#

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?

novel plinth
#

cool! so what's the problem?

steady matrix
novel plinth
#

most probably that?... I'm not a chess player but I watched some grandmasters played and they used that

obsidian glade
fresh salmon
#

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

novel plinth
#

yeah, people rarely used Diagnostic class for ingame purposes

steady matrix
steady matrix
#

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?

scenic forge
obsidian glade
#

it's a tuple (of tuples)
(int x, int y) pair

is similar to

struct Pair
{
    int x;
    int y;
}

Pair pair;
hollow garden
#

yeah kind of

#

although c# goes haha trolled and ValueTuple<int, int>

hybrid plover
#

Does anyone have experience with writing a list of vector3's to a texture2D?

#

Kinda stuck on step 2

sage radish
hybrid plover
sage radish
hybrid plover
#

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

sage radish
hybrid plover
#

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

sage radish
#

This example is passing it to a compute shader with SetBuffer, but you would just replace it with visualEffect.SetGraphicsBuffer(propertyName, vertexBuffer)

sage radish
hybrid plover
#

Hmm yeah I'll try! But will it still work if I scale it?

#

I scale the transform

sage radish
#

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.

hybrid plover
#

oh okay I see! thanks for the help. I'll try it out ๐Ÿ™‚

tribal pivot
#

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.

#

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)

sage radish
tribal pivot
#

Essentially yes

#

Atm i have a bottleneck of nearly 2ms calling Graphics.DrawMeshInstancedIndirect, i thought scheduling all in advance would be faster

sage radish
#

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?

tribal pivot
#

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.

glacial wedge
#

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

hallow elk
#

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:

tribal pivot
#

What version of Unity are you on?

hallow elk
#

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

daring sandal
glacial wedge
#

I think u should use 2021

fresh salmon
#

Or the fact that not all of the features of one C# version are enabled in Unity

scenic forge
#

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.

tribal pivot
#

Afaik 2021 supports c# 8

sly grove
#

Except for a few features...

scenic forge
#

Yep, can also see that from the csproj it generates.

daring sandal
#

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

hallow elk
undone coral
undone coral
daring sandal
#

๐Ÿ˜ฆ

undone coral
#

are you using unitask?

glacial wedge
#

no, I'm using an AsyncAwait library

#

and I found that i was missing the asmdef for it

#

solved it. thx

undone coral
#

you should use unitask

#

what library is "AsyncAwait"

#

"Web3Unity" very concerning...

glacial wedge
#

I found it very helpfull to interface my webgl build to metamask and other web3 services

hybrid lichen
#

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!

undone coral
#

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

hybrid lichen
#

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

topaz pilot
#

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.

fickle mango
topaz pilot
#

No, just the basic "assembly-csharp"

topaz pilot
fickle mango
#

have you tried adding 'using NameOfNameSpaceOfAssemblyDefinition' in your player script?

topaz pilot
#

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

fickle mango
#

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

topaz pilot
#

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

fickle mango
#

so it worked?

topaz pilot
#

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'

fickle mango
#

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

topaz pilot
#

Ahh

#

Would that class work as a middle man?

fickle mango
#

I hope the base class has virtual methods, try writing
'override' and see if it suggests a collision method

fickle mango
topaz pilot
#

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.

fickle mango
#

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

whole quest
#

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.