#archived-code-advanced

1 messages · Page 158 of 1

wispy terrace
#

Also, why dont you call initValues() on setCard() just after you assign card = c?

#

That way you will not have to call initValues() once every frame

#

Does CreateCard get destroyed or public Card card; in CreateCard reasigned?

high sluice
#

i made createcard a func that happens when i press a button

wispy terrace
#
    public void setCard(Card c)
    {
        card = c;
        initValues()
    }
#

And delete the update function

#

I meant the CreateCard component, does it get destroyed or disabled?

#

And the public Card card; variable in the CreateCard component, Does it get reasigned?

high sluice
#

the createcard component just remains thr

high sluice
wispy terrace
#

Where is the CreateCard component attached to?

#

Also, the CardDisplay component is attached to a child of the main objects prefab

#

But you are trying to find the component in the parent object

high sluice
#

its in the game scene

wispy terrace
#

There is no button in this scene

high sluice
#

wait

#

its like this for me, its not for u? does exporting not carry over scene data or did i export wrong

#

but anw if it isnt thr u can prob just make a button that would run createcard when clicked

#

yea i made a new one n imported what i just sent n idk y the button isnt thr :c. anw just make a button

wispy terrace
#

Right, I found a bunch of errors

high sluice
#

mm same i just dk how to fix em

#

like idk how to call setCard lol

wispy terrace
#

First off, you are using scriptable objects, the script "Card" only sets the architecture of the scriptable object

high sluice
#

sry i barely understand that i just used scriptable card as i saw a vid some1 sent on it

wispy terrace
high sluice
#

but should i not use scriptable card or?

#

yea that

wispy terrace
#

Have you seen it all?

high sluice
#

yea

#

i manage to make a card but idk how to throw that into the create card func

#

like make a card n insert the values in

#

i just dk how to make a func that can instantiate a card then insert the values in

wispy terrace
#

You make the script which tells what information the scriptable object contains, and then, you make a scriptable object for each of the cards

high sluice
#

cuz in the vid he doesnt instantiate cards n they r all alr objects taht exist

#

err can u give an example

wispy terrace
#

Ill make a video

high sluice
#

oh lol ok thanks

wispy terrace
#

I did fix something else that's not in the video

#
public class CreateCard : MonoBehaviour
{
    public GameObject cardTemplate;
    public Card card;

    public void createCard()
    {
        GameObject createdCard = Instantiate(cardTemplate);
        createdCard.transform.GetChild(0).GetChild(0).GetComponent<CardDisplay>().setCard(card);
    }
}
#

Because the CardDisplay component is in the child of the child of the main objects prefab

#

TextMeshProUGUI is what display the text, so what you have to store in the scriptable object is the text you want to be displayed (string)

#

Then you want to create a "Card" scriptable object for each card in the game by rightclicking > Create > Card

#

And store the stats of the card into the scriptable object

high sluice
#

um i took a bit of effect to make the text TMPro instead of text n string but i think both work

#

also i think the main thing is this line cs createdCard.transform.GetChild(0).GetChild(0).GetComponent<CardDisplay>().setCard(card);

#

after i did this line it worked

#

the rest of the changes u made in the vid r mainly changing TMPro to String or text right

#

createdCard.transform.GetChild(0).GetChild(0).GetComponent<CardDisplay>().setCard(card);

#

could u explain this tho

#

.transform.GetChild(0).GetChild(0)

sly grove
#

created card's first grandchild, you might say.

high sluice
#

so in this case its cardtemplates -> canvas -> cardbase -> CardDisplay component of CardBase?

wispy terrace
#

What you spawn is CardTemplate, but the script you want to access is in CardBase, which is the child of Canvas which is the shild of CardTemplate

high sluice
#

then if i instead used getchild on cardbase, getChild(0) would get me Cost? (1) would get me Health? or whats the index based on

wispy terrace
#

Exactly

high sluice
#

hm so the index is based on how i arranged the prefab

wispy terrace
#

Bear in mind, that before you get a child, you have to get the transform of the object

high sluice
#

but my general idea is to make a card like this and to instantiate it, from what uve seen, is there anyway to do this more efficiently?

wispy terrace
#

createdCard.transform.GetChild(0).GetChild(0).GetComponent<CardDisplay>().setCard(card);

high sluice
#

oh yea about that, why do i need to get the transform?

#

i thought the transform just refers to the position of the object? xyz coor, rotation scale

wispy terrace
#

Because the transform is what holds all the positioning information, and childs follow the transform of their parents

high sluice
#

if i didnt use transform n just used getchild?

wispy terrace
#

You'll get a fat error xD

high sluice
#

oh yea i do

high sluice
#

also ty a bunch

#

got stuck here for like 8h hahhaa

wispy terrace
#

You could put the component on CardTemplate, and doing so, you could delete the whole "transform.getchild(0).getchild(0)" shenanigans

high sluice
#

btw whr did u find this .transform.getchild thing

#

hm as in put the carddisplay on cardtemplate instead? ic

#

but i mean like

#

changes like using a diff system

#

like inheriting from something other than scriptable obj

#

or using a diff method

high sluice
wispy terrace
#

Well, there are plenty of ways of doing anything on Unity xD

#

It depends on what you want to do with the game

#

That system is good enough I would say, if you dont plan on adding logic to the cards

high sluice
#

err i plan on adding other stuff like event listeners for when they enter attack etc

#

but thats for later

#

should i do something now so itll be easier later?

#

also is this like some basic unity stuff

wispy terrace
#

The parent and child relationship? I would say yes

high sluice
#

i just watched a few unity vids from unity learn but idk

#

hm ic ig i shld learn more unity

#

any place to learn ud recommend? is unity.learn good? or?

wispy terrace
#

And I would not recommend to make a fully functioning tcg if you haven't much experience

high sluice
#

:c lol

wispy terrace
#

But if you want to do it anyways, I would recomend you look into Inheritance

high sluice
#

hm ill prob just run through the unity learn again i guess

#

i learnt a bit of OOP with java

#

but its kinda diff with unity n cs

#

idek whr to start lol

wispy terrace
high sluice
#

ah im kinda bad at reading doc

wispy terrace
#

I'd say Unity Learn is a good way to start

high sluice
#

dont do it much

#

did u start with cs? or unity?

wispy terrace
#

I started with unity but everyone recomended me to learn C# before doing anything considerable in Unity xD

high sluice
#

hm ic

#

anw thanks again

wispy terrace
#

Np

kindred tusk
lost crest
#

@high sluice best advice, make a bunch of smaller games first. before you attempt a large one. so you can better understand the basics of unity and C#

wispy terrace
#

Man, I've been looking into networking and I've got a lot of questions:
-What's the best network api for a Tabletop Simulator kinda game?
-How do you host a server on the cloud? (or rather, how do you do so for free?)

#

I've made some games with the Transport Layer before, but they were games just my friends and I would play, and they have no use for my IP nor did I care about theirs

#

And because I don't know how 3rd party server hosting (like, anything other than local hosting) works, I don't know what would be better to use for networking

wispy terrace
#

I can't find a single free alternative to host the server so I'll change my question:

#

-How safe is it to host it in my machine?

flint sage
#

Peer to peer networking?

flint sage
wispy terrace
#

Right, never thought of that, i've got a (don't remember the word) changing IP

wispy terrace
#

Yes! That word xD

#

I suppose you need a static IP to do so

autumn bolt
#

I'm in the same hole rn trying to wrap my head around networking to make a MUD client and server (lol), so I don't think I can help too much with this. I can however agree with Navi that you would probably want some sort of Peer-to-peer networking system. have you tried something like Mirror or Proton (I think thats what it's called? I'm pretty rusty with Unity since I just came back to using it today)?

#

speaking of networking, I might as well ask something I'm suffering with rn

I am making an MUD-like client and server for a game that sends and recieves data via TCP and is formatted in JSON (this project was originally with a lua client, but my friend and I decided to make the client with Unity for easier controls and better graphics instead of relying on making our own rendering engine).
sometimes, the data being recieved can be as small as {"message": "login successful!", "user": "User"}, but it can also be as big as {"Players":{"User":{"Name":"User","Coordinates":[1,1],"direction":"north","currentRoom":0,"CurrentHealth":10,"Data":{"Class":0,"Skills":[0,0,0],"Inventory":[],"Equipment":[]}}},"type":"worldupdate"} (practically, this would be even bigger). what would my best option be for to parse data like this on the client side?

I apologize if the question looks like a mess :P

wispy terrace
#

How would I go about giving the clients a list of hosted games through peer to peer? Also, isen't it a bit shady that I have to collect all of their IP's and give them away to other players?

simple badge
wispy terrace
#

So maybe, make them upload and download an updated list of hosted games through dropbox or something?

simple badge
#

But know that you cant simply connect to someones ip without them doing port forwarding, you'd have to hole punch

simple badge
#

As for hosting, you either have to host yourself or forget about "free". Servers start at less than 5$ per month though

#

At digitalocean, for example

wispy terrace
#

Welp, now that I know I have to host locally anyway or pay, I guess I'll go with the p2p alternative to lower the load to my poor computer xD

tardy sail
wispy terrace
#

Thanks!

simple badge
simple badge
wispy terrace
#

Yeah, but I was just a bit scared about giving away public IP's

#

And I thought that was the best alternative anyway because hacking would not be a problem in this kind of game

#

But I thought there would be a hard and intricate way of cyphering the IP's or something like that

#

I'm actually happy I was wrong

#

And lucky me, seems like FizzySteamworks bypasses the need for hole punching

glacial wedge
#

I have a code that reference my ScriptableObject and changes some values, when I stop playing the asset is changed. I wont change it, so I added a clone function to perform changes on a copy of the asset:

public static T Clone<T>(this T scriptableObject) where T : ScriptableObject
        {
            if (scriptableObject == null)
            {
                Debug.LogError($"ScriptableObject è null. Restituisco {typeof(T)} vuoto.");
                return (T)ScriptableObject.CreateInstance(typeof(T));
            }
 
            T instance = Object.Instantiate(scriptableObject);
            // instance.name = scriptableObject.name; // remove (Clone) from name
            
            return instance;
        }

and when I enter in playmode I see that my code reference the (Clone) of ScriptableObject, but the changes still are applied to the asset. So I think that this happen because in my ScriptableObject I have reference to others that are saved inside and probably my Clone function doesn't clone the children.

How to solve my problem? there is a way to get children of ScriptableObject without specify the class and ciclyng its variables?

glacial wedge
#

is it normal that the changes are saved from runtime?

spark forum
#

if you don't want persistent changes in scriptable objects you might want to create a data holder class that mimics the structure of the SO, and just copy the values over after loading the SO

glacial wedge
#

yeah, i'm working this way

#

all seems to work as expected

#

I used a class data holder with a constructor from the SO

#

but I thought that the default behaviour of scriptableobject doesn't persist changes made in runtime

#

my bad

small badge
#

