#archived-code-advanced
1 messages · Page 158 of 1
That way you will not have to call initValues() once every frame
Does CreateCard get destroyed or public Card card; in CreateCard reasigned?
wait wdym
i made createcard a func that happens when i press a button
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?
oh n this didnt work
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
er createcard is a button that has a createcard script
its in the game scene
There is no button in this scene
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
Right, I found a bunch of errors
First off, you are using scriptable objects, the script "Card" only sets the architecture of the scriptable object
sry i barely understand that i just used scriptable card as i saw a vid some1 sent on it
When making a game you need a good way of storing data. This is where Scriptable Objects come in! In this video we’ll learn how to use them by looking at an example: Making cards for Hearthstone.
● Project on GitHub: https://github.com/Brackeys/Scriptable-Objects
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
····················...
Have you seen it all?
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
You make the script which tells what information the scriptable object contains, and then, you make a scriptable object for each of the cards
cuz in the vid he doesnt instantiate cards n they r all alr objects taht exist
err can u give an example
Ill make a video
oh lol ok thanks
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
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)
created card's first child object's first child object
created card's first grandchild, you might say.
so in this case its cardtemplates -> canvas -> cardbase -> CardDisplay component of CardBase?
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
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
Exactly
hm so the index is based on how i arranged the prefab
Bear in mind, that before you get a child, you have to get the transform of the object
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?
createdCard.transform.GetChild(0).GetChild(0).GetComponent<CardDisplay>().setCard(card);
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
Because the transform is what holds all the positioning information, and childs follow the transform of their parents
if i didnt use transform n just used getchild?
You'll get a fat error xD
oh yea i do
hm is thr someway to do this more efficiently
also ty a bunch
got stuck here for like 8h hahhaa
You could put the component on CardTemplate, and doing so, you could delete the whole "transform.getchild(0).getchild(0)" shenanigans
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
yea n about this, was this pre existing knowledge or did u search something? i tried googling a bit but didnt manage to find anything relating to my issue
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
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
The parent and child relationship? I would say yes
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?
And I would not recommend to make a fully functioning tcg if you haven't much experience
:c lol
But if you want to do it anyways, I would recomend you look into Inheritance
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
Idk mate, I learnt c# from top to bottom and then just guided my way out of problems I encountered with the Scripting API
ah im kinda bad at reading doc
I'd say Unity Learn is a good way to start
I started with unity but everyone recomended me to learn C# before doing anything considerable in Unity xD
Np
Gotta read it all even if it doesn't make sense. It will eventually. Until then you're probably in the wrong room, maybe try #💻┃code-beginner
@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#
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
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?
Peer to peer networking?
Your isp might not allow it
Right, never thought of that, i've got a (don't remember the word) changing IP
Dynamic?
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
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?
Ips are public information, don't worry about that
So maybe, make them upload and download an updated list of hosted games through dropbox or something?
But know that you cant simply connect to someones ip without them doing port forwarding, you'd have to hole punch
Nah, you'd have to write your own server to handle this list. It's a 10 minute job for an experienced node developer so I'm sure you can figure it out
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
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
I think maybe use a messagetype to map your different message types and then parse them.
Thanks!
I'd recommend looking into protocol buffers. Makes the messages smaller and generates message classes for you.
Thats the easier option anyway since it'll mean one server = one game
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
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?
is it normal that the changes are saved from runtime?
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
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
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.)
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
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
Well, isn't those tutorials outdated?
ya they're the old unet, but I wanted to use the matchmaking system
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.
Not safe if you have no clue what you are doing.
But if you are willing to spend a bunch of time learning, it is a highly valuable skill set. Just… you will have to put game development on the back burner
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.
The above two comments are a reply to you
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.
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.
Your users probably won’t want to do that. The early people, sure. Ideally, this list of hosted games is something your server code keeps track of and can provide to game clients when asked.
Oh, I hadn’t considered using protobufs for game code. We use them for dayjob at bigcorp. Honestly, not a terrible idea. I would say this is advanced advice and maybe not best for a new game server developer but… well this is #archived-code-advanced after all
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
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)
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?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Is there a reason you need to load all 12,000 images at once?
I doubt you're showing them all on screen at once
you can load them on demand
I am not showing it all on screen at once. I was more concerned about having everything already loaded so if the user wanted to search for any image, it'd already be there. Though... loading them on-demand could be another way to go to give the impression that everything is already loaded.
UnityWebRequestTexture.GetTexture is fastest without manually creating GPU ready textures in separate worker threads. It avoids data copies and jobifies the texture creation internally.
There's a lot of tricks to this too. You can have a bunch of much smaller thumbnail/low quality images which you load upfront and display temporarily as you load in the real image on demand
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
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.
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
My apologies, I just wanted to test out UWR again, so let me respond in the order of replies...
I saw it but I haven't exported ever for native mobile OS 😦
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
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...
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.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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
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.
@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
Which... Honestly, pretty often devolves into finding commands online and just running them.
y y i know @regal olive just was looking if someone had the issue before and a quick fix
That could be a great idea, actually! I've been loading up the bigger quality thumbnails alongside loading the smaller, lower-quality images as well. I could probably just load the smaller ones first and then load the bigger ones on-demand.
yah that would make it faster. smaller thumbnails load pretty quick
this is what i was working on a while back. small demo https://www.youtube.com/watch?v=fPzaBMad7ss&ab_channel=pRoFlT
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
how much data should it be?
i used Mono.Data.Sqlite.dll file for the sql database. put in assets\plugin folder
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.
there maybe better ways to do this. just what i came up with
That's actually pretty cool :o I wonder how you were able to do that on top of the many restrictions Unity imposes.
20 GB is approximately 12k 512x512 RGBA textures
and your code looks like you are storing all those textures in a datastructure
using FreeImage @hard solar
my 6k library is 182GB file size. takes seconds to load thumbnails. db is only 100k
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)
does not matter how big they are on disk
So about there.
if they are jpg their disk-size is probably 10X smaller than when decompressed into RGBA
@hard solar https://codeberg.org/matiaslavik/unity-async-textureimport check this here tell me if it help
@mighty cipher nice, i may have to try that on my asset browser
@hard solar okay you have some ideas now. good luck i have to run
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.
Thank you for your ideas. I don't think I ever responded back to you, my apologies, but your could be an idea for future use just in case.
Thanks for the link! I'll take a look at it
.
and then being able to mesure stuff accurately inside the pictures
@hard solar sure np
the UWR has a memory leak that you have to manually plug by explicitly destroying any texture you may no longer need.
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
Read #📖┃code-of-conduct this is not the place for recruiting
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;
am sorry
dint knw did u guys ban nfts from the channel or smtin?
ws just lookin for helping hands
God I hope not. NFTs are the future.
^^^ this
am nt advertising sir pls dnt get me wrong
i was tryna just show progesss and i need help frm devs
am building on unity
Well, you are, you're searching for people to work on your game
That's a job advertisment
am sorry ill delte de messag
Technically speaking, we all are searching for people to work on our games when we ask questions...
To donate their brain power.
exactly
please i need help its a distress call
Um, then ask your question...?
message deletd
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
ok thanks i understnd now
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)
bro am sending u a frend request
were can i request for project collab
On the Unity Forums
ok let me chk
Expect people to not work for free in this case
u mean #💻┃unity-talk
I'll not work for free any day.
I’ll work for free if it’s an interesting topic. I love helping people out on discord
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?
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/
pls go away
how about user identification with a fricking fido key
wtf would be the point of an nft achievement. that is literally the worst i've heard
very nice that you are supporting literal scams
@drifting galleon uhhhh
I don’t believe this. I’m sure there is worse ideas out there you’ve heard.
It’s inevitable.
wat.jpeg
haha
nah
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?
with fricking nfc. just touch your phone
also you are literally comparing carrying a usb stick (wallet) with carrying a usb stick (yubikey)
@regal olive For the record, topic of NFTs has nothing to do with this server. Please discuss it somewhere else along with other scams.
+1
It's been two minutes. Please do not cross-post.
Uh… Okay, hmm. Isn’t this advanced code? Are we not able to talk about what impact Web 3.0 technologies might have on the design of our code base in game?
@frozen imp @austere jewel please let me know if the topic of Web 3.0 stuff cannot be discussed in this or other channels due to a policy. However; don’t tell me it isn’t on topic as it is literally on topic.
If it's not directly related to a Unity implementation, this isn't the right place to discuss it, and if you do, I think everyone would prefer it be threaded so it's not creating spammy divisive conversation like the above.
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.
no one took out aggression on you
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);
You need to debug, measure it, and find out the interference.
Also make sure you are using it during physics update with FixedUpdate
That is my debug and measure. That's literally all the forces at play right there.
I do have it in Update, it's just always 0.25 more, which is odd.
FixedUpdate not Update
If you are running code in frames outside of physics step that might explain it
how do I set a default prefab value
elaborate
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
show attempted solution code, if any
Resources.Load(path), for example
I tried to set the prefab value like this,
it works
no ill show u
Inb4 it's not in a Resources folder
``
oh ok where do u want to talk?
Got it, thanks.
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
yeah if you are dealing with serialization you are bound to box at some point, unity doesnt do proper generics so yeah.
Hey i have a question about openxr is there a way to call a function before Grab()?
like what to do before grabbing?
Entry point is Grab() tho. Not sure how to have a function called before that
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
okey i figure it out, thx for help anyway i called function in LastSelectExited and it worked
ooh. i may use that next time too
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 :)
Does anyone know how to bring the unity exe to the front (WITHOUT using a dll)?
i think general way is to use thje user32.dll otherwise its going to be a complicated answer
yeah the only reason I said without using a dll is because THAT looked like the complicated answer
but if it's the easiest ig I would have to use it
without the dll you'd essentially be breaking down what is does and manually performing it which would be very painful most likely
its similar to an api however you have less access to modifying it
I don't want to use third party stuff if possible
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
Win32 is installed on all windows machines by default you won't need to include it in your game
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?
Holyee crap that's one helluva' request.
I assume the project is big? I guess copying the files over to a new version won't work?
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.
the project is not huge, but big enough to break everything. A lot of stuff has been discontinued too, GuiImage and various plugins
Ehhh you can try upgrading in small increments
christ I forgot about the old as hell UI. lmao.
You charging these people a mint?
See when it breaks
thanks so much, those are great tips to start off
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?
i need to make an esteem on how much to ask lmao, it all depends on time spent, and i'll multiply it * 2.5 because that's half the time it will take
yeah if I were in your shoes, I'd ALSO go domain by domain there as well.
updating the UI to the new hotness is one element alone.
If this is an Multiplayer game, LOOORDDY you add ANOTHER chunk for that because that will suck.
Then, if you're updating Unity 4 mats to URP Shaders, THAT TOO is a separate chunk.
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
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
Don't blame you.
Also, I could swear you're working at my last job 😛
Something I was going to rally for at my last studio was dumping my CORE scripts into a "Package", and then you add the package to new projects via package manager.
You can FORK your code using pre-processor directives.
#IF_UNITY_2017 //Do all this stuff #else //Do this stuff instead
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.
pre processor directives are a great tip! thanks so much for everything @woeful kraken! I'll get you a beer if i ever see you irl
You state-side?
lol
u mean US? i'm in europe
DOH! That beer will be a long time in waiting lol
but hello, from across the pond! Keep us posted
if i have any updates on the project upgrade i'll post here. Thanks so much again
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
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.
data property has all base properties + some specific
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.
yes, I'm trying to make a fsm
Heck yea! Is this your first implementation?
I'm trying to give extensibility power to my old implementation
Gotcha. Yea, FSMs are fantastic things.
I've structured like States are MonoBehaviours and are added and removed from the StateMachine (that is monobehaviour too), States should work likes manager
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.
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;
}
Woah... Okay, fascinating implications of this code. Very cool, very interesting.
are you following a blog post or a video or something?
I'm thinking on your suggestion to separate the property data to a core part and an specific part
no, I did it myself
That is awesome!
I checked some others fsm before starting
That's usually how I approach things too 🙂
but nobody was using monobehaviour like this
Have you seen this before? http://www.gameaipro.com/GameAIPro/GameAIPro_Chapter04_Behavior_Selection_Algorithms.pdf
Check out 4.2
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.
it's the same for me, I haven't any problem on State, I'm having problems on the StateData
tell me more
because I'm giving control to the FSM about the data
I want to save and load the state state
I see. I think I would add to my state abstract interface, and defer implementation details to the subclasses in that case.
see, in the last line before return I set the data of the State with the class holder version of my ScriptableObject data
in the overridden method I'll have : state.data = new ExampleStateData(exampleStateDataScriptable);
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.
[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
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.
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
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.
ok thnx
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
hot damn thats a long where statement
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.
ah i see
In Line 64 I have already saved it and normally I could access it again as I tried in Line 113
but when it reaches line 115 it becomes null?
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)
the output 1 is from line 114 am i right
yes
are there any other coroutines you think are running in parallel to this one?
try storing a reference to this between lines 108 and 109
then call OnInteractEnded() on the reference on line 115
forgive my boomerness
😄
does the changes show up on ur end too?
yep
hot damn thats cool
hmm
that selectable is garunteed to be on the component u are trying to get or nah
Yes, otherwise the count woudn't be 1
x.GetComponent<KMSelectable>() != null in the where
i dunno how it says that its found something but still throw a null reference
can u try logging selectable
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)
well its definitely there
means that whole finding of the object is correct
which then leaves OnInteractEnded()
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)
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
yeah, I .ToUpperInvariant() the name. The module shouts xD
is OnInteractEnded() a valid member on the component. maybe thats the null ref
Hrmm.
Normally it's a predefined function. But perhaps some other modules don't assign it?
hmm
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
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.
@vague granite #📖┃code-of-conduct for collab/job posts location
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.
Do any Unity Devs have documentation for EditorBuildSettingsScene and EditorBuildSettings.scenes? I believe this is the source of my issue but it is undocumented.
Fantastic, can you show me where EditorBuildSettingsScene.GetActiveSceneList is? I don't see it on either page. 🙂
Goodness, you don't ask for much
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.
Well what do you need to know about that method?
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.
just read the sources
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);
}
}
While I am immensely appreciative of this, it does not solve my current issue.
find the problematic undocumented part in sources, understand how it works
The problem undocumented part is not in sources.
😄 true
What part is problematic because it sounds like you're just not using the array properly
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
im on 2020
are you looking at the source or decompiled
decomp
then you cannot trust what it's showing you is actually what the code looks like
just that it is functionally the same
i dont think the compiler would unroll some other code into
where scene.enabled
select scene.path
or would it
need to know
well, the source exists for what you're looking at, so take a gander 😛
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
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.
Rider's decompiler shows a delicious 🤣
yeah THAT looks like what compiler does
You should post all the relevant code if you're looking for help, because what's been posted so far is all reasonably described in the source and doesn't generate arrays
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!
Yes, I know. The whole system works differently in build.
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
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
yeah if you change build settings without recompile tho
Tried that and it does work, which gives me the impression that the listener is initializing a frame too early. Somehow.
Has anyone ever tried a gravitational pull in game where gravitationalForce * ((object * mass)/distanceBetween) = forceToApply
as in get the objects addressablespath in script?
Keep in mind gravitational effects scale with distance squared
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?
basically yeah, creating a realistic blackhole
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?
Hello! I have an error with Pathfinding https://hastepaste.com/view/T3h1 did anybody know what causes it? An enemy monster goes to a different spot for some reason. It did not occur before, with the same code
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
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
Above solution presumes you are building from source, which might not be the case since you are modding.
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:
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?
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
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!
Your code doesn't show the timing. But you'll probably need to use the deltaTime from that package.
(based on a quick skim of the API)
Basically, all the timing there is comes down to yield return null; in the coroutine/cycle, my bad for not including it
while (!TargetInRange)
{
CheckTarget();
Movement();
yield return null;
}
I tried to change it to yield return new WaitForFixedUpdate(); hoping that all things related to fixedUpdate is handled by Chronos, but it doesn't seem to achieve desirable effect
Chronos has it's own WaitForSeconds, but not their own WaitForFixedUpdate();,
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?
An object definitely takes more space than a bool and byte.
how confident are you in that assumption? cause object o = new byte() works.....so byte derives from object
All types derive from System.Object, but value types like byte are handled differently from reference types like object. When you cast byte into object, you're actually creating a new object that wraps around the byte.
This is called boxing, and it's something you usually want to avoid.
yeah i know. i just really wasn't all too sure in the case of empty new object() 's
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.
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?
If you absolutely can't change the field type, make one empty object and reuse it everywhere. Since I assume you'll just be checking for null, it doesn't matter if the same object is being shared.
exactly. it's in one of unity's classes so i can't change it
For example:
public static class ObjectFlag
{
public static readonly object True = new object();
public static readonly object False = null;
}
...
objectFlag = ObjectFlag.True;
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
got it to work
@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...?
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
Icic. Cool! Always nice to see memory based impacts of code discussions. 🙂
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
Make sure your question fits the channel you post in
Movement animation = letting the animation move your character for you? I forget what that mode is called.
Root Motion I think?
sorry i didnt know, i thought this was the best fit for the quetion cus it is advanced for me
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
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
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
There it is. Thanks!
ok ill try that, ty
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
That's the whole point of layers, to filter collisions before those methods even get called
You need to use the layer collision matrix in the physics settings
I know, but the online answers still suggested to check for the layerMask with an if after the function was called
Thanks, but what if I want to use specific layerMasks for different scripts? Can I diversify the function calls somehow or specify it with parameters or something?
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
Layermask are only a thing for physics queries like Raycast, OverlapSphere etc
This part you do entirely with the layer collision matrix
Yeah, I just figured it out, thanks a lot for the help!
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;
}
}
@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.
Ooh, that's an interesting solution to try. I haven't done much with addressables. I'll check it out.
Any resource you might reccomend?
var sceneInstance = await Addressables.LoadSceneAsync("AltScene", LoadSceneMode.Additive, activateOnLoad: false).Task;
await sceneInstance.ActivateAsync().ToUniTask();
var scene = sceneInstance.Scene;
Ooooh.
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
for more information, see #📦┃addressables
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)
That is super helpful, @marsh vine , thank you!
hopefully it helps the pause you're hitting! 🙂
Does the game freeze briefly, or is it a visual flicker?
It freezes briefly. Definitely more noticeable since it's VR
Hello is there a way to check if an animation played by an Animator is finished ?
Have you ran the profiler to see where the slowdown is coming from?
Hello, I would want my Regex to capture multiple matches, but it seems to not be working, as it gets only the first number, does someone knows how to do ? Thanks in advance : https://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyEwsSBlJlY2lwZRiAgIC6vtSYCww/index.html
(Click on .Net to show my results)
More explicit example : https://dotnetfiddle.net/EpyQBp
Test | Test your C# code online with .NET Fiddle code editor.
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.
Did addressables address it?
Tracked it down to the .+ part, which matches the last digit of the number. Removing it captures the whole number.
Final regex (?:([\d]+)EL) (optimized, removed unnecessary + quantifiers that didn't alter the matches)
Hm, you wouldn't even need the character set (?:(\d+)EL)
(Test at https://regex101.com/r/G8IHIE/1)
Thank you for your help but when I test it doesn't work (or I do something wrong) ? https://dotnetfiddle.net/HQX0Qb
As you can see it gives "3EL" as result and not :
20
3
Test | Test your C# code online with .NET Fiddle code editor.
Yeah, I think that you need to iterate over the groups, for each match, hang on, testing...
There we go
var test = Regex.Matches(text, @"(?:([\d]+) *EL)");
foreach (Match x in test) {
Console.WriteLine(x.Groups[1]);
}
Included * to account for possible spaces between the number and the "EL". For some reason the non-capturing group is still captured, so we access the second one (the inner number).
Thank you for your help 🙂
Will let you know. Dealing with some unexpected behavior first.
@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
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!
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
Use Newtonsoft JSON and avoid all the pain of json utility. There is a newtonsoft fork on GitHub that handles unity types
Sorry to bug, but how would I go about doing that
Seems simple, but my json has multiple entries, each with their own key, how do I do it with that?
Your private backing fields will need some annotation attributes for the serializer to find them
annotation attributes? Sorry I'm quite new to this
it’s all in the docs
Alright, I'll try and figure it out
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
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?
If you annotate it with this, it will receive the value https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm
Annotate my "s0-01" to be "index : s0-01"?
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
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
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?
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
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"));
}
That ‘new’ is not needed, it gets overwritten
Oh yeah, I guess I could set it to deserialize when I define it
But that's how I'd do it right?
You can’t
oh ok
If by define you mean declare
declaration must be compile time static
Yes, I think so
Cool, I'll install the Newtonsoft Json Unity Package and let you know if it works
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
You can search the asset database for MonoScripts and then check which types they are
It presumably has this API because the instance needs a reference to the MonoScript that it's created from. While a MonoScript is made from a type, there is nothing that connects the two in that direction beyond that.
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
"t:MonoScript"
and then AssetDatabase.LoadAssetAtPath<MonoScript>(AssetDatabase.GUIDToAssetPath(...
Awesome, just what I needed
AssetDatabase.FindAssets("t:MonoScript").Select(AssetDatabase.GUIDToAssetPath).Select(AssetDatabase.LoadAssetAtPath<MonoScript>).ToArray();
Beautiful
Any idea hide grass inside of the car ?
how do i convert an array using a generic type to a class array if valid?
You could make it invisible (alpha clip 1) based on camera distance and set that shader feature on/off when entering/exiting a car
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
c) is by far the best, some sort of first byte that identifies it
thanks 👍 ill use that
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
yeah, i dont like the try/catch approach but found it in stackoverflow
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
thanks for the advice @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
😄 true
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
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
hey can you link me a video tutorial?
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
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
can't the script just take the numbers?
and just directly input it in the the transform?
No, you need to convert it
If you're receiving "12, 25, 59" as the position you need to convert it to a vector3 manually
ya
That's why I need the format to direct you to the appropriate resources
How many times do I have to say it
I need the format of the string you're receiving
#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
Ah there we go, "I'm not understanding" is what you should have said from the start
ya
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
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
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
I mean, that thing UnitySubscriber<MessageTypes.Geometry.Pose>? Never heard of it
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
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
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
is it much easier?
My view is biased because I'm not aware of the libraries you're using, but probably yes
damn but i don't think i'll be going with UDP
can you link me something
?
i don't wanna ask every single line of code i write
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
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
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
Fair, but I have a simple C# script that works with Unity very well, and a really simple implementation in Python for sending the data
If you can actually avoid WS entirely, and use TCP or UDP instead, 100% go for it. It's much easier to implement
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
so it allows python to be used and sent to unity?
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
You can implement a UDP connection in Python with 2-3 lines of code
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
how do i save a multidimensional array of a class with a constructor into a file?
serialize it
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
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
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?
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 ...
100% of the time when someone says "they followed" a tutorial, they didn't.
Also this belongs in #💻┃code-beginner.
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
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
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
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
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
i don't know how to do it in compute shaders unfortunately
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
i feel you
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? 😦
assembly definitions?
is the right one in a different project?
I don't even know where to start with assembly defs.
Nah, same project
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
try removing the namespace?
I did, it just breaks the entire plugin unfortunately
oh man, that is kinda funny but not good
did you update the visual studio editor package?
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;
}
}
What do you want to happen the mouse is dragged vertically?
Could be the same behavior, either toned down a bit with a multiplier, but it would angle around two axis.
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)
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
Maybe onmousedrag you lerp to a rotation?
Possibly yeah, I'm kinda lost with rotations to begin with, thoses would be quaternions right?
I would use Eulers its a Vector3
Eh, maybe not a shear perhaps just scaling
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);
}
Is this like an FPS gun?
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?
Yup, the card is being dragged only along the screen space plane, and does face directly towards the camera
You should be able to rotate your card around it's up-vector by whatever degrees you like
There's also RotateAroundLocal
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?
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
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
yeah... I was looking at things quickly. I'm actually not sure where I saw RotateAroundLocal now
I mean both exist, they just say they are obsolete and to use Rotation instead
Ah, i saw it in intellisense
Hmm, the first weapon sway thing I posted was position so kinda useless for this, but there's that, that seems closer!
https://answers.unity.com/questions/410134/how-to-add-weapon-swayc.html
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
jump would be vertical and left right would be horizontal
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
yeah I've been using local values, I think
Anyway, that's your API for applying a rotation. You'll just need to rotate around whichever local vector is facing your camera
mhm, thanks kinda have a good idea now, lets see if I can make it work!
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.
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?
@lone barn @versed pewter thanks again! here's what an untweaked version looks like!
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
There's nothing advanced about your issue. You just don't provide enough details. I asked you to show your room prefab in the other channel.
Also, what does the element 0 in the rooms list reference? The scene Room1 object?
the room1 prefab itself, not the one in the scene
But is that how the room prefab looks like? Come on, don't make me repeat the same question several times...
yes
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
it shouldnt crash tho, since it cap at 30
ah so the spawning happens before the number of rooms can update
Here's your loop
When an object is instantiated, OnEnabled and Awake are called on it as part of the Instantiate
so I should switch the position of the 2 actions right?
Each OnEnable is of course called on the new instance of the RoomSpawner, so it's not a loop, but recursion.
Give it a try.
At the very least, that wouldn't freeze the game
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
You should probably remove the setter from IndexList. I think you're reassigning it somewhere.
You're probably assigning the same list to all of your object.
setter? you mean " = new list<string>()"
this:
set { indexList = value; }
oh
That's far from an advanced-code issue btw. 😅
Should I just make the regular variable public then? or how should I go about setting the variable
You don't set it. There shouldn't be any need to set it at all.
Unless it's from inside the class.
Well, what if I want to change that value in one of the instances
You should work with the elements of the list - not the list itself.
Why would you ever need to reassign the list?
To mass wipe the list
you can do that with list.Clear. It's faster and cleaner
aka set the list equal to another list
That's probably where your problem comes from.
lists are reference types. If you assign it to reference another list, changing elements in one, would affect the other.
So should I list.clear and then list.addrange?
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).
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)
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.
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.
Do you mean that it wouldn't look the same?🤔
It may just look squished instead of retaining its volume.
Yeah I tought about that, its just that I don't know a bunch about animations
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)
I don't care how its done tbh, it'll just be a couple of springs, nothing instanced
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 ...
You're doing some bullshit with render textures, so your gpu is dying.
Just an assumption
Is it really 38 Gb of render textures? I thought it might be Mo
4.5 GB
38 render textures
Maybe reduce their resolution or something. Can't say any more just from that info.
Just empty project no changes anywhere?
Well, **something **is creating these render textures.
Could be the bunch of custom tabs that you have docked there
plugins are often a source of lags in the editor. Especially if you don't have a clue how they work
I think I might have overbloated the poor editor
try restarting the editor.
Looks like it.
Try now after closing the tabs.
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!
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...
You won't even have to use the animator component for this one xD
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!
@graceful sparrow Don't crosspost please
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.
public static implicit operator OtherType(ThisType t) => new OtherType();
@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?
unfortunately you can't do that
you'll have to do something like add an extension method
alr
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?
Yesss
Hope it helped Leteen!
Personally, finite state machine 'cause it makes it easier to setup the visuals and because I hate working with coroutines
Though, you could use an event listener to switch the state machine xD
I appreciate the thoughts! I’m still debating internally.
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)
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:
- a user drags an image into the game window
- unity loads the image asset into memory as sprite
- unity bundles the image and some base data to make the image into a new type of prefab.
- 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.
Yeah, I'm definetly on the right track, thanks!, altough the blend shapes seem to be quite problematic to get working in blender since I have to use two different meshes to define the positions
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
yea, it's all pngs and json data mostly, but it's used to build in game objects with colliders, so it's sad to hear I can't easily bundle that for quick transfer between players.
It sounds like I probably need to make my own import and addressing system for the user provided and shared data files, and keep them in persistentDataPath
yes probably that's best for your use case.
you can serialize the hierarchy using Trees and attach components to the node
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?
Why not try it and then profile it?
i guess lol
Trees? Sorry not sure I get the context
My biggest issue with marching cubes was actually updating the loading queue lol.
See if you'll even need performance.
Trees are a good way to store hierarchy (incase you let the user create a complex hierarchy)
its a data structure type. it gets a bit complex with unity like hierarchy, so you can combine trees with linked list
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
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.
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)
@languid sinew There seems to be decent amount of implementations for this
https://github.com/greggman/unity-webgl-copy-and-paste
https://github.com/kou-yeung/WebGLInput
I'll try those out, thanks
TL;DR: you can do this from JS, so implement this in jslib and communicate with the Unity instance
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?
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.
Nope you'd have to do it yourself
E.g. instead of calling AddComponent you call your own helper method that calls AddComponent and triggers your event
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 😛
Does anyone have a good resource for laying out a fresh framework for different tasks, or a set of general rules to follow/examples?