Changes to gameobjects in play mode will be lost; changes to assets in play mode will be saved. (ScriptableObjects stored as part of the scene are a weird edge case in many ways; I would guess they behave like assets in this case, but I've not tested.)

regal olive
#

hey I'm trying to dissect GTGD's code and I have his network manager in my project but I get this error. public class Network_CustomManager : NetworkManager. the type or namespace name 'NetworkManager' could not be found

hushed fable
#

GTGD = Gamer To Game Developer YT channel? Make sure using statements are correct and that you have all dependencies required

#

Decent chance it uses some networking library/framework

frigid elbow
regal olive
#

ya they're the old unet, but I wanted to use the matchmaking system

regal olive
# wispy terrace Man, I've been looking into networking and I've got a lot of questions: -What's ...

It depends on what your expectations of the game is. If you any real time ‘immediate’ interaction, look into having the unity game client establish a TCP sockets. If you are okay with a bit of travel time for each network message, request/response model is okay and easier.

How do you host it on the cloud? Typically a cloud vendor offers compute for a fee (e.g. in AWS the compute instances are EC2 instances). Spin one up. I prefer Linux but others like windows server, with the GUI and buttons and everything. Now it depends on your server implementation on what happens next. For me, I’ve used mirror library with a central authority server setup on Ubuntu OS using just a terminal interface and I’ve had to install some things to be able to run the server using the ‘screen’ binary. Remember, your code has to keep this use case in mind so don’t hard code IP addresses in the code or anything. Make sure that instance can speak on whatever port you want your game to run on.

Now you are ready to connect a game client. I have had setups where the user then needs to know IP addresses and then type it out. Lame. I now usually put up an HTTP endpoint that provides all this information so the game client can do stuff under the hood.

Oh wait, you want it for free? Umm maybe not the cloud then. You can run your own server from your house. It’s difficult but if you have more time than money, it would be a great learning experience. Just take precautions as your home network will basically be opened up for potential attack from the public internet.

regal olive
regal olive
regal olive
#

The groovy thing about TCP is that you get to define your interactions with our a whole lot made for you. It’s a bless and it’s a curse.

For me, I’ve used a socket to send many types of messages like it seems you want to do. Parsing depends on message. I typically use a JSON parsing library, and I usually bundle up the logic of instantiating a object representation of the message (vs the raw bytes) in a factory method.

I would say that technique affords you the ability to leave the socket communication details in a small part of your code base, and let’s you model stuff in code.

#

“The best?” I don’t know.

regal olive
regal olive
# wispy terrace How would I go about giving the clients a list of hosted games through peer to p...

Yea it’s shady. P2P kinda sucks in that way because clients need to talk with clients running on other users hardware. Hackers love having that info, as it lets them troll a bit harder.

…and if a hacker is elected as the authority instance, lmao… just…

Central server authority is just a better way to go in my opinion. You control where your server is running and what it’s doing. It’s more fair to the players than P2P. And since player’s client is talking through the server to other clients, everyone’s client just sees your game server and not each other’s hardware, if that makes sense.

regal olive
# flint sage Your isp might not allow it

I have put web servers and game servers hosted from my home network. It’s been for testing purposes and never for production traffic.

If you were running something with a large amount of traffic you will probably get a call from your ISP. But let’s be honest, a fledgling game server isn’t going to be near enough traffic even if they shared the info with a discord channel.

I bet the hardware running the game server fails before an ISP cares.

regal olive
regal olive
#

Apologizes for the waaay after the conversation replies, dear channel... When I see discussions about multiplayer I get pretty excited. I replied as I was reading, ha.

Multiplayer is the bees knees

#

FWIW on the topic of multiplayer... if you are looking to run a game server on a linux based operating system this guide gives here you a good sense of the sorts of binaries to install and command you will need to run.

https://mirror-networking.gitbook.io/docs/faq/server-hosting/google-cloud

I've used this guide to help me create docker containers for my game servers (which I then run in kubernetes)

#

I've found that having a game client running in server mode should handle the game logic. I also usually build a RESTful interface (in whatever programming language I want to learn more about) for supporting services for the game.

It gets complex quick so I'll hold back details unless there are some who are curious

#

But yea, I usually do a hybrid setup involving a unity game server and then RESTful APIs for supporting services

mighty cipher
#

Anyone Used to build IOS / MAC build with Unity ? i'm facing a small problem i built my project into xcode as it need to be added some DLLS etc. but it's saying can't found library -lc++ i don't really understand why since the scripting backend is MONO, however anyone can help me fix this error ? (someone comfi with mac plz)

hard solar
#

What is the fastest way to load images to gameobjects from your local drive? I've looked into using UnityWebRequest to locally load files (holds 22gb of my memory for ransom) and Sprite.Create which turn out to be an expensive operation, resulting in wait times of over 3 minutes when loading nearly 12,000 jpgs.
https://pastebin.com/AgJeamfL
This script seems to solve my other issues; it takes between 12-22 (one case, it was 40) seconds to fully finish executing and increases my memory usage by about 1.6 gb, which is honestly pretty good comparatively. However... I want this to be faster. If I can get this down to a max of 10 seconds, I would be pretty happy. I would think multithreading this would be a perfect way to get the times down, but Unity has locked down texture-usage in its main thread and the job system doesn't seem to allow for loading these images in parallel. What can I do to increase the speed of loading images onto gameobjects for 12,000 of them?

sly grove
#

I doubt you're showing them all on screen at once

#

you can load them on demand

hard solar
compact ingot
sly grove
#

Or if the user is scrolling through a list, if you know which images are coming up in the list, you can start loading them before they appear on screen

regal olive
# hard solar I am not showing it all on screen at once. I was more concerned about having eve...

I wonder if the benefit is worth the cost of implementing what you are after: loading up all images at once so the user doesn't experience lag when they are searching. It is worth doing if it is indeed worth doing; techniques from the web world will definitely help.

I imagine it won't be acceptable for the app to take ~1-5 minutes to load, so we have to talk about loading images in chunks.

Assuming all users start out with a similar viewing experience, you can prioritize some images as 'immediate load' so your user can start using the app ASAP. Then, you will have to be smart about how you prioritize loading more images.

E.g. if you know common searches users typically use your app for, then you can prioritize those common searches next. Try to load up the top 20% of images that handle 80% of the use cases is the goal/ideal.

Also, given the stuff you are loading is so huge you should make sure the images are cached local to the client. As the user uses the app, over time it should load up basically all the images.

mighty cipher
#

if it's on PC i have an async load image thing @hard solar working with threads to load ur images faster

#

so it doesn't impact heavily ur project

#

don't know if that can help

#

anyone have seen my issue about Xcode ? i'm a real begineer with IOS stuff

#

and i don't find that many answer on google

hard solar
#

My apologies, I just wanted to test out UWR again, so let me respond in the order of replies...

regal olive
mighty cipher
#

it's not for native mobile ios

#

it's just a mac build

#

but seen that in order to bring the DLLS i have to make a xcode project

#

yep basically i can build from Unity to MAC, but the DLL doesn't follow

#

but anyway i'll have to also build for Ipad so the xcode thing is just a problem that'll happend at a time

regal olive
#

it's saying can't found library -lc++
It seems like something in your project needs c++

#

Probably see about installing that on your system. I wonder if I haven't had an issue because I use and have configured Rider before, which stepped me through installing some stuff...

hard solar
# compact ingot `UnityWebRequestTexture.GetTexture` is fastest without manually creating GPU rea...

Here is the snippet I wrote when using UWR: https://pastebin.com/c6V8weQt This takes about 45 seconds to finish going through (in the case of loading everything up) and rapidly increases memory usage up to about 20 gigabytes of system memory, which is pretty terrible. It's very possible that something is missing or this was written incorrectly, but I would like to hear your thoughts on it.

mighty cipher
#

gonna install Rider and see if it fix the thingy haha my mac is only a "build" computer so i don't have a lot of things installed, will see if that fix the thing @regal olive will keep u posted

regal olive
#

Cool. This is just a guess. Definitely read any and all errors you encounter. Sounds like you might have to do the research thing where you find a bunch of info and have to synthesize what they are saying for your use case.

lost crest
#

@hard solar so this is just to show images for user selection? i wrote some editor window code to do something like this. i built a SQL backend with thumbnails. It was for a texture browser for game dev. so i could have external itexture library. it loads 6000 images pretty quick. but you need this for in game. not sure how hard to get the SQL running in game code. might not be to hard

regal olive
#

Which... Honestly, pretty often devolves into finding commands online and just running them.

mighty cipher
#

y y i know @regal olive just was looking if someone had the issue before and a quick fix

hard solar
lost crest
#

yah that would make it faster. smaller thumbnails load pretty quick

#

only issue i had was tiff files would not convert correctly. i did all the thumbnail creation inside unity. that took time. but after that the database was quick

lost crest
#

i used Mono.Data.Sqlite.dll file for the sql database. put in assets\plugin folder

hard solar
# regal olive I wonder if the benefit is worth the cost of implementing what you are after: lo...

Users would have a similar viewing experience. They would be on a screen where they can view images on a "collection" screen. In this case, looking at what cards they have in their deck. I see where you are coming from, prioritizing the images they see first (in this case, their deck) and then loading more as time goes on when the game is running. I have an idea of "staple" cards users could search for and maybe see if I can load those up first.

lost crest
#

there maybe better ways to do this. just what i came up with

hard solar
compact ingot
#

20 GB is approximately 12k 512x512 RGBA textures

#

and your code looks like you are storing all those textures in a datastructure

mighty cipher
#

using FreeImage @hard solar

lost crest
#

my 6k library is 182GB file size. takes seconds to load thumbnails. db is only 100k

hard solar
# compact ingot how much data should it be?

That's... quite interesting. The big image folder has a size of 713 MB, while the small image folder has a size of 190 MB. The sizes are either about 421x614 (big) or 168x246 (small)

compact ingot
#

does not matter how big they are on disk

hard solar
#

So about there.

compact ingot
#

if they are jpg their disk-size is probably 10X smaller than when decompressed into RGBA

mighty cipher
lost crest
#

@mighty cipher nice, i may have to try that on my asset browser

mighty cipher
#

Np

#

on my project i use to load shit ton of images

#

and that helped a lot

lost crest
#

@hard solar okay you have some ideas now. good luck i have to run

hard solar
# compact ingot and your code looks like you are storing all those textures in a datastructure

The structure I'm using is a game object with a component that allows the texture to be stored in it. Once the co-routine is done, I place it into a method that should move over the texture to a more "proper" gameobject with the components and items I'd need. It's admittedly a bit messy in that way. Though, I'm still not sure why using UWR takes up a lot of memory when using raw images uses so much less.

mighty cipher
#

doing also a thing where i load shit ton of images for a big pharma grp

hard solar
hard solar
mighty cipher
#

and then being able to mesure stuff accurately inside the pictures

#

@hard solar sure np

compact ingot
#

i.e. the texture never gets garbage collected although it isn't referenced anywhere in the C# side of unity... but explicitly marking it as invalid fixes that

sly grove
fresh salmon
#

What is going on with the NFT posts lately. It's new alright, but it doesn't allow people to post ads here and there

if (message.Contains("nft", StringComparison.OrdinalIgnoreCase))
  return;
odd mesa
#

am sorry

odd mesa
#

ws just lookin for helping hands

regal olive
#

God I hope not. NFTs are the future.

fresh salmon
#

Advertising is the issue here

#

Not NFTs

regal olive
#

^^^ this

odd mesa
#

i was tryna just show progesss and i need help frm devs

#

am building on unity

fresh salmon
#

Well, you are, you're searching for people to work on your game

#

That's a job advertisment

odd mesa
regal olive
#

Technically speaking, we all are searching for people to work on our games when we ask questions...

#

To donate their brain power.

odd mesa
#

please i need help its a distress call

regal olive
#

Um, then ask your question...?

odd mesa
#

message deletd

fresh salmon
#

Just so you're on the same page, collab requests go on the Forums, if your question is not about a single issue.
For example, "I need someone to do the programming of the whole game" falls into a collab request

#

"I tried to do XYZ but it didn't work, here's my code" does not fall into that category

regal olive
#

Agree. Feel free to use this channel to ask questions or discuss how NFTs impact software design. Please don't use this channel as a means of recruiting devs, if that was what you were doing. We can help and honestly many of us love to think about this sort of stuff. But the purpose of this channel needs to be respected is all.

#

Which... I mean, I was literally just talking about NFTs and video games on VR chat last night. So I'm primed lol.

I love web 3.0 because of the crypto wallets being used for authn. I love the idea of not having to write yet another username/password/email login/sign up/password reset portal. For web 3.0, your user is identified by their wallet. Hell yea!

#

I love the idea of your game saves living in your crypto wallet, too. I also love the idea of generating NFTs as you play a game. Imagine NFT achievements! So cool!

#

Just to further discuss the idea... I could see a market for a really popular streamer's in game NFTs. Imagine someone like doctor disrespect selling off some battle royal victory NFTs he won on stream. Like, what?! Awesome!

#

(full disclosure, I've written a NFT algo trader and worked with some artists to generate NFTs. I haven't turned my python stuff into C# yet, but... It's on the road map)

odd mesa
fresh salmon
#

On the Unity Forums

odd mesa
#

ok let me chk

fresh salmon
#

Expect people to not work for free in this case

odd mesa
fresh salmon
#

No, the Unity Forums, the website

#

(scroll all the way down)

merry robin
regal olive
#

I’ll work for free if it’s an interesting topic. I love helping people out on discord

hardy hawk
#

I have a subscene that is instantiated at a dynamic position. I used to set the root gameobject to said position but with static batching this isn't possible anymore, anyone who had similar problems?

torpid sky
#

If anyone has experience with UI Toolkit, I have some code that has unexpected behaviour and I'm not sure if it's my fault or a bug with UI Toolkit.
I'd appreciate if someone could look over it, I didn't find anything wrong.
https://forum.unity.com/threads/pointermoveevent-localposition-returns-incorrect-value.1220244/

drifting galleon
drifting galleon
drifting galleon
drifting galleon
regal olive
#

@drifting galleon uhhhh

regal olive
regal olive
drifting galleon
drifting galleon
regal olive
# drifting galleon giyf

Yea no I have a yubikey at work but, are you serious? So instead of a crypto wallet (which is getting huge) you think people would be more into carrying around a usb stick? How do I auth that for a phone game?

drifting galleon
drifting galleon
frozen imp
#

@regal olive For the record, topic of NFTs has nothing to do with this server. Please discuss it somewhere else along with other scams.

drifting galleon
#

+1

austere jewel
#

It's been two minutes. Please do not cross-post.

regal olive
austere jewel
regal olive
#

Sure. Thanks for clearing that up. As long as it is within scope of advanced code in unity then Web 3.0 talk is on topic.

I won’t respond to attacks on me in the future. Everyone has their own opinion on tech trends, and sometimes they take out their aggression on those who don’t share their opinion.

drifting galleon
#

no one took out aggression on you

golden oriole
#

Asked in #archived-code-general a bit ago, question's not getting any traction.

I have kind of a funky effect that's happening that I'm having trouble figuring out. When I reach my defined terminal velocity, I start adding a scaled opposing force. While moving, the character's movement force and the friction force are equal, but I'm still getting a 0.25 forward movement. No matter what I set for terminal velocity, I'm always ending up 0.25 faster than my defined terminal velocity. Does anyone know why this might be?

I am adding by doing

RigidBody.AddForce(forcesSum);
frozen imp
#

You need to debug, measure it, and find out the interference.

#

Also make sure you are using it during physics update with FixedUpdate

golden oriole
frozen imp
#

If you are running code in frames outside of physics step that might explain it

hardy wharf
#

how do I set a default prefab value

plucky laurel
#

elaborate

hardy wharf
#

like I am adding a script component. The script needs a prefab value. So What I want is when the start() runs, I want to call set a variable to a prefab in my asset folder

plucky laurel
#

show attempted solution code, if any

hardy wharf
plucky laurel
#

Resources.Load(path), for example

hardy wharf
hardy wharf
#

doesnt work

plucky laurel
#

it works

hardy wharf
#

no ill show u

shadow seal
#

Inb4 it's not in a Resources folder

plucky laurel
#

lets move out of advanced coding

#

this is not an advanced question

hardy wharf
hardy wharf
plucky laurel
golden oriole
lucid citrus
#

So, I would like a CustomInspector on a ScriptableObject that allows you to add/remove a field, and modify the type of any field. The plugin Ultimate Inventory System does this but its code is all in a dll so I can't see how they pulled it off. Anyone have any tips or resources on how to achieve this?

#

Here's a screenshot of what UIS looks like that I'm trying to emulate

#

I have a list of types then I added manually and through Assembly.GetTypes() but I'm struggling to figure out how to bind data to those types. Do I box everything into an Object? And from there how do I De/Serialize it all?

#

I don't really need help with the UI part, but more advice on how to structure my data or libraries/references to use

plucky laurel
#

yeah if you are dealing with serialization you are bound to box at some point, unity doesnt do proper generics so yeah.

agile grove
#

Hey i have a question about openxr is there a way to call a function before Grab()?

shadow plinth
#

like what to do before grabbing?

agile grove
#

yea

#

i mean i want to change rigidbody setting before grab event

shadow plinth
#

Entry point is Grab() tho. Not sure how to have a function called before that

agile grove
#

or maybe you know how to change setting after drop() function?

#

right after

shadow plinth
#

probably have a reference to what u were holding

#

once u call drop, then manipulate it

#

then clear the reference so that when u pick up a new object, you reference that object

agile grove
#

okey i figure it out, thx for help anyway i called function in LastSelectExited and it worked

shadow plinth
#

ooh. i may use that next time too

coarse compass
#

I'm looking to write a tool for unity that compiles a dll for the user. Does anyone know how to compile code through c# in a unity context?

#

Happy to do it through expressions or source code, I just need any way to compile a dll

#

Please reply with ping - leaving the channel for now :)

lofty inlet
#

Does anyone know how to bring the unity exe to the front (WITHOUT using a dll)?

cobalt sage
lofty inlet
#

but if it's the easiest ig I would have to use it

cobalt sage
lofty inlet
#

if I used the dll I would have to install something?

#

or is it just code

cobalt sage
lofty inlet
#

so it is 3rd party stuff

#

right

lofty inlet
#

I don't want to use third party stuff if possible

cobalt sage
#

win 32 is a microsoft dll

#

tbh may even be able to use it by default given unity runs off c# however havnt tried this myself

sly grove
#

Win32 is installed on all windows machines by default you won't need to include it in your game

jade coral
#

i really didn't know where to post this, so i'll just write it here. I have a request of porting a project from unity 4 to the 2020 version. Unfortunately, just importing the project and letting unity upgrade it makes a huge mess with references and project files, which in return wastes a lot of time. Does anyone have a somewhat stable solution for upgrading from old unity? Would step by step, version by version upgrade be a better alternative?

woeful kraken
random dust
woeful kraken
# jade coral i really didn't know where to post this, so i'll just write it here. I have a re...

Alright I had to do a LOT of converting/upgrading at my last job. And I mean a LOT of it.

To tackle this, I'd usually go "domain by domain" first. And I'd typically start with the scripts because they were the most likely candidates for needing upgrading.

A sharp tip I started doing; I started making the "scripts" as "packages" that I'd port into my new project. And I'd start going error by error, hunting down issues and upgrading them from there.

jade coral
random dust
#

Ehhh you can try upgrading in small increments

woeful kraken
random dust
#

See when it breaks

jade coral
woeful kraken
#

also is this a one time conversion? Or are you basically adding to a studio's "core database", with the intention of seeding this to other projects?

jade coral
woeful kraken
#

and the UI isn't just code mind you - it's carving out the GUI and putting in UnityEngine.UI and then updating the actual game objects, text and all, to what's working. Including TMPro shoudl it be needed

jade coral
# woeful kraken also is this a one time conversion? Or are you basically adding to a studio's "c...

what i need to do is upgrade a serie of many projects that have been discontinued since 2015 or so. They were all using same-ish plugins, so i was thinking on re-creating the cross-project functionality. But first i need to be able to at least know what the project is supposed to do. Maybe i can try and automate the upgrade for the components in gameobjects but i don't know if it would be beneficial timewise. Fortunately it's not multiplayer hahaha i'd say no to that.

#

for shaders i'll just use default ones, it's not a graphically intensive program

woeful kraken
#

so yeah - start by adding your scripts piece by piece domain by domain. Do charge some good money because this is gonna suck.

#

[ insert Hunger Games Tribute meme here ]
Goodluck, and may the odds be ever in your favor.

jade coral
jade coral
#

u mean US? i'm in europe

woeful kraken
#

but hello, from across the pond! Keep us posted

jade coral
#

if i have any updates on the project upgrade i'll post here. Thanks so much again

glacial wedge
#

I have two classes State and his child ExState:

public class State : Monobehaviour{
  public StateData data;
}
public class ExState: State{
  public ExStateData data;
}
[Serializable]
public class StateData{}
[Serializable]
public class ExStateData: StateData{}

I want to have it's property to be of the corresponding type

regal olive
#

I wonder if a parent/child relationship is appropriate for what you are trying to model. It doesn't seem like there is enough commonalities to justify having ExState be a child class of State, especially since the data property has a different type depending on what class it is.

#

Assuming it is the right modeling technique, I would suggest renaming and using the ExStateData property. State maintains a core set of common StateData, and ExStateData can use State.data or use the data that is unique to ExState, which could be contained in public ExState exData

#

@glacial wedge above is generic advise because I don't know what your code is used for. It kinda looks like a finite state machine? If you could tell me what game play functionality you are trying to support, I (or others) might be able to provide more detailed insights for you.

glacial wedge
regal olive
#

gotcha. I would advise you keep what is common to all child classes in the base class. Anything specific to a child class should be contained in that child class.

glacial wedge
#

yes, I'm trying to make a fsm

regal olive
#

Heck yea! Is this your first implementation?

glacial wedge
#

I'm trying to give extensibility power to my old implementation

regal olive
#

Gotcha. Yea, FSMs are fantastic things.

glacial wedge
#

I've structured like States are MonoBehaviours and are added and removed from the StateMachine (that is monobehaviour too), States should work likes manager

regal olive
#

That is an interesting implementation. Does the state machine just look for all states attached to the game object (GetComponents<State>())?

I usually model my state machines as a combination of vanilla C# scripts and a monobehaviour state machine runner.

glacial wedge
#

here is how the statemachine get the needed state

protected virtual State GetState(StateDataSO data)
        {
            Debug.Log("BASE GetState");
            Component target = GetComponent(data.type);
            if (target == null)
            {
                target = gameObject.AddComponent(data.type);
            }
            State state = target as State;
            if (state == null)
            {
                throw new Exception($"{data.type} non è figlio di State oppure è astratto");
            }
            state.data = new StateData(data);
            return state;
        }
regal olive
#

Woah... Okay, fascinating implications of this code. Very cool, very interesting.

#

are you following a blog post or a video or something?

glacial wedge
#

I'm thinking on your suggestion to separate the property data to a core part and an specific part

#

no, I did it myself

regal olive
#

That is awesome!

glacial wedge
#

I checked some others fsm before starting

regal olive
#

That's usually how I approach things too 🙂

glacial wedge
#

but nobody was using monobehaviour like this

regal olive
#

Its a pretty short read and if you are implementing an FSM on your own, you might get some inspiration for your own implementation.

#

My implementation of FSMs usually has the FiniteStateMachine be a monobehaviour, use abstract interface techniques (interface, base class, abstract class, etc) in vanilla C# so that the FiniteStateMachine doesn't have to know about or really care about details of States and Transitions.

public abstract class Transition {
  public abstract bool isValid();
  public abstract State nextState();
  public abstract void onTransition();
}
public abstract class State {
  public abstract void onEnter();
  public abstract void onUpdate();
  public abstract void onExit();
  public List<Transition> transitions = new List<Transition>();
}
public class FiniteStateMachine: Monobehaviour {
  private State _currentState;
  private void Start() {
    // build states
    // set _currentState
  }
  private void Update() {
    // naive implementation; evaluate every frame
    _currentState.onUpdate();
    foreach (var transition in _currentState.transitions) {
      transition.OnTransition();
      if (transition.isValid()) {
        TransitionState(transition.NextState());
        break;
      }
    }
  }
  private TransitionState(State nextState) {
    _currentState.OnExit();
    _currentState = nextState;
    _currentSTate.OnEnter();
  }
}

(edit: note this is pseudocode)

#

With this setup, you then subclass either a Transition or a State to provide specific details. Every subclass of either of those classes conform to the "contract" that the finite state machine knows how to deal with.

glacial wedge
#

it's the same for me, I haven't any problem on State, I'm having problems on the StateData

regal olive
#

tell me more

glacial wedge
#

because I'm giving control to the FSM about the data

#

I want to save and load the state state

regal olive
#

I see. I think I would add to my state abstract interface, and defer implementation details to the subclasses in that case.

glacial wedge
#

in the overridden method I'll have : state.data = new ExampleStateData(exampleStateDataScriptable);

regal olive
#

Um. Well. I guess the simplest thing for your implementation would be to store what class to instantiate for the state data inside the scriptable object itself. You'll be on the train of dynamic programming and there be dragons down that path.

#

But, I think that is probably the most straight forward step for your specific implementation of FSM.

glacial wedge
#
    [Serializable]
    public class StateData
    {
        public string key;
        public Type type;
        public StateValue value;

        public StateData(StateDataSO so)
        {
            key = so.key;
            type = so.type;
            value = so.value;
        }
    }

this is my actual StateData class. I'm using the type value to get which State (MonoBeahviour) to use as current state

#

adding here the data type could help me?

#

i think not

#

you say in the SO itself... but the SO should have the specific data

#

am I overextending it? I could give directly to StateData all the specific values and change to another StateData class if needed

regal olive
#

Not sure? I’m struggling to provide advice 😦

I can explain how I would approach an implementation of an FSM that supports whatever gameplay feature you are trying to support. I’m not sure of the gameplay element though 😦

I can also provide some principles to design your code base. For example, try to design classes/bundles of code that have a single reason to change. If you find that a class (like State) is responsible for child class data, that should be a sign to break stuff out.

I kinda don’t think your state machine should be setting state’s data in the way you are doing it. I think, if anything, your “State” class should define a “void MethodNameHere” that gets called by the state machine, and then child classes of “State” should know how to set its data.

#

Basically, your State monobehaviour should be the thing responsible for setting up its data. Subclasses of State should override and know how to set up its own data as well.

junior plaza
#

so there is a game on roblox its called deadline the gunsmith system on there is very advanced and modular how could i acheive that in unity

regal olive
# junior plaza so there is a game on roblox its called deadline the gunsmith system on there is...

Grab a pen and paper and write down all of the features of the game as you see it. Focus on trying to find the core game systems. Reverse engineer the game and really consider the details of the game.

Once you have a general description of the game, you can think about how you would model that in code. What monobehaviours might you want? What scriptableobjects?

Personally, I recommend turning your notes into acceptance and unit tests, and letting that guide your implementation.

junior plaza
#

ok thnx

shell grove
#

Greetings everyone. Here I am with another big problem

#

The gist of the problem is that I get a NullReferenceException in Line 115

#

Line 114 reports that it found 1 Component of type KMSelectable

#

The OnInteractEnded() function also works when I call it for example in between Line 74 and 75

shadow plinth
#

hot damn thats a long where statement

shell grove
#

Yeah, the thing is I already have it saved in the class. But I wanted to make sure that it's not some weird problem so I try to reference to it directly instead.

shadow plinth
#

ah i see

shell grove
#

In Line 64 I have already saved it and normally I could access it again as I tried in Line 113

shadow plinth
#

but when it reaches line 115 it becomes null?

shell grove
#

Yes

#
[LOOK AT ME #1] LOOK AT ME! I'M THE MODULE NOW! IGNORE THE SIMPLETON
[LOOK AT ME #1] Moved successfully
[LOOK AT ME #1] 1
NullReferenceException: Object reference not set to an instance of an object
LOOKATMEScript+<LookAtMe>c__Iterator2.MoveNext ()
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress)
shadow plinth
#

the output 1 is from line 114 am i right

shell grove
#

yes

shadow plinth
#

are there any other coroutines you think are running in parallel to this one?

shell grove
#

Line 90-105 basically runs constantly

#

ModuleChecker

shadow plinth
#

try storing a reference to this between lines 108 and 109
then call OnInteractEnded() on the reference on line 115

shell grove
#

You can edit in codeShare

#

If you want to

shadow plinth
#

forgive my boomerness

shell grove
#

😄

shadow plinth
#

does the changes show up on ur end too?

shell grove
#

yep

shadow plinth
#

hot damn thats cool

shell grove
#

let's see if it works^^

#

nope, still throws the error in 115

#

well, now 116

shadow plinth
#

hmm

#

that selectable is garunteed to be on the component u are trying to get or nah

shell grove
#

Yes, otherwise the count woudn't be 1

#

x.GetComponent<KMSelectable>() != null in the where

shadow plinth
#

i dunno how it says that its found something but still throw a null reference

#

can u try logging selectable

shell grove
#

Let's see

#
[LOOK AT ME #1] LOOK AT ME! I'M THE MODULE NOW! IGNORE THE SIMPLETON
[LOOK AT ME #1] Moved successfully
[LOOK AT ME #1] 1
[LOOK AT ME #1] TheSimpleton(Clone) (KMSelectable)
NullReferenceException: Object reference not set to an instance of an object
LOOKATMEScript+<LookAtMe>c__Iterator2.MoveNext ()
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress)
shadow plinth
#

well its definitely there

#

means that whole finding of the object is correct

#

which then leaves OnInteractEnded()

shell grove
#

True

#

I changed it back to what it was and I'm logging module.ModuleSelectable

#

Let's see if it's the same

#

Still

[LOOK AT ME #1] LOOK AT ME! I'M THE MODULE NOW! IGNORE THE SIMPLETON
[LOOK AT ME #1] Moved successfully
[LOOK AT ME #1] TheSimpleton(Clone) (KMSelectable)
NullReferenceException: Object reference not set to an instance of an object
LOOKATMEScript+<LookAtMe>c__Iterator2.MoveNext ()
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress)
shadow plinth
#

same eh

#

cant help but notice IGNORE THE SIMPLETON in the log but its TheSimpleton in the reference

#

is that correct for you or nah

shell grove
#

yeah, I .ToUpperInvariant() the name. The module shouts xD

shadow plinth
#

is OnInteractEnded() a valid member on the component. maybe thats the null ref

shell grove
#

Hrmm.

#

Normally it's a predefined function. But perhaps some other modules don't assign it?

shadow plinth
#

hmm

shell grove
#

I mean

#

I could module.ModuleSelectable.OnInteractEnded += Action(); inject something to it

#

But what I don't know

#
        <member name="F:KMSelectable.OnSelect">
            <summary>
            Called whenever this selectable becomes the current selection
            </summary>
        </member>
        <member name="F:KMSelectable.OnDeselect">
            <summary>
            Called whenever this selectable stops being the current selectable
            </summary>
        </member>
        <member name="F:KMSelectable.OnCancel">
            <summary>
            Called when player backs out of this selectable, an example would be zooming out of a module
            </summary>
        </member>
        <member name="F:KMSelectable.OnInteract">
            <summary>
            Called when player interacts with this selectable. Done on button down
            Returns whether or not it should try to drill to children
            </summary>
        </member>
        <member name="F:KMSelectable.OnInteractEnded">
            <summary>
            Called when a player is interacting with this selectable and releases the mouse or controller button
            </summary>
        </member>
#

For reference btw.

#

Well, I could also skip the deselecting and select another thing. That should theoretically deselect the original

marsh vine
#

Does anyone here know of a viable GPU hardware occlusion query implementation?

I'm looking at GPU Instancer but that seems to only support Hierarchical-Z for instanced objects, and I'm aiming to have complex one-off geometry occluded by it without baking.

frozen imp
hallow elk
#

I have a listener system and it has completely stopped working. I am now getting Null Reference errors, which shouldn't be possible since the script that manages the listeners is static. I am not sure how to diagnose this.

hallow elk
#

Do any Unity Devs have documentation for EditorBuildSettingsScene and EditorBuildSettings.scenes? I believe this is the source of my issue but it is undocumented.

hallow elk
shadow seal
#

Goodness, you don't ask for much

hallow elk
#

As it is, GetActiveSceneList is not documented. That is my issue. And several hours of google searching and testing haven't been super helpful. But I appreciate the attempt nonetheless.

shadow seal
#

Well what do you need to know about that method?

hallow elk
#

It's a very, very complicated situation involving listeners, actions, and scripts that verify whether additively loaded scenes have already been loaded. I am getting null reference errors and Out of Bounds errors on a script that is grabbing from GetActiveSceneList, so I wanted to see if that method has any caveats, or if it might be pushing cached data, or anything like that.

#

It appears that the data from GetActiveSceneList is not giving the expected data, and I am unsure as to why.

plucky laurel
#
        public static EditorBuildSettingsScene[] scenes
        {
            get
            {
                EditorBuildSettingsScene[] editorBuildSettingsScenes = EditorBuildSettings.GetEditorBuildSettingsScenes();
                foreach (EditorBuildSettingsScene editorBuildSettingsScene in editorBuildSettingsScenes)
                {
                    bool flag = editorBuildSettingsScene.guid.Empty();
                    if (flag)
                    {
                        editorBuildSettingsScene.guid = new GUID(AssetDatabase.AssetPathToGUID(editorBuildSettingsScene.path));
                    }
                    else
                    {
                        editorBuildSettingsScene.path = AssetDatabase.GUIDToAssetPath(editorBuildSettingsScene.guid.ToString());
                    }
                }
                return editorBuildSettingsScenes;
            }
            set
            {
                EditorBuildSettings.SetEditorBuildSettingsScenes(value);
            }
        }
hallow elk
plucky laurel
#

find the problematic undocumented part in sources, understand how it works

hallow elk
#

The problem undocumented part is not in sources.

plucky laurel
#

😄 true

austere jewel
#

What part is problematic because it sounds like you're just not using the array properly

plucky laurel
#
        public static string[] GetActiveSceneList(EditorBuildSettingsScene[] scenes)
        {
            return (from scene in scenes
            where scene.enabled
            select scene.path).ToArray<string>();
        }
#

first time seeing pure linq in sources

austere jewel
#

I don't see that in 2022

plucky laurel
#

im on 2020

austere jewel
#

are you looking at the source or decompiled

plucky laurel
#

decomp

austere jewel
#

then you cannot trust what it's showing you is actually what the code looks like

#

just that it is functionally the same

plucky laurel
#

i dont think the compiler would unroll some other code into

where scene.enabled
            select scene.path
#

or would it

#

need to know

austere jewel
#

well, the source exists for what you're looking at, so take a gander 😛

plucky laurel
#

gh source ref shows your version

        public static string[] GetActiveSceneList(EditorBuildSettingsScene[] scenes)
        {
            return scenes.Where(scene => scene.enabled).Select(scene => scene.path).ToArray();
        }
#

for 2020

#

hm i wonder if im looking at different version of UnityEngine

hallow elk
# austere jewel What part is problematic because it sounds like you're just not using the array ...

I wish it was that simple, but it's not. There are, for example, 8 scenes currently in my build list. I am doing checks with this script that are checking if (for example) the scene at index number 5 is loaded. And it throws an out of bounds. When I breakpoint it, I discover that the script, which is getting this data during OnEnable, is getting an empty array when it looks for this data, which might suggest that it's pulling cached data from EditorBuildSettingsScene[] somewhere along the way.

austere jewel
#

Rider's decompiler shows a delicious 🤣

plucky laurel
#

yeah THAT looks like what compiler does

austere jewel
hallow elk
#

There's a bit involved in it here...I'll just keep at it on my end. If GetActiveSceneList doesn't have any additional notes on it outside of being an array, then I can only assume an issue with the UnityAction involved. I'll circle back if needed. Thank you!

plucky laurel
#

unity action?

#

ah just UnityEvent

#

but the api you try to use is editor only

hallow elk
#

Yes, I know. The whole system works differently in build.

plucky laurel
#

When I breakpoint it, I discover that the script, which is getting this data during OnEnable
you tried awaiting a frame?

#

i know it works like that on runtime, not sure about editor

#

you can skip editor frame with EditorApplication.delayCall

#

theres also editor coroutines package

austere jewel
#

without seeing or debugging the code I can't even say that's required. Getting scenes out of build settings has always worked for me on InitialiseOnLoad, the first point in time when you might think that they could be missing if Unity's API sucked

plucky laurel
#

yeah if you change build settings without recompile tho

hallow elk
graceful sparrow
#

Has anyone ever tried a gravitational pull in game where gravitationalForce * ((object * mass)/distanceBetween) = forceToApply

dire peak
#

How do I go from Object -> AddressablePath?

#

This really should be possible

graceful sparrow
#

as in get the objects addressablespath in script?

magic vigil
#

What context do you wanna use this in? N-body physics? Attract small objects to the nearest planet like in KSP? Something more like Mario Galaxy?

graceful sparrow
unique ermine
#

Im not sure where to ask this question
but perhaps you guys can help me out.
How would you handle multiple mods for your game?
Lets say people can adjust values of mobs in my game and upload those changes for others to download.

What would happen if a user downloads 2 mods which changes the same mobs but with different values?
What value is getting choosen? How do other games handle this? Any help in that regard?

#

Should I perhaps check for duplications and warn the user when trying to start the game?
So only 1 mod per type is allowed?

kind bison
sturdy bay
#

Is anyone aware of any tools for modifying global-metadata.dat or would I have to write my own?
For context, I'm modding a game compiled with il2cpp and would like to add things to it without having to hijack MetadataCache::Initialize and transforming on a case-by-case basis using code injection

regal olive
# sturdy bay Is anyone aware of any tools for modifying global-metadata.dat or would I have t...

That’s a build artifact, right? Do you know the structure of the data (is it xml? Is it json? Is it unstructured text?).

I’m not sure about a pre-existing tool, but it sounds like the desired “observable side effect” you are looking for is simply to add or remove stuff to a file. If I were in your gamer shoes, I would just write a procedure that attaches to post build step: https://docs.unity3d.com/ScriptReference/Callbacks.PostProcessBuildAttribute.html

regal olive
sturdy bay
#

yeah I only have the compiled files

#

the main problem is the lack of documentation on this file, but also odd things that seem to be happening like this section of nulls where should be strings:

regal olive
#

That is pretty cool. This is above my head; I’ve never dived in to this type of stuff. Just read about it, based on some GO and unity development.

Tell me more about the lifecycle of how you go from unmodded client to modded client? Is it basically what you led with— that you hijack MetadataCache::Initialize to add whatever stuff you need for your mod?

sturdy bay
#

I'm modding nintendo switch games, where we can apply ips patches to modify small instructions, and we can add another entire binary that acts effectively like a dll

#

so in theory I could just put a jump at MetadataCache::Initialize to a custom initializer to patch classes at runtime

#

but it'd be cleaner to patch the static files instead

lone elk
#

Greetings gentlemen, anyone here familiar with Chronos (https://assetstore.unity.com/packages/tools/particles-effects/chronos-31225)? Perhaps someone could help me figure out a solution to a problem with migrating?

Basically, I use homemade state machine for my units to move. So interaction with RigidBody2D happens within the infinite coroutine loop, like so:

void Movement() => _rb.AddForce(((Vector2)transform.right) * _curSpeed - _rb.velocity);

private IEnumerator MoveTowardsTargetState()
    {
        while (!TargetInRange)
        {
            CheckTarget();
            Movement();
            yield return null;
        ...

This, however, is unaffected by chronos, even considering that I use chronos implementation of AddForce (_rb = _time.rigidbody2D.component;).
How can I make infinite while loops run along with chronos time measurements?
Thanks!

kindred tusk
#

(based on a quick skim of the API)

lone elk
lone elk
drifting galleon
#

hey, kinda niche question here but: does anyone know how large a new object() is in c#? in bytes?
i am curious if it's better to use a bool, byte, or a new object() as a flag memory wise. but is new object() even smaller than a byte?

sage radish
drifting galleon
#

how confident are you in that assumption? cause object o = new byte() works.....so byte derives from object

sage radish
#

This is called boxing, and it's something you usually want to avoid.

drifting galleon
#

yeah i know. i just really wasn't all too sure in the case of empty new object() 's

sage radish
#

Ignoring the potential size difference, the major performance difference is the fact that creating a new object allocates heap memory, which eventually needs to be garbage collected.

drifting galleon
#

since we're at the topic of boxing currently. in my case i'd be assigning a byte, bool or new object() to a field of type object anyway, so what do you recon would be the best option?

sage radish
drifting galleon
sage radish
drifting galleon
#

yeah yeah, i know how to do it

#

thanks again though

#

aaaanndd......turns out my approach i tried to do still doesn't work. awww man this is killing me

drifting galleon
#

got it to work

regal olive
#

@drifting galleon What are you up to? Just curious. My mind is racing with reasons why you would need to care about memory sizes. Academic exercise? Lotta stuff getting generated? Or...?

drifting galleon
#

nah nothing of the sort really. i just always aim to write my code as optimized as possible. my use case was related to UI Elements

regal olive
#

Icic. Cool! Always nice to see memory based impacts of code discussions. 🙂

pale arch
#

hello so im trying to put movement animation on player but idk how to put animation on clicking movement script, i have tried to find tutorials but all i get is movement scripts

#
transform.position = Vector3.MoveTowards(transform.position, destination, movementSpeed * Time.deltaTime);

this is the movment im using

#

i have put an animator also on my player, but ye i dont know how i cna connect animation with clicking animation

fresh salmon
#

Make sure your question fits the channel you post in

regal olive
#

Movement animation = letting the animation move your character for you? I forget what that mode is called.

fresh salmon
#

Root Motion I think?

pale arch
fresh salmon
#

Ah yeah, channel naming in a nutshell

#

What can be easy for one is advanced for another. Result, chaos

#

Anyway, your player script should be controlling an Animator where all your animations are on, and use parameters to communicate values to the Animator

#

Probably with a Blend Tree if you want your animations to react according to input

pale arch
# fresh salmon Probably with a Blend Tree if you want your animations to react according to inp...

i made a blend tree and got animating frames into animation, but i dont know how i should get the animation work with the script, so my player is moving by clicking around but the animation is not working, i tried to follow a tutorial that are using buttons, and i remember using like ```cs
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");

    horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
    
    animation.SetFloat("Speed", Mathf.Abs(horizontalMove));
}

private void FixedUpdate()
{
    body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);   
}```
#

this worked with buttons so i tried to combine cs animation.SetFloat("Speed", Mathf.Abs(horizontalMove));
to clicking movement like and it didnt work

fresh salmon
#

By click movement, you mean the user clicks on the screen and the player auto-walks towards it?

#

If that's the case, you can operate on the Rigidbody's velocity instead. You just have to convert it to local space so it's relative to the player

#

Feed that into your blend tree and you're done

regal olive
pale arch
swift wind
#

Is there a proper way to use LayerMasks on the collision functions OnTriggerEnter2D() etc?
All I found on the internet are ways to check if it's on the right layer after Unity already called the function, but is it possible to get Unity to only call these functions (or an equivalent of them) when the collision is actually on that layer?
Otherwise there are just countless unnecessary checks/function calls for some uses
All that I came up with so far is just doing collision checks yourself with something like OverlapBox() together with a LayerMask, but I can't imagine not using Unity's collider components and manually checking would be the best practice

sly grove
#

You need to use the layer collision matrix in the physics settings

swift wind
swift wind
#

An example: I want to use a trigger area as the vision field of an enemy, and I want to set in the script which is managing the collider(s) what kind of objects the enemy is interested in seeing (Which could differ for each enemy)
And what I want is to only have the OnTriggerStay2D() function being called when an object set as interesting is inside, without having to filter it with if() inside the method myself and having mostly noise in it

sly grove
sly grove
swift wind
hallow elk
#

Hello again friends. Got a question about LoadSceneAsync when loading additively. My current code uses everything I can find to lower the thread priority of the async load, but it still makes a noticeable pause when loading—not good when building for VR. I can break scenes into even tinier parts, but I wanted to know if there's a different way to make it smoother.

My current loading script looks something like this:

public void LoadScene()
    {
        Application.backgroundLoadingPriority = ThreadPriority.Low;
        StartCoroutine(LoadAsyncScene(TargetScene));
    }

IEnumerator LoadAsyncScene(int scene)
    {
        AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive);
        asyncLoad.priority = 0;
        // Wait until the asynchronous scene fully loads
        while (!asyncLoad.isDone)
        {
            yield return null;
        }
    }
marsh vine
#

@hallow elk I think Addressables does something clever here- it can load and activate the scenes asynchronously; I'd recommend trying that out and seeing if it helps, since it also gives you a reference to the scene that was loaded as the results of the Task, making parallel loads less race-condition-prone.

hallow elk
#

Any resource you might reccomend?

marsh vine
#
            var sceneInstance = await Addressables.LoadSceneAsync("AltScene", LoadSceneMode.Additive, activateOnLoad: false).Task;
            await sceneInstance.ActivateAsync().ToUniTask();
            var scene = sceneInstance.Scene;
hallow elk
#

Ooooh.

marsh vine
#

I'm not actually sure how to properly pack addressables initially, but you can get to scenes packed with the Build Settings window this way:

#

the key is the "Addressible Name" directly, I think, but you can right-click and copy address for any item to get the matching key

#

oh and if you want to do async activation, add activateOnLoad: false after LoadSceneMode; I forgot it in my example (which has now been updated)

hallow elk
#

That is super helpful, @marsh vine , thank you!

marsh vine
#

hopefully it helps the pause you're hitting! 🙂

static marsh
hallow elk
thorny onyx
#

Hello is there a way to check if an animation played by an Animator is finished ?

static marsh
raven rock
echo meadow
#

I have made a knife script that damages an opponent when its close enough to the knife and the player presses "shoot" at the same time. Its just a raycast that damages the player if the raycast htis it. How would i make it so that the raycast is in a wider range? So it would go from a dot raycast to a line raycast if somebody understands.

marsh vine
fresh salmon
#

Hm, you wouldn't even need the character set (?:(\d+)EL)

raven rock
fresh salmon
#

Yeah, I think that you need to iterate over the groups, for each match, hang on, testing...

fresh salmon
hallow elk
lost crest
#

@fresh salmon well i know where to go for regex next time i need one. man i hate those things and love them at the same time

regal olive
# echo meadow I have made a knife script that damages an opponent when its close enough to the...

Couple options. You could throw out more ray casts at different angles and try to detect the victim that way.

Alternatively, you can use a box (or sphere or other) collider to have a wider detect radius.

If you want an inspector friendly solution, you could make a separate collider game object (no mesh) and pass a reference to it from your knife script.

Personally, I like to add a collider on the weapon itself and react to a collision, which happens during an attack animation. That versus programmatically doing it. You know your code best, so follow your heart!

languid sinew
#

I've got a question on how to load json data, I read the docs on JsonUtility and JSON Serialization but I'm still confused on how to use it.
My json data looks like this:

{
    "S0-01": {
        "name": "The Army's Greatest Force",
        "img": "https://i.imgur.com/3Rr3fdp.png",
        "kind": "Monster",
        "type": "Rock",
        "power": "1600",
        "stack": "1",
        "quote": "This ultimate soldier holds the potential of victory.",
        "info": "n/a"
    },
    "S0-02": {
        "name": "The First Power Sword",
        "img": "https://i.imgur.com/Ys6eTWu.png",
        "kind": "Power",
        "type": "Paper",
        "power": "+600",
        "stack": "n/a",
        "quote": "The first sword forged to wield magical powers. It’s made of gold because that’s fancy.",
        "info": "n/a"
    },
    "S0-03": {
        "name": "The Most Loyal Mage",
        "img": "https://i.imgur.com/lYG7lSU.png",
        "kind": "Monster",
        "type": "Paper",
        "power": "1400",
        "stack": "2",
        "quote": "This magical entity values loyalty to its master above all else.",
        "info": "This card only initiates an attack if the command comes directly from its original owner."
    }
}

My card class looks like this


[System.Serializable]
public class Card //one card
{
    private string index; // field
    public string Index   // property
    {
        get { return index; }   // get method
        set { index = value; }  // set method
    }

    private string name; // field
    public string Name   // property
    {
        get { return name; }   // get method
        set { name = value; }  // set method
    }

    private string kind; // field
    public string Kind   // property
    {
        get { return kind; }   // get method
        set { kind = value; }  // set method
    }

    private string type; // field
    public string Type   // property
    {
        get { return type; }   // get method
        set { type = value; }  // set method
    }

    private string power; // field
    public string Power   // property
    {
        get { return power; }   // get method
        set { power = value; }  // set method
    }

    private string stack; // field
    public string Stack   // property
    {
        get { return stack; }   // get method
        set { stack = value; }  // set method
    }

    private string info; // field
    public string Info   // property
    {
        get { return info; }   // get method
        set { info = value; }  // set method
    }

    private string quote; // field
    public string Quote   // property
    {
        get { return quote; }   // get method
        set { quote = value; }  // set method
    }

    private List<string> tags = new List<string>(); // field
    public List<string> Tags   // property
    {
        get { return tags; }   // get method
        set { tags = value; }  // set method
    }
}

How would I go about making a list of cards from my json file (make List<Card> have entries with all the data from my json, where the "s0-01" thing is the "Index" string)

#

The json data contains 240 entries, and is an actual file in my assets

compact ingot
languid sinew
#

Sorry to bug, but how would I go about doing that

compact ingot
languid sinew
compact ingot
#

Your private backing fields will need some annotation attributes for the serializer to find them

languid sinew
#

annotation attributes? Sorry I'm quite new to this

compact ingot
#

it’s all in the docs

languid sinew
#

Alright, I'll try and figure it out

compact ingot
#

For serialization to work source json and target type have to be compatible… if source is an array, target must be a collection type too

#

if source is an object, target can be any type with corresponding fields

languid sinew
#

can my target be a list<card>?
and If my target is a list<card> what will happen to the "private backing feild" aka the "s0-01" thing?

compact ingot
languid sinew
compact ingot
#

No

#

read the docs

languid sinew
#

this looks like it's for converting card objects to json entries if I'm not mistaken, I'd like to convert json entries to card objects

compact ingot
#

There are lots of possibilities for converting between json/c# types

#

Most attributes work both ways

#

the reference doc for the attribute has more details than the example

languid sinew
#

but my entries don't have a json Property name, as in the "s0-01" doesn't have something like "index" : "s0-01", so how can something find that?

compact ingot
#

deserialize into Dictionary<string, Card>

#

If you want s0-01 to be a field on a c# type you have to rename it via attributes

languid sinew
#

I see, so if I went to deserialize the whole thing, I would do


    List<Dictionary<string, Card>> allCards = new List<Dictionary<string, Card>>();
void Start()
{
        allcards = JsonConvert.DeserializeObject<List<Dictionary<string, Card>>>(Resources.Load<TextAsset>("cardsJSON"));
}
compact ingot
#

That ‘new’ is not needed, it gets overwritten

languid sinew
#

Oh yeah, I guess I could set it to deserialize when I define it

#

But that's how I'd do it right?

languid sinew
#

oh ok

compact ingot
#

If by define you mean declare

languid sinew
#

yeah

#

But otherwise, that would do what I want it to right?

compact ingot
#

declaration must be compile time static

compact ingot
languid sinew
#

Cool, I'll install the Newtonsoft Json Unity Package and let you know if it works

coarse compass
#

Is there a way to get a MonoScript from a given Type?

#

From what I see, you need an instance which doesn't make sense

austere jewel
#

You can search the asset database for MonoScripts and then check which types they are

austere jewel
coarse compass
#

thanks - the asset database should work

#

what method would you use for this?

#

I'm looking into the generic FindAssets method right now but 1) not sure how to filter yet and 2) it seems to return asset ids which I haven't yet figured out how to use to get the script

austere jewel
coarse compass
#

Awesome, just what I needed

#

AssetDatabase.FindAssets("t:MonoScript").Select(AssetDatabase.GUIDToAssetPath).Select(AssetDatabase.LoadAssetAtPath<MonoScript>).ToArray();

#

Beautiful

wheat spindle
#

Any idea hide grass inside of the car ?

somber grotto
#

how do i convert an array using a generic type to a class array if valid?

compact ingot
wheat spindle
#

hmm test 1 sec

#

pff alotof shader customization 🙂

stuck onyx
#

I want to apply compression to my savegame strings, they come from a database. But if i add this feature now code will receive some compresseed and some non compressed files....
I was wondering how to detect if a gameFile is compressed or not and i see different options...
a)Try-Catch decompression so if it succeds i decompress and if it fails it was not compressed. (but i wonder if ALWAYS throws exception when trying to decompress a non compressed string 🤔

b) set a flag in database saying if that gamefile is compressed or not

c) All gamefiles start by {"version": maybe i can do
if ( ! gamefile.StartsWith("{version}") decompress

#

which one you think is the best approach?

#

I tend to think the c) approach

compact ingot
stuck onyx
#

thanks 👍 ill use that

compact ingot
#

all the other options can be done additionally, i.e. in the database for filtering without checking each file

#

the try/catch thing is smelly

stuck onyx
#

yeah, i dont like the try/catch approach but found it in stackoverflow

compact ingot
#

you should only do that as a fix in a live project where there is no other way to handle under extreme time pressure. if you can control the other end of your code, don't use exceptions

stuck onyx
#

thanks for the advice @compact ingot

compact ingot
#

reason being: control flow based on exceptions is hard(er) to reason about, it has crappier performance and other people will think you are a dummy

stuck onyx
#

😄 true

regal olive
#

hey is it possible to create a script where i can directly change the nubmer of hte player's transform from the number i receive from a python file?

#

so like

#

from the pose stamped subscript it will recieve position of x,y,z that it wants the player(pink box) to go to

#

i got up to that part but then idk how to actually input that number into the transform component of the player

fresh salmon
#

You have to convert the data you're receiving to a Vector3. It greatly depends on the format of what you receive, but it's usually a string:Split call. Then once you have the Vector3, it's straightforward transform.position = theNewVector

regal olive
#

well i'm using ros to communicate between python and the unity

#

i got the ros to actually send stuff to the unity with the coordinates i want for x,y,z (it changes on the inspector tab) and i want to send that new x,y,z to the object

fresh salmon
#

Everything is done on the C# side, so no need to edit the Python code. And no, I don't have a video tutorial because your question is lacking info, especially the format of the string you're receiving

regal olive
#

can't the script just take the numbers?

#

and just directly input it in the the transform?

fresh salmon
#

No, you need to convert it

regal olive
#

damn that's tuff

#

i'm sending it as float

fresh salmon
#

If you're receiving "12, 25, 59" as the position you need to convert it to a vector3 manually

regal olive
#

ya

fresh salmon
#

That's why I need the format to direct you to the appropriate resources

regal olive
#

want me send you the communication code?

fresh salmon
#

How many times do I have to say it

#

I need the format of the string you're receiving

regal olive
#
#from std_msgs.msg import Float64 # from package.[msg/srv] import ["msg"/"srv"] 
from geometry_msgs.msg import Pose
pose_msg = Pose()

pose_msg.orientation.x = 0
pose_msg.orientation.y = 0
pose_msg.orientation.z = 10
pose_msg.orientation.w = 1

def talker():
    #pub = rospy.Publisher('data_topic', Float64, queue_size=10) # TOPIC
    pub = rospy.Publisher('chatter_', Pose, queue_size=10) # TOPIC
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    k=0.2
    
    while not rospy.is_shutdown():
        #hello_str = "hello world %s" % k
        variable = k
        #pub.publish(variable)
        pose_msg.position.x = -k/1.5
        pose_msg.position.y = k/2
        pose_msg.position.z = k/3

        

        pub.publish(pose_msg)

        #rospy.loginfo('Envio: %s', variable)
        rospy.loginfo('SEND DATA: \n%s', pose_msg)
        k=k+0.1
        rate.sleep()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:```
#

this will do?

#

i'm not understanding your question

#

never used unity before

fresh salmon
#

Ah there we go, "I'm not understanding" is what you should have said from the start

regal olive
#

ya

fresh salmon
#

So, the format is how do you encode a position in a string before you send it

#

For example (x, y, z) or x, y, z are formats

#

They're different, but can still be processed from C#

#

I don't understand Python, so it's up to you to tell me how a position vector is encoded on Python's side before being sent

regal olive
#

hmm

#

i mean those are the only 2 files that goes back and forth with the unity and the ros

#

otherwise rest of the files is deticated to unity sending back all the infos back to ros

fresh salmon
#

Then I can't help, because I don't understand that Python code

#

It's filled with libraries and custom classes I've never heard of, even on C#'s side

regal olive
#

then is there a c# script that i can follow?

#

what i'm doing is

fresh salmon
#

I mean, that thing UnitySubscriber<MessageTypes.Geometry.Pose>? Never heard of it

regal olive
#

i have a RL program that is trying to move an arm in unity to pick up something

#

i just need to somehow be able to report the coordinates to ROS so i can keep track of things

fresh salmon
#

Yeah sorry that's using things I never seen before. I thought you were just using a websocket or something to make the communication between Py and C#. Oh boy I was wrong

regal olive
#

ohwait

#

that's a good idea

#

i was thinking of using websocket as well

versed pewter
#

Tried looking into UDP sockets and JSON data?
I have succesfully implemented a Python script that takes the pitch, roll and yaw from my head, and sending that data to unity to change the camera angle

regal olive
#

is it much easier?

fresh salmon
#

My view is biased because I'm not aware of the libraries you're using, but probably yes

regal olive
regal olive
#

?

#

i don't wanna ask every single line of code i write

fresh salmon
#

You'll need a C# library to handle websockets I think. So it's actually going to be more (advanced) work on C# side. Like, a thread that runs the ws client, and a way to pass messages you receive to the main Unity thread

regal olive
#

ah but i'm working with an ML team and they use python only for now

#

i was gonna stick with isaac

#

but the team wanted to use some easier software to run and train

#

caz we only have like 3 pc that has a6000

fresh salmon
#

Multithreading and cross-thread communication isn't something you want to do if you're starting out with C#, at least if you want to do it right

versed pewter
fresh salmon
#

If you can actually avoid WS entirely, and use TCP or UDP instead, 100% go for it. It's much easier to implement

regal olive
#

so they are writing the planner in python that pretty much will send x,y,z components to unity well not even it's only sending the rotation

regal olive
fresh salmon
#

It doesn't care about the other side really

#

As long as you send and receive using the same network technology, you're good

#

Example, you want to receive UDP packets on Unity's side? Then send UDP packets on Python's side

#

The language used by the endpoints doesn't matter as long at the net tech is the same

versed pewter
#

You can implement a UDP connection in Python with 2-3 lines of code

fresh salmon
#

It's a bit more complex in C# (you still need multithreading if you don't want your game to freeze waiting for a message), but not hard to set up

somber grotto
#

how do i save a multidimensional array of a class with a constructor into a file?

somber grotto
#

uh, not exactly sure what that entails

#

i don't have a save system in place right now since i'm using a saving asset but that saving asset doesn't support the 2d class array so i need to set something to save that up specifically

patent dock
#

hey all, working my way through the catlike coding tutorial on srp, and I've gotten to the bottom of the first tutorial. I think I've found a bug in unity, but I just want to sanity check it. When two cameras are in the scene, the depth is always cleared, even if the depth is set to "don't clear"

#

oh, I might be an idiot, don't mind me.

#

I am indeed a moron

#

welp

spare mural
#

I know you can use map.SetColor() to change the color of a specific tile, but is there any way to only make certain tiles glow?

#

the best solution I can come up with is using Bloom and then creating a second tilemap which is just the added strength of the bloom effect but that'd be a pain to code, are there any other better/built-in solutions?

slate walrus
#

Hello i saw

https://www.youtube.com/watch?v=dnNCVcVS6uw

and did exactly what he did and nothing happens can someone pls explain?

btw put it on playback speed of like 0.5

Link to the project:https://github.com/PizzaDestroyerX/Unity-Mehcnaics
Link to the code: https://bitbucket.org/Vespper/grappling-hook/src/master/

In this video we'll create the PERFECT grappling hook for your game. the code is open source, so let's all make this already pretty good grappling hook to an amazing one.

Thank you everyone for 100 ...

▶ Play video
slate walrus
#

What he did exactly

#

I have a newer unity version tho

humble leaf
#

100% of the time when someone says "they followed" a tutorial, they didn't.

silver hill
#

Hey I know we have #archived-shaders but I'm having an issue with a compute shader which is honestly more code than shader in nature, and said channel seems to be more visuals oriented is it ok if I ask here?

#

Anyway, I needed to to do heavy computation on a dynamic amount of objects, and compute shaders seemed like a good suited tool. Essentially, I have a number of Compute Buffers I need to perform modifications on and then render their contents. The problem is that I can't find a way to synchronize compute dispatches and frankly not sure if I'm even supposed to try. In theory it works like Set Buffer 1 -> Compute -> Set Buffer 2 -> Compute -> ... but that means I'll need to wait until the shader finishes it's job before swapping the buffer. I found GraphicsFence class with almost zero documentation that was supposed to do something like this, but I never managed to get it working

#

Another approach I thought of was to combine all said buffers into one, but that doesn't sound too convenient as it's size will vary a lot, which means frequent allocation and release

drifting galleon
#

depending on what you need to do, bursted jobs might also be a very good approach for you. there you can do the defined behaviour easily

silver hill
#

Oh, no, it's like (at least) 40 000 elements in each buffer. It's a foliage shader.

#

Not sure if jobs could compete with gpu threads in this

drifting galleon
#

for 40 000 elements easily. you might loose 3-5% in speed but that's probably not really all that relevant

#

depending on your cpu of course

silver hill
#

I see

#

And as for using compute shader?

#

You're not ideally supposed to communicate completion to CPU right?

#

I've heard it's a performance killer

drifting galleon
#

i don't know how to do it in compute shaders unfortunately

silver hill
#

Alright then I'll try jobs and see the performance I guess 🤷‍♂️

#

Thanks

#

Didn't really want to load CPU for this as it'd make sense for the visual elements to be handled by GPU but looking for compute shader information is hell

drifting galleon
#

i feel you

crystal ridge
#

This is probably a dumb question, but i'll try anyways.

Basically, I am trying to get some VR multiplayer working, I have a script that handles player input in it's own namespace, and I am using Pun which resides in it's own namespace.

I cannot reference either namespaces whatsoever.

I need to add a check in the playerinput update func that determines if the user is the "owner" of their avatar.

I'm trying Using.PUN, Using.Realtime, all which work in any normal script, but as soon as I try to inject it into something with existing namespaces, it doesn't work.

#

How do I get around this? 😦

formal lichen
#

is the right one in a different project?

crystal ridge
#

I don't even know where to start with assembly defs.

crystal ridge
#

I can access 'Using Photon.PUN' from any script I create, but this specific script i'm trying to use it in is inside it's own namespace

#

I think that's the issue

#

Just not sure how to fix it

formal lichen
#

try removing the namespace?

crystal ridge
#

I did, it just breaks the entire plugin unfortunately

formal lichen
#

oh man, that is kinda funny but not good

#

did you update the visual studio editor package?

raw lily
#

How could I modify this drag function to make the object slighty angle in the opposite direction it's being dragged towards? I guess sway would be another way to describe this. Ideally based on cursor acceleration!

 void OnMouseDown() {
        if (!isBeingThrown) {
            if (initialPosition == Vector3.zero) initialPosition = card.transform.position;

            var position = card.transform.position;
            screenPoint = Camera.main.WorldToScreenPoint(position);
            offset = position -
                     Camera.main.ScreenToWorldPoint(
                         new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
        }
    }

    void OnMouseDrag() {
        if (!isBeingThrown) {
            // Drag the card around
            Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
            Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
            card.transform.position = curPosition;
        }
    }
lone barn
#

What do you want to happen the mouse is dragged vertically?

raw lily
#

Could be the same behavior, either toned down a bit with a multiplier, but it would angle around two axis.

lone barn
#

I'm imagining a sprite with a natural vertical orientation. Say an arrow that points up. It makes sense if you drag that sprite left/right that you'd rotate it in the opposite direction but it's not clear what should happen for a vertical drag

#

Only asking this because I'm wondering if a shear is what you're thinking of

#

but in any case for a rotation what comes to mind immediately is just just keep track of prev and current mouse pos. If the x component is greater than zero rotate left, opposite for a negative one

#

You could also accumulate rotation over multiple frames by adding the delta-x into a member var

#

(on update would restore the accumulated delta-x to zero)

raw lily
#

Tried to look up what a shear is, was kinda hard to find but I think it would be something like this?
But since it's a more or less complex 3D object I'm not sure that could apply here

versed pewter
raw lily
#

Possibly yeah, I'm kinda lost with rotations to begin with, thoses would be quaternions right?

versed pewter
#

I would use Eulers its a Vector3

lone barn
raw lily
#

Hmm, I think maybe what people use for weapon sway in-game might apply to this

#
function Update() {
        MoveOnX = Input.GetAxis("Mouse X") * Time.deltaTime * MoveAmount;

        MoveOnY = Input.GetAxis("Mouse Y") * Time.deltaTime * MoveAmount;

        NewGunPos = new Vector3(DefaultPos.x + MoveOnX, DefaultPos.y + MoveOnY, DefaultPos.z);

        GUN.transform.localPosition = Vector3.Lerp(GUN.transform.localPosition, NewGunPos, MoveSpeed * 
Time.deltaTime);
}
lone barn
#

Is this like an FPS gun?

raw lily
#

In my case I'm dragging a playing card around

#

But the above yeah!

lone barn
#

So this is a card in 3d space that the player is dragging around with the mouse?

#

One of the card faces is directly toward the camera?

raw lily
#

Yup, the card is being dragged only along the screen space plane, and does face directly towards the camera

lone barn
#

You should be able to rotate your card around it's up-vector by whatever degrees you like

#

There's also RotateAroundLocal

raw lily
#

Yeah that makes a lot of sense, I probably just need to use this with the weapon sway thing for the mouse movement * MoveAmount

#

What would be the difference with local?

lone barn
#

The point and and up vector are from the frame of reference of the object's transform

#

So for example, this.transform.RotateAroundLocal(Vector3.zero, Vector3.up, 90) would rotate the object the script is attached about it's origin, around it's up vector 90 degrees

#

It's just the local vs. global coordinate system that the parameters of the rotation are specified in

raw lily
#

Hmm, I think it's without the vector.zero maybe?

#

Ohh.. but then:

#

I think it's probably RotateAround then

#

Oh both are obsolete somehow

lone barn
#

yeah... I was looking at things quickly. I'm actually not sure where I saw RotateAroundLocal now

raw lily
#

I mean both exist, they just say they are obsolete and to use Rotation instead

lone barn
#

Ah, i saw it in intellisense

raw lily
#

jump would be vertical and left right would be horizontal

lone barn
#

Yeah, it looks like Rotate is what you want and the optional third param will let you specify the coordinate system

#

Default is local, which is probably what you want in your case

raw lily
#

yeah I've been using local values, I think

lone barn
#

Anyway, that's your API for applying a rotation. You'll just need to rotate around whichever local vector is facing your camera

raw lily
#

mhm, thanks kinda have a good idea now, lets see if I can make it work!

hallow elk
#

I seem to be full of weird questions this week, so I apologize. I load the next scene in my game with a script I call via invoking a UnityEvent, which then calls LoadSceneAsync. It looks like this:

         public void LoadNewScene(int scene)
        {
            StartCoroutine(FadeThenLoadScene(scene));
        }

        public IEnumerator FadeThenLoadScene(int scene)
        {
            if (ScreenFadeTime > 0)
            {
                yield return new WaitForSeconds(ScreenFadeTime);
            }
            Debug.Log($"Doing Single load of {scene}");
            SceneManager.LoadScene(scene);
        }
#

Here's the very very weird part. I call this script with OnClick from my main menu's New Game button. That works just fine.

#

However, after playing the intro scene, a different UnityEvent calls the same script, in the same exact way, to load the next scene.

#

Even weirder: it works just fine in Editor. It does not work in the build.

sinful fossil
#

Hi! Does anyone know how I might be able to use a .compute file in a winforms application. I have a shader I use in unity but I am making a c# winforms application that would benefit from it. And how might I dispatch it in code?

raw lily
versed pewter
#

you welcome

#

looks good

hexed bay
#

this belongs in #💻┃code-beginner but it seems that no one have a clue what is happening, when I press play the camera screen go back, I cant interact with the hierarchy or inspector, the top bar is the only thing that seems to work, I cant stop the play test and need to force crash it to stop the project and reopen again
I have 3 scripts
this one is to check if an area is empty

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(BoxCollider))]
public class SpaceCheck : MonoBehaviour
{
    public Transform checkerScale;
    public GameObject thisRoom;
    public GameObject RoomParent;


    float maxDistance = 10f;
    public bool isOccupied = false;
     RaycastHit hit;

    void Start()
    {

        isOccupied = Physics.BoxCast(transform.position, transform.localScale, transform.up * -1, out hit, transform.rotation, maxDistance);
        if (isOccupied == false)
        {
            RoomParent.SetActive(true);
        }
        if (isOccupied == true)
        {
            Destroy(thisRoom);
        }
    }
}

This is to spawn a room if that place is empty

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RoomSpawner : MonoBehaviour
{

    public List<Transform> Spawners;
    public List<GameObject> Rooms;
    int choosenSpawner = 0;
    public GameObject SpaceCheck;

    void OnEnable()
    {
        choosenSpawner = Random.Range(0, Spawners.Count);
        GameObject manager = GameObject.Find("RoomsManager");
        RoomsManager managerProperty = manager.GetComponent<RoomsManager>();

        GameObject Space = SpaceCheck;
        SpaceCheck spaceProperty = Space.GetComponent<SpaceCheck>();

        if (managerProperty.maxRoom > managerProperty.RoomCount && spaceProperty.isOccupied == false)
        {
            Instantiate(Rooms[Random.Range(0, Rooms.Count)], Spawners[choosenSpawner].position, Spawners[choosenSpawner].rotation);
            RoomsManager.instance.AddRoomCount();
        }
    }
    void Update()
    {

    }
}

and this is to add a limit the numbers of rooms that can exist

public class RoomsManager : MonoBehaviour
{
    public static RoomsManager instance;
    public int RoomCount = 0;
    public int maxRoom = 30;
    private void Awake()
    {
        instance = this;
    }
    public void AddRoomCount()
    {
        RoomCount += 1;
    }
}
#

my project stopped working when I press play

#

and one of these is the problem

#

screen when press play:

#

cant interact with anything, cant even press the x to close the project

#

only thing I can interact with is the white bar on the top to crash the program and reopen it

untold moth
#

Also, what does the element 0 in the rooms list reference? The scene Room1 object?

hexed bay
#

the room1 prefab itself, not the one in the scene

untold moth
#

But is that how the room prefab looks like? Come on, don't make me repeat the same question several times...

untold moth
#

Okay, then you have a recursion there, because when a room spawns it has it's own spawner that gets enabled and spawns another room and so on.

#

All of which happens within the first frame awake/start making the game freeze in an "infinite loop"

#

*infinite recursion

hexed bay
untold moth
#

Your cap doesn't work.

#

It doesn't even have chance to iterate

hexed bay
#

ah so the spawning happens before the number of rooms can update

untold moth
#

Here's your loop

#

When an object is instantiated, OnEnabled and Awake are called on it as part of the Instantiate

hexed bay
#

so I should switch the position of the 2 actions right?

untold moth
untold moth
#

At the very least, that wouldn't freeze the game

languid sinew
#

I've been banging my head against a wall for over an hour now, I have a custom class that I made, and a bunch of instances of that class working in my script, for some reason, when I change one instances variable, all of them change to that value, even totally separate ones that I never write to -_-

#

here's the class if it matters


[System.Serializable]
public class Filter //a list of cards
{
    private string name; // field
    public string Name   // property
    {
        get { return name; }   // get method
        set { name = value; }  // set method
    }

    private List<string> indexList = new List<string>(); // field
    public List<string> IndexList   // property
    {
        get { return indexList; }   // get method
        set { indexList = value; }  // set method
    }

    public void FilterFromAllCards(string propertyName, List<string> allSearches, List<Card> allCards)
    {
        indexList = new List<string>();
        foreach (string search in allSearches)
        {
            foreach (Card card in allCards)
            {
                if (card[propertyName].ToString().Contains(search))
                {
                    if (!(indexList.Contains(card.Index)))
                    {
                        indexList.Add(card.Index);
                    }
                }
            }
        }
    }
}
#

It's specifically the "indexList" varable, whenever I change that in one instance of the class every indexList changes to match it

untold moth
#

You're probably assigning the same list to all of your object.

languid sinew
#

setter? you mean " = new list<string>()"

untold moth
#

this:

set { indexList = value; }
languid sinew
#

oh

untold moth
#

That's far from an advanced-code issue btw. 😅

languid sinew
#

Should I just make the regular variable public then? or how should I go about setting the variable

untold moth
#

Unless it's from inside the class.

languid sinew
#

Well, what if I want to change that value in one of the instances

untold moth
#

You should work with the elements of the list - not the list itself.

#

Why would you ever need to reassign the list?

languid sinew
#

To mass wipe the list

untold moth
#

you can do that with list.Clear. It's faster and cleaner

languid sinew
#

aka set the list equal to another list

untold moth
#

lists are reference types. If you assign it to reference another list, changing elements in one, would affect the other.

languid sinew
#

So should I list.clear and then list.addrange?

untold moth
#

Yes. If you really want to do it the way you do now, you'll have to make sure that you don't share list references between your objects(unless you want to).

languid sinew
#

Right, thanks!

#

The issue is gone! thank you so much

jagged kindle
#

Hi!, I was wondering if this is something possible to do fairly easely in unity, I can't seem to figure it out.
Making the spring preserve its width while its compressing, I was thinking compute shaders or some kind of mesh manipulation
(video from blender, I did it by making a curve and skinning it, I just scale the curve and it mantains its shape)

untold moth
#

The simplest way would probably be an animation.

#

2 one frame animations: one fully expanded, another fully contracted. Then you can use a blend tree in the animator to lerp between the 2 based on some parameter.

austere jewel
#

with blend shapes that sort out reversing the crushing of the spring geometry

#

If you want to do all that cheaply you can look into a vertex shader that can handle that. The kind of thing that'll only work in this one case.

untold moth
austere jewel
jagged kindle
#

The parameter could easely be the normalized distance between the maximum and minimum points

#

This is the setup, two rigidbodies and meshes with LookAt(eachother)

jagged kindle
frail tiger
#

How would I go on about to debug this?

#

Scene plays fine in editor preview, once the game is launched I get 3-4 FPS.

#

My rendering is fine ...

untold moth
#

You're doing some bullshit with render textures, so your gpu is dying.

#

Just an assumption

frail tiger
#

Is it really 38 Gb of render textures? I thought it might be Mo

untold moth
#

4.5 GB

#

38 render textures

#

Maybe reduce their resolution or something. Can't say any more just from that info.

frail tiger
#

Literally an empty scene

#

Keep in mind I'm debugging the editor

tough tulip
#

Just empty project no changes anywhere?

untold moth
#

Well, **something **is creating these render textures.
Could be the bunch of custom tabs that you have docked there

frail tiger
#

You are right, something is for sure creating those render textures

untold moth
#

plugins are often a source of lags in the editor. Especially if you don't have a clue how they work

frail tiger
#

I think I might have overbloated the poor editor

untold moth
frail tiger
#

Tried that, 8x times +

untold moth
untold moth
frail tiger
#

For some reason, this was due to SteamVR.

#

Oh well, thanks for the support dlich. Dlich for president! Been working on this problem for 6 hours now, I deserve a good night's sleep. Have a good one!

wispy terrace
# jagged kindle The parameter could easely be the normalized distance between the maximum and mi...

In this video I show how to use Shape Keys created with Blender as Unity Blendshapes.

I export the textures blender object as fbx and import it to Unity with blendshapes. This gives me the possibility to use the shape keys I created with Blender in my Unity project.

I also add a C# Script to add a timer logic to fade in the blendshape animatio...

▶ Play video
#

You won't even have to use the animator component for this one xD

strange pagoda
#

Hey can anybody help me with this?
https://github.com/Unity-Technologies/DOTSSample/blob/5a8230597a8c4b999b278a63844c5238dacf51b6/Assets/Scripts/Game/Main/NetworkStatisticsClient.cs
I am trying to use and show the RTT in my game but its value is always zero!

GitHub

A third person, multiplayer sample project. Built with Unity and using the new Data Oriented Tech Stack (DOTS). - DOTSSample/NetworkStatisticsClient.cs at 5a8230597a8c4b999b278a63844c5238dacf51b6 ·...

humble leaf
#

@graceful sparrow Don't crosspost please

merry hill
#

is there a way to make implicit casts for "base" data classes? like bool to int for example

#

preferably where it doesnt need a method call, but could be just like int result = _boolean * _number; for example (which would be the same as int result = _boolean ? _number : 0; in this case, but i think it might be handier in bigger equations etc.

hollow garden
merry hill
#

@hollow garden an implicit cast like this must be in the enclosing type (either in the OtherType or ThisType class), how would i do this for classes i cant access, like bool and int in my example?

hollow garden
#

you'll have to do something like add an extension method

merry hill
#

alr

regal olive
#

I’m remaking Pac-Man from scratch as hackathon practice and wanted to ask for opinions on edible ghost behavior.

When Pac-Man eats the “jaw breaker” then the ghosts should turn blue and become edible. Easy peasy; I have a monobehaviour that implements an IEdible interface that I can activate/deactivate. A ghost “fleeing” coroutine is triggerable.

My question is… I’m having trouble deciding if this interaction is best modeled as a finite state machine (because roam, chase, and flee behavior is different) or as an event + event listener (jaw breaker eaten then starts a flee coroutine).

Both approaches work but I’m having trouble figuring out which way of modeling fits the situation better. Any thoughts?

wispy terrace
#

Hope it helped Leteen!

wispy terrace
#

Though, you could use an event listener to switch the state machine xD

regal olive
rugged river
#

Hello all. Has anyone tried using the Facebook SDK? When I import the asset, even in a new blank Unity2d game (Unity 2021), I get a repeating error that says: AmbiguousMatchException: Ambiguous match found. System.RuntimeType.GetMethodImplCommon (System.String name, System.Int32 genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConv, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) (at <31c0f51ac5a24a22ba784db24f4ba023>:0) System.RuntimeType.GetMethodImpl (System.String name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConv, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) (at <31c0f51ac5a24a22ba784db24f4ba023>:0) System.Type.GetMethod (System.String name, System.Reflection.BindingFlags bindingAttr) (at <31c0f51ac5a24a22ba784db24f4ba023>:0) System.Type.GetMethod (System.String name) (at <31c0f51ac5a24a22ba784db24f4ba023>:0)

silent rivet
#

Does anyone here know about using Addressables? I've been reading guides but I'm not sure if I can do what i'd like to.

I want to have a game with user generated content, and an in game editor for that content. I was hoping to be able to give each piece of user generated content an address, and bundle it's data together.

I'm not sure how exactly though to go about the workflow I was hoping for which would be:

  1. a user drags an image into the game window
  2. unity loads the image asset into memory as sprite
  3. unity bundles the image and some base data to make the image into a new type of prefab.
  4. this new prefab is given a unique address and can be used as an archetype to instantiate objects of it's type, or can be edited or copied by the user.
jagged kindle
tough tulip
# silent rivet Does anyone here know about using Addressables? I've been reading guides but I'm...

Prefabs exist only in editor window. If you're releasing your project, you need to think of prefabs as non existent.
One more point i would like to add here is that you cannot generate bundles from a runtime player. You need editor for that.
You might create a webserver which has en editor running and generate bundles there.
Or if user generated content can be exported to some other media type format like png, jpg, audio file, video, a 3d model then you can get away without having to generate bundles at runtime with addressable

silent rivet
tough tulip
round pawn
#

Hey, I'm writing a marching cubes algorithm for Jobs, but I'm not sure whether to split the process into multiple steps or do it all in one job. Should I use a IJobParallelFor to determine the cube configurations separate from an IJob that generates the verts and tris?

#

What is the primary bottleneck for marching cubes?

tough tulip
#

Why not try it and then profile it?

round pawn
#

i guess lol

silent rivet
silent rivet
tough tulip
round pawn
#

I'm having an issue with un-disposed native collections, but I call Dispose() on all of them

#

Here's the meat:

NativeArray<float> density_array = new NativeArray<float>( GenerateDensity(8), Allocator.TempJob);
        NativeArray<Vector3> vertices = new NativeList<Vector3>(8 * 8 * 8, Allocator.TempJob);
        NativeArray<int> triangles = new NativeList<int>(8 * 8 * 8 * 3, Allocator.TempJob);
        PerCubeDataJob cubeDataJob = new PerCubeDataJob
        {
            resolution = 8,
            surface = surface,
            density = density_array,
            vertices = vertices,
            triangles = triangles
        };

        JobHandle testHandler = cubeDataJob.Schedule(8 * 8 * 8, 8);
        testHandler.Complete();

        Mesh mesh = new Mesh();

        mesh.SetVertices(vertices.ToArray());
        mesh.SetTriangles(triangles.ToArray(), 0);

        filter.mesh.Clear();
        filter.mesh = mesh;

        density_array.Dispose();
        vertices.Dispose();
        triangles.Dispose();
#
struct PerCubeDataJob: IJobParallelFor
{
    [ReadOnly]public NativeArray<float> density;
    [ReadOnly]public float surface;
    [ReadOnly]public int resolution;
    public NativeArray<Vector3> vertices;
    public NativeArray<int> triangles;
    public void Execute(int index){
        int vec2int = index % (resolution * resolution);
        int x = Mathf.FloorToInt(vec2int % resolution);
        int y = (vec2int - x) / resolution;
        int z = (index - (x + y)) / (resolution * resolution);
        float[] cube = new float[8];
        for(int i = 0; i < 8; i++)
        {
            Vector3Int corner = new Vector3Int(x, y, z) + MarchingTables.CornerTable[i];
            cube[i] = density[x + (y * resolution) + (z * resolution * resolution)];
        }
        MarchCube(new Vector3(x, y, z), cube);
        float point_density = density[index];
        //Debug.DrawLine(Vector3.zero, new Vector3(x, y, z), Color.red, 10f);
        //Debug.Log("x: " + x + ", y: " + y + ", z: " + z);
    }
    void MarchCube(Vector3 position, float[] cube)
    {
        int config = GetCubeConfig(cube);
        if (config == 0 || config == 255) return;
        int edge_index = 0;
        for (int i = 0; i < 5; i++)
        {
            for (int p = 0; p < 3; p++)
            {
                int indice = MarchingTables.TriangleTable[config, edge_index];
                if (indice == -1) return;
                Vector3 vert1 = position + MarchingTables.EdgeTable[indice, 0];
                Vector3 vert2 = position + MarchingTables.EdgeTable[indice, 1];
                Vector3 vert_pos = (vert1 + vert2) / 2;
                int index = (i * 3) + p;
                vertices[index] = vert_pos;
                triangles[index] = index - 1;
                edge_index++;
            }}}
    int GetCubeConfig(float[] cube){
        int config = 0;
        for (int i = 0; i < 8; i++){ 
            if (cube[i] > surface) config |= 1 << i;
        }
        return config;
    }
}
#

Thanks in advance

round pawn
#

I enabled full stack tracing and tried to install ECS, but the editor crashed

#

Now I get the line of code that the collection was allocated from, but I disposed of them in 2 different place. I have no clue what's wrong.

languid sinew
#

I'm using this channel because 1.) I think this might be a complex issue, and 2.) the other channels are being used right now

I've got a program on itch.io running in the browser using WebGL build, it's a tool for building decks in a TCG, and one of the features needs to be a way to export the deck as a deck code, I tried using input feilds, but you can't copy input feilds to clipoboard in WebGL, then I tried a "copy to clipboard" button using GUIUtility.systemCopyBuffer but like the input feilds, it works everywhere but in your browser.

#

Any ideas on a way to get the deckcode string outside of the game from a WebGL browser? even ideas that don't use the clipboard

#

(And yes, I've searched everywhere on the web and it seems like no one has a working solution)

hushed fable
languid sinew
#

I'll try those out, thanks

hushed fable
#

TL;DR: you can do this from JS, so implement this in jslib and communicate with the Unity instance

urban warren
#

Is there a good way to get a property for a field or a field for a property other than trying to find the other based on name?

marsh vine
#

I'm looking for a way to monitor and intercept component addition to objects in the hierarchy under a particular gameobject; is there some sort of event we can intercept for this? MonoBehaviour doesn't expose any.

sly grove
#

E.g. instead of calling AddComponent you call your own helper method that calls AddComponent and triggers your event

marsh vine
#

Ouch; Okay- I'll aim for the alternative method- all APIs that user-content-scripts can call to do anything of the sort feed into a custom event handler which notifies me first 😛

dawn zinc
#

Does anyone have a good resource for laying out a fresh framework for different tasks, or a set of general rules to follow/examples?