#archived-code-general
1 messages Β· Page 455 of 1
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ty for telling me about octo trees never new what they where before you mention it.
Done but now I'm clueless on what to do because nothing even appears in my screen π¬ Also it puts the Canva (Environment) again when I'm inside the prefab scene π€
When you are editing a UI prefab, it gives you a "phantom" canvas so that you can do things like set up anchor points because a rect transform needs something to anchor to.
its not even on a canvas in the second image..
the big black rectangle is a Canvas, it's the object named "Canvas", it has a component "Canvas", that's what I was using before.
I'm totally lost π₯²
Yeah i didn't put "Tile" inside the Canvas as you said I don't need Canvas anymore
ohh you had switched to sprite renderer now ? didn't see you saying that anywhere.. ok forget previous message then
yeah
like so ?
yes if thats the correct sprite for it
Well the sprite looks small compared to it's text child
im trying to return a delegate from my function but i get The assignment target must be an assignable variable, property, or indexer
here is my code
// Some class
MessageUI.CreateNewAndWaitForUser("") += () => {};
// The MessageUI script
public delegate void OnClicked();
public OnClicked onClicked;
public static OnClicked CreateNewAndWaitForUser(string message)
{
var GM = GameManager.Get();
GameObject go = Instantiate(GM.messageUIPrefab.gameObject);
MessageUI messageScript = go.GetComponent<MessageUI>();
messageScript.SetText(message);
return messageScript.onClicked;
}
what is goin on += () =>
foo += () => {} is actually foo = foo + () => {}.
You cannot reassign an expression, like it wouldn't make sense to do Random.Range(0, 10) += 1.
I would personally rewrite that into MessageUI.CreateNewAndWaitForUser("", () => {}) (or async/await)
i guess its because im passing it by val ?
cant you also do
MessageUI.CreateNewAndWaitForUser("") += () =>
{
Debug.Log("User clicked!");
};```
+= is a compound assignment.
You cannot perform assignment on an expression like Random.Range(0, 10) = 5.
yeah ill simply do public static void CreateNewAndWaitForUser(string message, OnClicked clicked)
As a side note, you can also skip the delegate type altogether and just use Action (there are also Action<T>, Action<T0, T1>, as well as the equivalent Func<>s).
Some people do prefer an explicit delegate type though to make things clear.
how do i improve this code
i think you should check the basics first
Start by fixing the compile errors
Actually, start by configuring your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
Excluding the script template around them, both lines are nonsensical. You'll have to follow a course instead of just throwing random things in. See !learn π for example
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
What do i actually need to learn of C# before i can start making something in unity
i'd just watch all of the tutorials i see but i dont actually know what i need to learn
There's no hard requirements. The basics of classes, structs, variables, functions, delegates would be good.
I had zero C# coding up until 5 hours ago and all i know how to do is make the console say stuff and make variables and functions π
are there any tutorials i should specifically look for?
up until now i've just been watching a free C# tutorial course from codemonkey
There are links in the pinned messages in #π»βcode-beginner (where this question belonged anyway)
Oh thanks
Should i just open every single tutorial pinned there
Im just gonna open every tutorial pinned there
Are you going to do them all at the same time?
Well ill probably do them one at a time
but ill most likely do all of them tonight/today
idk what to call it cause its 4 am
Should i just do them from top to bottom
Start with one and then see where you're at
i'd recommend learning the basics of coding if you dont know yet, such as variables, functions classes
then just think of a feature you wanna make and do it
you'll learn more as you go
I know what classes are for but idk what they are, i do know what variables and functions are from prior coding experience with GML though
So for now ill just follow the unity learn one
thanks for the help
What's the recommended way to handle player settings? PlayerPrefs are not quite it: it can only save and load int, float and string. Like I want to save and load vector2 right now and then in the future story mode progress and a bunch of things, doing it with only 3 types and doing it manually is going to be tiresome and error-prone.
Any advice on getting adequate serialization?
Story mode progress etc is not "player settings". That sounds like a saved game system
Long story short is use whatever serializer you want/are comfortable with and save the progress to a file.
JSON is common, as are MeasagePack and Protobuf, as well as custom binary formats.
PlayerPrefs is for settings, like "what kind of quality setting does the user have selected". Int works fine for that as you can map it to an enum.
Yeah I mean I'm more interested in being able to do GameSettings.Save(Path, MyObject) and then MyObject = GameSettings.Load(Path, MyObject) and so it works on all platforms. I don't care what kind of a format they're saved in behind the scenes.
So I'm interested if there's any out of the box solution like that. There have to be.
Nope
Yes I just mentioned them. The thing is there's no "out of the box" for describing what "MyObject" is in your example because every game has a specific bespoke set of data that needs to be saved
The actual "serialize this and write to a file" part is the simplest part
Just call your serializer and use standard C# File IO to read and write the files
The thing is there's no "out of the box" for describing what "MyObject" is in your example because every game has a specific bespoke set of data that needs to be saved
C# has reflection, you just go over all properties maybe marked with an attribute and you serialize them. If those properties are simple, you just serialize them. If they're complex: struct or class, you again go property by property. And you do it until you're done. And you dump it as json, yaml, whatever, then save to a file. Then you load it similarly. I've written this in C++, it's not that hard to do, it just takes time and then more time to make it platform-agnostic for Unity.
No need
I don't really see what you're asking here. Yes, serializers exist
Use one
That's not the hard part of the save system
The real work is designing the data model that gets saved and there's nothing automatic about that because every game is unique in terms of what data needs to be saved
Here's an example savegame system that works like mine:
public interface ISaveData { }
public class SaveGameManager
{
private static Dictionary<long, ISaveData> _saveData;
public static void AddSaveData(long id, ISaveData data);
public static ISaveData GetSaveData(long id);
}
This just serializes the dictionary (plus a version number)
The one thing you want to do, at least for JSON, is make sure ONLY types inheriting ISaveData can be deserialized
{
"dateTime": "06/06/2025 09:24:47",
"timePlayed": 0.0,
"isTutorialFinished": true,
"hasDied": false,
"moveSpeed": 12,
"playerHP": 15,
"playerHPMaxValue": 20,
"criticalChance": 4,
"armor": 4,
"pickupRange": 5,
"healthRegen": 6,
"harvesting": 2,
"knockback": 1,
"xpAmount": 0,
"tunaCanAmount": 0,
"silverCoinsAmount": 15,
"bossCoinsAmount": 6,
"scrapMetalAmount": 15,
"weaponIndex": 0,
"drinkIndex": 1,
"drinkCharges": 5,
"drinksUnlocked": [
0,
2,
5
],
"hasChosenPreset": false,
"currentMiniBoxIndex": 0,
"currentCity": 0
}
there's no such thing as a "MyObject" but you can have a list, save the index into JSON and when game loads you search through that list to match that index
so far works well for me
i mean there can be a myobject but just not out of the box (hence needing to design it)
Yep
How do I address different platforms then? Like I feel like it's going to be a big goose chase of supporting different platforms even if I use an already existing serializer. For example, on PC it's going to be a file maybe in Appdata, but then on the web it's in local storage. Am I going to have to address those differences myself?
Unity has a thing for that
I think you're overthinking it. Just use Application.persistentDataPath
That handles it
as far as i know unity is a god when it comes to making builds for different platforms
depending on your render pipeline of course
ok but can i use sublime text 2
(when theres like 4* options its easy to be a god by comparison, not really a notable title)
Don't
why
isnt it UE5 that cant build for switch or sth?
Even compared to cross-platform UI systems it's an absolute breeze
Because you need a real IDE especially since you clearly don't know how to code and need all the help you can get
only PC and consoles
(the switch is a console)
i read the words you write
Thanks guys, I'll use that.
(ue5 can build to switch btw)
man
Gonna be honest though - in reality this one's an absolute nightmare.
hmm i see
Not because of the directory but because of cloud saves π
save systems suck the more you care about them, like many things in life π
talking about that how would saving to cloud saves on steam work?
with their API
do you just pass your JSON?
file
on steam you can use the API to trigger it manually, or just set up a folder to sync automatically with no code
All you do is write your save file to disk. Steam handles the rest
I believe you pass the files. But the nightmare part is all the edge cases
ah thats nice
Xbox Live requires you to sync WHILE THE GAME RUNS
So you need to handle all the edge cases yourself
i keep thinking about it, its already hard enough to make the game
User might press the cancel button
then integrating steam API to it
Internet may be down. There may be conflicts
so much work man
thats why you make games without saving π
if you use a password system, you don't even need to spend the money to put a battery on the cartridge!
why you roasting me, im not that beginner. (yes i mostly type programs on python or JS, that doesnt mean im that bad)
The code you showed is that bad
Honestly I love to whip out a lightweight IDE when I can't be bothered as I've coded for years before IDEs started handholding devs, but there's a lot of reasons you do want something more custom to Unity because it takes advantage of a lot of reflection bullcrap which will leave you scratching your head
I've also coded "for years before IDEs started handholding devs", which is exactly why I appreciate the computer highlighting mistakes before they happen.
I mean I guess JS devs are used to the pain so they may be better off rofl
well typescript is massive for a reason too
Also most code editors have a JS integration with intellisense available. Only a handful have a Unity integration
Yeah most modern Javascript projects have a build step anyway. Might as well add some compile time safety while you're at it.
I have a script that generates a triangle for a collider. I need it to be able to create an isoceles triangle, whith control over the lenght of the median and the BAC angle. It then rotates it around A. But the BAC angle is fifferent each time. Can someone explain why ? Here's my code : https://paste.myst.rs/ek89nlm2
a powerful website for storing and sharing text and code snippets. completely free and open source.
If you ever need your code critiqued, just ask copilot! Careful though, you might receive..a few..roast back..(Includes AI Content)
Just a heads up that we have absolutely zero interest in this!
if my computer talked to me like this i would be submitting my next merge request handwritten on lined paper
It really had to put the cherry on top at the end lol
you can really tell that they fed it all the reddit data to be trained on
ever since then, its talks in such an incredibly annoying "look at me im so quirky and wacky" way, just like redditors do when they think its funny for 20 people in a row to start making the same joke over and over again
it never used to say crap like "held together with duct tape and hope...spaghetti monster"
its so embarrassing
The formula for the points is wrong. It should be
Vector2 pointB = new Vector2(Mathf.Cos(halfAngleRad), Mathf.Sin(halfAngleRad)) * ILSrange;
Vector2 pointC = new Vector2(Mathf.Cos(-halfAngleRad), Mathf.Sin(-halfAngleRad)) * ILSrange;
is this why the server gets an influx of people using this
influx of people doing what?
Using Invoke & InvokeRepeating
thanks for your help, it's working now
"microwaving pizza with a hair dryer" did microsoft/openai really test it (their professional ai coding tool), see it could write things like this and say "thats good to roll out for our customers to use"
I dont know if theres an influx of people using it
considering what happened with Fortnite i have no faith that any major company has any actual control over the ai shit they use and make available to use
A majority of the early tutorials and basic unity learn resources don't use it in my personal experience and i've always been curious where people who clearly don't read the docs yet get the habit of using it. Just curious if AI nonsense is the reason
With that, is it recommended to only use InvokeRepeating for something that should run no matter what? But use a method for everything else that only runs on certain conditions? Copilot probably mentioned the invokerepeating part because I was previosly cooling the laser by just calling the cooldownlaser method every second. I've now added an if statement in the update method that only calls the cooldownlaser method when needed. Not sure which way is more effiecient though since before the method ran every second but now the if statement is being checked once per face.
Maybe invokeRepeating is better for this case?
im pointing it out because i personally think it's a good example of ai being shit and not recomendable
there's nothing wrong with using a timer like you are doing
you asked AI to find problems and it gave you problems, doesn't have to give you real ones
I want to create a road system similar to the one in Manor Lords, always wanted to make a city builder without grids. I understand that bezier curves or similar alternatives are the method to achieve what they did, where the user is able to simply press along a path and the road(s) curve and align accordingly.
I would however appreciate a tutorial on this, and all I can find are tutorials of people doing similar things in the editor, not in-game.
You guys have any ideas?
Invoke and InvokeRepeating use magic strings. they aren't really recommended for anything
they couldve been done with actions, but they didn't do that
So running an invokerepeating would probably be the most effiencient way of cooling the laser since that'll be less call to things?
to start with, have you looked at the splines package?
no im saying a timer is probably preferable than invokerepeating
no it'd actually be more calls (not the reason it's bad though)
I have yes, I don't quite understand how to apply my idea to it, although I know that or bezier is what to do
I think providing the AI with code that functions well, but is badly written, and asking it to "fix/improve the code" the AI could interpret that as
"refactor, dont alter anything, but shorten and make it more clear"
or
"the user will likely want this code to be transformed into something more advanced, improving it to make it fancier"
Ive noticed it will do both of these, and its a coin flip. the solution is asking a better prompt so it doesnt risk doing stupid stuff to it that you clearly wouldnt ever want
the solution is not using AI at all tbh
i think it comes with a sample scene that's similar to what you want? it's been a while since i looked at it
100% agree but 10x moreso if you don't know enough to know if it's giving you bullshit
I didn't know that, I'll take a look
yeah, the fact that no matter what you ask it, will still lead to it misunderstanding what you really mean and what you really want, is a gigantic issue
(though if you can tell its bullshit you likely don't need it)
also the part that it takes your entire code and gives you a new block of code - you can't specify what to change and not to change reliably
but new programmers dont have any way of understanding this, its something that you only better understand if you come from a time before AI tools existed. I cant think what its like as a new programmer and you have access to tools like this
it doesn't make changes, it remakes it based on the input
I like to use it to help explain certain parts of code. It's decent on the beginner stuff
a lot of simple stuff, things that tens of thousands of people will have done, AI is pretty good at replicating their code. But thats just how probability works with genai
its not decent because it's giving you bad advice and you dont know it
you dont know if its decent
gpt likely wont get a basic C# HelloWorld file wrong
i mean yeah because if its simple enough it will just steal peoples work outright
but "my inventory isnt working right and the UI is buggy, please fix" is never going to be right
it's all hallucinations. it might get stuff right by coincidence, but it's not immune - rather, likely - to getting stuff subtly wrong. and now you don't have anything to check with if you treat it as your primary source
Sebastian Lague had a video on a curve editor for the unity editor, I believe I can modify it to work in runtime, we'll see
hey, at least now GPT is getting worse and its overly cheerful and informal crap is seeping into code, its making it easier than ever to spot!
greatest thing is that they dont stop it from putting emojis into comments
especially because it doesn't need to give you a correct answer, it needs to give you a satisfactory answer. looking correct can satisfy that.
AI is pretty bad at that, the critiques it gave you most likely won't even work to be 100% honest here, I don't know how your code works, but that's bad advice from AI right there
Agreed! I always like looking at a few articles online to see if things match up
inb4 said articles are also from chatbots
Just look up those articles !
It doesn't actually answer questions, it gives answer-shaped text dumps
maybe I'm mean for doing it, but anytime I see code that I'm 95% confident is AI, especially if theres an emoji in a comment
I like to question that person who posted it, ask them a leading question about why/how they thought to write that specific thing
that way they either shy away from giving a straight answer, try and dance around the question
other times they admit it was ai written
after they admit it, my job is complete π
Job securityπ
I saw that one thing (think it was on john oliver?) where a pdf was formatted incorrectly and had a paragraph on the left page and a paragraph on the right page format in a way where the string reads both as one big paragraph. AI read that and made up a fake science term by combining the word from the end of one paragraph with the word at the start of the other and as a result it ended up in a bunch of science studies.
It's funny and horrifying how shoddy processing that much randomly formatted data is
huh i didn't notice this at first lmao
this is kinda funny
really captures the pinnacle of what AI is
sometimes it's right but it'll fit weird BS in all the same
- input smoothing is often an issue rather than the desired effect
- error handling isn't really needed, can just fail fast, doesn't need to be fail safe
and of course the weird InvokeRepeating recommendation
"commented out code" as a code review issue is wild π
though this is leading into the AI Discussion thread topic now
(how do you tag a thread like you'd tag a channel? like #archived-code-general )
"well im glad the errors handled now. code still breaks without the laser prefab because it's a game with lasers but it saves me looking for the line of code that threw!"
the same way, but the autocomplete menu doesn't show threads you aren't in (like channels you can't access)
gotta search for the thread and copy link
no clue what channel that thread is in though
to avoid allocating a new TransformAccessArray each frame, im making one "big" TransformAccessArray which hols some null entries, and fill it when i got entities to move.
when adding null entries im getting this warning: Adding null Transform to TransformAccessArray will result in degraded performance.
what does it mean by that ? inside my job im returning early if the transform at the given index is null
probably that it's still gonna have to process the null transform?
seems like it's more of a list than an array though - why are you adding null entries?
why add null? You can just create a TransformAccessArray with the desired capacity
and only add the ones you need
its an array, im initalizing it with nulls
Like Chris said, if you look at the API it's more of a list
it has a capacity for exactly this reason
there's no reason to add nulls
it says it's an array, internally it's an array, but it itself is a list - it controls the length, while the length of the internal array is the capacity
because doing this each frame is memory exhaustive
doing what each frame
create it once
you don't need to though?
making a new TransformAccessArray
its dynamic
thats why im making one at the maximum capacity
That's fine - you still don't need to add nulls
ok, so just, don't add nulls
then just setting the entries as the entities count varies
so ... what do i put ?
nothing
well that null
add only the transforms you need
no, not add "nothing", just don't add anything
No, it's default. Which is not necessarily null
im not adding, im allocation the arry with the capacity
var tempAloc = new Transform[bulletPoolMaxSize];
bulletEntitiesTransformAccessArray = new TransformAccessArray(tempAloc);
TransformAccessArray myArray = new(bulletPoolMaxSize, desiredJobCount);```
you don't need the tempAloc at all
ik, its for conveniance later on
this is all you need
you're losing flexibility now, though.
well thats just a refactor of what i shared ?
no it's using the other constructor
that takes an int instead of an array
its defining capacity
yes
TransformAccessArray is a list. you're nuking your options by using an array as an intermediate rather than just using the list directly
but yours is defining the capacity as well as adding a bunch of nulls
it's not the same, and doing it with the array the way you are is what's causing the issue
whats "default" here anyways
i can only think of null
default isn't really relevant here
since its a transform
no clue what digiholic was referring to
The array could internally have a struct that itself has a transform
that's why your array elements are null that's all
which is why it doesn't like putting nulls in
ah, yes, that seems to be the case
Transform[] will have nulls in it if you create it with capacity.
TransformAccessArray has some optimizations for memory and should not be created from an array with nulls in it
ill test that when i got time
for now it does impact enough to be noticeable in profiler
this is a double whammy
not only are you adding the nulls to the TAA which is bad enough, but you're allocating an extra useless managed array too
im in a rush for a dealine rn, working unoptimized code is the least urgent for me rn
it's a one line change
ig unless you were using tempAloc to pass in transforms afterwards for some reason
no, other logic used that indexing
ill have to do a few tests after "changing this only one line"
you would use TransformAccessArray's methods for managing its elements, rather than through the tempAloc
my code works in editor but not build
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShellPickup : MonoBehaviour, IUsable
{
public GameObject explosionEffect;
public GameObject puff;
public Sword sword;
[SerializeField] private AudioClip _clip;
// Start is called before the first frame update
void Start()
{
sword = GameObject.FindGameObjectWithTag("weapon").GetComponent<Sword>();
SoundManager.Instance.PlaySound(_clip);
}
// Update is called once per frame
public void Use()
{
sword = GameObject.FindGameObjectWithTag("weapon").GetComponent<Sword>();
if (sword == null)
sword = GameObject.FindGameObjectWithTag("weapon").GetComponent<Sword>();
if (sword != null)
{
sword.hasShell = true;
Destroy(gameObject);
}
else
{
Debug.LogWarning("reference is null");
}
}
}
its an ui button and it does nothing when clicked only in build
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sorry
paste code onto one of the links, hit save and send link
A tool for sharing your source code with the world!
i know its scripting order but i really dont knoiw
make a dev build check for errors, also the Player log file to see if there are any erros anywhere
what exactly is the problem, i tried using awake() too
also are you building the correct scene?
it might just be a UI issue
what i dont get is that i have a ton of items similar to this one
same ui and stuff
but nah they work
since in the build the resolution changes it could be shifting the UI and covering the clickable areas
also they work when u click 1 2 or 3 on keyboard
as shortcuts
i know its not a ui error its scripting order
but idk what exactl
other items work
this is just an assumption, have you proved that
kinda
i remember it had a really really simple fix
but i lost that
and i cant remember how i did it it was a year ago
and also i think valid proof is that many other items
use the same thing
and also that they dont need UI to be activated ive implemented keyboard shortcuts for them
idk what "other items" means in this context, havent really showed what it looks like
i can record if u wanna
but its just other stuff that use the same inventory system
like this
or what exactly isnt working
"its an ui button and it does nothing when clicked " sounds like UI to me unless you can check the PlayerLog and see errors
see the bad part
is that i cant find that
i tried but my player log is nowhere
folder empty
where did you look
appdata local low then my company then game then
nothing
idk
nothing in the folder
its just nowhere to be found
i dont know what im doing wrong
yeah it should be %USERPROFILE%\AppData\LocalLow\CompanyName\ProductName\Player.log
are you sure you set them to what you expect in Player Settings ?
also try the Development build thing
what does "put the setting" mean , also do use a complete sentence before hitting send
no
sorry, but i meant development build and script debugging
both are on but theres just no log file
and what about the box in the Dev build does it show info, on the actual game
oh i just managed to do that
it says value cannot be null
still no log but the box is there
what does, can you ss it
idk what that reffers to even, all my values are assigned, and again it just works in unity
ss?
screenshot
ah sorry
Wait a sec
Till then i can just say that the only thing visible in the box is "value cannot be null, parameter: target"
I cant get the damn box to reappear
I really dont know how this debugging stuff works
that could be anything really lol hard to know if its somethiing in your script or something else
My biggest problem is that i remember the fix was hella easy
All i know is its in that script
Or maybe one other one
But its not UI
so you tried calling the same function with a Keyboard key press and works ?
I can send other items scripts
Theyre same formula
And they work
They get component of an object
Set it to true
Button dissapears and it works out
Yes and it doesnt work
Other items do
And again to specify, other items have the same ui and logic
okay what is that function supposed to do again ?
Theres a shell that you can put on the weapon
Clicking the button gives the sword "hasShell = true"
And it's supposed to have it on
And it works fine in editor
I can send the sword code too
all it changes is a bool ? that doesnt sound like the function itself is the problem if thats all it does.
I'm thinking more in terms with reference types and any possible nulls / order access issue
Well ye pretty much but the buttons find the sword
They fail to find it
The sword is an instance though
That also might be a problem?
How are they attempting to find it
I can re send the script
It finds the object with a tag
As i said it works in editor
Wait, scrolled up and found the link
So thats why i am sure its an error with code order
What is the point of this. You search for it, and if it's null, you just do the same search again?
That's just gonna get null again
Looking for a solution tos such a dumb small you get desperate
GameObject.FindGameObjectWithTag is going to find whatever object with that tag has the lowest GUID which is essentially completely out of your control
But there is only one object with that tag
If you have more than one object with that tag, you basically can't guarantee which one you'll get
It should recognize it?
Always will be
And wouldnt that then cause problems in the editor too
But it works perfectly in the editor
Then if there's only ever one, why the Find at all? Set it in the inspector
I cant
Its a prefab
It appears sometimes so it needs to find the sword automatically
Is this a prefab, or is the Sword a prefab? Or both?
So, have whatever object spawns this pass in the reference to the thing it spawns
And the shells are prefabs you pick up, theyre supposed to be used with the sword
and have that object reference the sword in the inspector
Well kinda, this is a script for a button, and the button equips a shell when clicked
And u get the button by picking the shell off
I can record it if u wanna
It would be like 8s long
It's a prefab, so you're spawning it somewhere, right?
So, have that script set the sword variable on this script after you spawn it
Its a button it needs ro be used
I can record , im saying again cause it explains whats thw issue better
I have no idea what it being a button has to do with this
I suck with words sorry
Spawn the prefab, set the variable on it
Sword is a scene object, right?
Is the thing that spawns this ShellPickup also in the scene or is it also a prefab?
Yes but when button is clicked prefab deletes and sets variable to true
What does clicking have to do with what you do when you spawn it
Shellpickup is a button that spawns when u pixck the shell up
Clicking hasn't occurred yet
What if it spawns and i dont want the player to have the shell
When you spawn the object, set the sword variable
They choose when they equip it
Again, I don't know what this has to do with setting the reference to sword
Spawn prefab, set sword variable
Then the prefab can do whatever the hell you want
It just wont
Because Finds are essentially arbitrary
You probably have something else with that tag that you don't know about
also potentially execution order being arbitrary
and in a build it's finding that
I dont
How do you know what you don't know π€
How about logging the thing your Find returns and seeing what it says so you know for sure
I checked
This
The prefab just wont apply
I even removed the tag
And switched it with a new one
Special for this one object
And replaced name in the code
Well, either you want to find out why it's not working in a build in which case you're going to need to do some logging and find out what it's actually getting instead
Or you want it to just work in which case you should just set the variable directly when you spawn it
I need it to work in the build
Like it does in the inspector
And learn how to NOT cause that again
So, put the logs in to find out what is happening in the build
Also i think i should apologise for explaining terribly, help of everyone here means a lot
instead of just assuming you know what the problem is
I had a problem recently where logs just dont appear
In the folder
Even in dev build with debugging on
Do the find first, log the thing it finds. Then try to get the Sword component from it and see if that exists
If you get an exception the entire function just dies
and it won't log anything
Break down your chained functions into steps so if any of them are throwing an exception you'll know exactly which part is the problem
So, find the object and store it in a variable. Then on another line, get the component from that
Why are they not throwing an exception in the inspector
We've been over this
And how do i know which ones ARE throwing it in the build without logs
Finds are not consistent
In the editor, your objects are running in one order, and Find is returning one object, and those could all be different in a build
But why is this happening
Even an order sword is always there
I managed to (kinda?) fix it by using JUST find
And then the name of the weapon
Instead of relying on a tag
Still, thank all of you for your help and again sorry for not understanding some stuff im still mostly new
void Update()
{
float dist = Vector3.Distance(Player.transform.position, DoorMainS1.transform.position);
Debug.Log(dist);
KeyDisplay.SetActive(dist <= radius);
if (dist < radius)
{
if (Input.GetKey(KeyCode.E))
{
SceneManager.LoadScene("Room2Scene");
}
}
}
any idea why the
KeyDisplay.SetActive(dist <= radius);
doesnt work?
everything else works but that one line
it doesnt make the key display work as it should (its a canvas)
I would start by adding logs:
Debug.Log($"dist is {dist}, radius is {radius}, the bool is {dist <= radius}");```
already did
im telling you bro everything
works perfectly fine
but that one line
even the debug.log(dist)
I only dsee Debug.Log(dist)
I don't see any logging of radius or what the result of dist <= radius is
radius is a float 3f;
No, I'm trying to help you.
YOu are making assumptions. When debugging, the best way to do it is to remove all assumptions
The other thing you can and should log is the active state of the object before and after:
Debug.Log($"Before, KD is {KetDisplay.activeSelf}");
KeyDisplay.SetActive(dist <= radius);
Debug.Log($"After, KD is {KetDisplay.activeSelf}");```
wdym by "it works"?
Those were logs - share the output of the log
ok good
now do this
what is .activeSelf
the current active state of the object
ye i js dont know
what exactly is happening that differs from your expectation
well
sometimes it just
appeasr instantly
and doesnt turn off
(the key)
or it just doesnt appear at all
dk
watching the console logs when that happens (now that they're all in place) should be helpful
What I'm saying is - when you see the issue happening - if this code is not the one activating it - then you have some other code activating it
defo not
Can you show a video of this?
Like with game view visible as well as the console visible
also - ideally have Collapse turned off in the console
collapse?
oh
ye
i cant send a video here
nvm
its just there
and then doesnt go away
I'm trying to find a way to visually indicate what a camera can see, I want to tint everything in view of a camera with a color, so you can see what's visible to it. Something that would basically work like a light, but only illuminating what that camera can see and nothing else
maybe a cone?
I don't want an approximation of the shape of a frustum. I want the exact things that are visible by the camera to be tinted a different color
so i helped u but ur being a weirdo
By your own admission, you were guessing at something, and were posting it one or two words at time, pushing the question off screen from someone who definitely knows a way
And whatever you were suggesting before deleting it didn't make sense anyway. There already is another camera. Hundreds of them, even. I need to color what a camera can see regardless of what the active camera is
I need to basically project a color out of the camera and tint everything it touches
just the visible area, not the whole object
How is that being weird? Do you want your questions to be pushed? Its common courtesy.
How do you launch something rotating... And when it touches a ceiling or wall or floor... It attaches to it?
My enemy got a skill... It throws a turrent to the air and sticks to surfaces. Like - sticking on it with proper angle.
β’ If its ceiling. Its up-down. 180Β°
β’ If its wall. Its 90Β°. (- or + depends on left/right wall)
β’ If its floor (didnt hit anything else) then its 0Β°
How is it done? Hmm right now turret gets thrown and spins... It has a raycast to its front with hitinfo to get "normal". Hmm
Use OnCollisionEnter. The Collision object has all the data you need including surface normals
Yeah but once it gets surface normal - what is needed to make it stick with proper angle?
it "sticks" immediately when you stop updating its position and rotation.
When it touches a surface - yeah
anywhere really
I dont understand how this get normals really work o.o
I mean, using maya - i know its the surface of an element. The "face" - but converts that into rotation if it hits a side or bottom... Not sure
If you want to stick a cube on a wall so that it sits flush to the surface you set its transform.up = hit.normal (+ some offset to the position along the normal depending on the objectβs pivot), but that wouldnβt be the most plausible βstickβ pose. βstickβ implies it freezes in the rotation it has at the moment of impact. The βflushβ pose would be more like a snap created by some form of gravity or magnetism.
Sounds about right since this turret once attached it doesnt move or rotate (unless animation does or "lookat" so it rotates and aims to the target)
Based on what i've seen online there's no like perfect option but any personal recomendation for solutions to identify different "islands"/"areas" of a mesh using it's verts and indicies?
I don't think i can 100% confirm all my usecases use proper vert indexing either so i think i need to do distance checks?
Any insight as to why this needs to be qualified/clarified now? (6.2.b4)
error CS0118: 'Editor' is a namespace but is used like a type
i can fix it, so far, with UnityEditor.Editor but i am curious to know if this is a beta error, or is just how it is now
What's the exact line that was using it?
How was it used?
public class SmartTools_SettingsEditor : UnityEditor.Editor @cosmic rain
i am not a programmer, so i am not sure if that is enough information
This is correct. But it doesn't seem like this is a recent change. It's in that namespace back on 2021 LTS according to the docs.
Did you try with using UnityEditor?
interesting.. i was not seeing that error in 6.0, or 2022.3, but i upgraded this project, and had other issues, so perhaps related.
yes, that using is set
Better Folders also caused the same error
If you have the using, and inherit from Editor does it error out as well?
it will take me a minute to figure out how to do that, code-wise
using UnityEditor;
public class SmartTools_SettingsEditor : Editor
yes., and i 'fixed' it by adding adding the qualification
Oh, I see. Then it must be a namespace either in your project or in one of the namespaces you include with usings.
Which creates an ambiguity for the compiler
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Overlays;
using UnityEngine.UIElements;
#if UNITY_EDITOR
namespace SmartTools
interesting
maybe in SmartTools?
although i do not know if it is true, this is what the AI told me:
"You have a folder or class named Editor somewhere in your project that is overshadowing the UnityEditor.Editor type.
Unity 6000.2 introduced stricter parsing of ambiguous identifiers, and now it prioritizes the Editor namespace over the Editor class."
That's more or less what I've said. Aside from the latter sentence. Need to confirm that.
Yep, just included that first sentence to be complete
Logging off for the night. good hunting
@twilit scaffold if your ide is configured, you can hover over Editor when it errors to see what it's pulling from
Just sanity checking, I think it's ok? I want to check if a point is within a bounds but with consideration of rotation. Collider.ClosestPoint works well but not all my bounds use a collider.
My attempt at solving this is just making a "singleton" collider where i just sample a rotation + the bounds. This should work fine right? Assuming my Bounds is in world space
internal static bool Contains(Bounds b, Transform t, Vector3 point)
{
BoundsCollider.transform.rotation = t.transform.rotation;
BoundsCollider.center = b.center;
BoundsCollider.size = b.size;
return (BoundsCollider.ClosestPoint(point) == point);
}
Bounds cannot ever rotate
So the premise is confusing
Do you want to check if the point is inside a collider?
What do you mean by this exactly?
Bounds cannot ever rotate but I have a scenario in which I have a bounds on a rotated transform, but not a collider
Why not just use a BoxCollider on that object
reasons
And maybe that's what you're actually doing here with BoundsCollider
it is
i would love to go that route but no dice
hence my idea of using a single new one that gets kinda shared around during the check
So I mean... Yeah the code makes sense in that way but the whole setup is confusing to me
Why is it "no dice"
Stuff we can't talk about specifically on this server
call it an arbitrary requirement π
I'm actually not sure if this will work or if you need a Physics.SyncTransforms() call first
oh good call
that snippet does not do what it says it does and it would be incredibly buggy even then. Delete BoundsCollider, inverse the point into local space of t and use bounds Contains if you want to determine if a rotated bounds contains the point
and Praetor has a good point here: you are probably supplying renderer bounds (world space) to this method and that doesn't consider rotation (it's an AABB), so your setup is definitely weird. If you make the change I suggested, you will probably want to provide mesh bounds instead in local space
its not renderer bounds but is world space. I don't have mesh bounds here
will look into your suggestion though, I don't fully understand how transforming points works in regards to rotation so that might be my blind spot
bounds are axis aligned so to have some kind of rotation you need to counter rotate the point around the bounds pivot/center before checking
this can be done with a matrix or quaterion if you work in local bound space instead.
hello, i wanted to ask if there is a way to make a wait/delay inside of update
yeah, but you'd be running that delay every frame, you sure that's what you want?
what are you trying to achieve?
basically
im detecting a keypress
to load a scene when that key is pressed
but it loads it instantly
i want it to load 2 seconds late
like :
click e
2 sec passes
loads the scene
you would use a coroutine for that
yea but the funny thing is idk how to use those
call a coroutine from that button press, then in the coroutine you can easily make a delay
ik what they are but idk how to set themup
the internet is full of resources
you have a keyword to search for now
being able to find information yourself is a very crucial skill, may as well practice that now π
alrighty
ok
i think i got it
IEnumerator DelayedSceneLoad()
{
isWaiting = true;
yield return new WaitForSeconds(2f);
SceneManager.LoadScene("Room1Scene");
}
something like this?
then call the coroutine @vestal arch
how can i make my player always look at where the 3rd person camera is pointing? animation blends? (Even when moving sideways like fortnite)
Ik. Or just rotating the head bone towards a target
ill look into it thanks. same for aiming the hands or weapon at the crosshair i suppose
Lookat probably fine, but can maybe get 4 animations in blender to get the constraints you want then throw them into a blend2d/3d
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
In 3D FPS games, is shooting typically done by instantiating a bullet prefab and shooting it forward or is it done with raycasting?
hey is anybady a gtag mod menΓΌ guy i need help maiking one
I mean, raycasting is the most typical way of doing that in those game from my experience, but some games do also use bullet prefabs if, for example, an NPC enemy's shot is intended to be dodged by the player.
so, basically, raycasting is more common in FPS games, but many such games have both bullet prefabs and raycasting (depending on whether or not a specific weapon shot is meant to be avoidable by the target). I myself tend to use bullet prefabs, since I am so used to them (and also because I haven't figured out a way to script a visible line between the raycast starting point and the impact point, so I could have a visual effect...)
for some reason this is still giving me an error when i attempt to unload the current scene, unsure as to why tho
public class CustomisationDoneButton : NetworkBehaviour
{
GameObject player;
public GameObject playerPreview;
public void CustomisationDone()
{
StartCoroutine(LoadGameplayScene(playerPreview));
GameObject[] allClients = GameObject.FindGameObjectsWithTag("Client");
foreach (GameObject client in allClients)
{
if (client.GetComponent<ClientInfo>().clientID == NetworkManager.LocalClientId)
{
client.transform.GetChild(0).GetComponent<PlayersObjects>().playersColor.Value = playerPreview.transform.GetChild(0).GetComponent<PlayerColourPreview>().playerColor;
}
}
StartCoroutine(UnloadCustomisationScene());
}
public static IEnumerator LoadGameplayScene(GameObject playerPreview)
{
SceneManager.LoadScene("MainGameplayScene", LoadSceneMode.Additive);
yield return null;
}
public static IEnumerator UnloadCustomisationScene()
{
SceneManager.UnloadSceneAsync("PlayerCustomisationScene");
yield return null;
}
}
What error?
"Unloading the last loaded scene Assets/Scenes/PlayerCustomisationScene.unity(build index: 3), is not supported. Please use SceneManager.LoadScene()/EditorSceneManager.OpenScene() to switch to another scene."
Sounds like the next scene is not loaded yet, when you try to unload the customization scene.
Speaking of which, your coroutines don't do anything at all
I suggest you check the documentation on coroutines. This is not the correct way to use them.
You don't have any other scenes loaded currently so Unity won't let you have no scenes loaded.
how come the LoadGameplayScene() coroutine isnt loading in?
The scene starts loading, but you don't wait for it to complete loading.
Are you ever running it?
Oh I see
Yeah LoadScene (non async) takes one frame to complete
So you'll need to wait at least one frame for that to finish before unloading this scene
Conveniently, you're in a coroutine already so that's very easy
Just
yield return null;
( the one in your bottom coroutine doesn't do anything)
i already am doing that though?
The top one doesn't do anything either. It just delays the end of a coroutine after the scene is loaded.
The bottom one also. Basically, you're not really delaying anything.
All of the shared code executes immediately
how would i get it to wait until the scene is loaded before unloading the new scene then?
You could load it async and check with the handle to see if it's loaded or not before unloading.
Or as Praetor suggested, yield in the second coroutine for one frame. Before unloading, not after it.
yeah that worked thank you so much
https://docs.unity3d.com/ScriptReference/BuildPlayerWindow.html
Is BuildPlayerWindow even used anymore?
It's replaced by this now right?
Hello! So when instantiating gameobjects while the character is moving, they lag behind the spawn transform. for a prefab im instantiating i set a flag and check it in LateUpdate to spawn the obj, this worked for that. but i have vfx prefabs, doing the same thing, instantiating in LateUpdate, but its still behaving like its happening before the movement.
are those objects being moved to follow the "spawn transform"? if so, are they being moved in LateUpdate too?
no, a couple of the vfx are in local space but they arent being parented or anything
then describe what you mean by "they lag behind the spawn transform"? because if that object is moving and an object is spawned at its location then the locations will only be the same for the first frame that new object exists
that makes sense. like, if im moving to the right and instantiate an obj in front of my player, it spawns to the left of the transform. so if i get the transform after the movement happens, it would spawn at the correct location right? even if it moves afterwards
you should throw a Debug.Break in when you spawn the object so you can see exactly where it spawns in relation to the spawner object
Debug.Break will pause execution at the end of the frame so theoretically you should see it at the same location
Hey, im pretty sure this can be more compact but im not sure how.
if (TotalEnemies <= 12)
{
level = TotalEnemies / 6; //if 6 returns 1 if 12 returns 2
}
ill do that, i just turned the time scale wayy down to see it in slo mo and ye its spawning at the correct pos, it just looked like it wasnt because of the vfx being in the same spot
not really, there's nothing repeated there - but basing "total enemies" on the level rather than what you have here would probably give a more straightforward flow
so there wasn't a way to put an if statement (aka condition) on equals?
not one sided like that, no
c# doesn't have that kind of modifier
you could do ```cs
if (TotalEnemies <= 12) level = TotalEnemies / 6; //if 6 returns 1 if 12 returns 2
You might be thinking of the ternary operator here? but you dont have anything here if the equation is false.
Anyways needlessly making everything more compact is a waste of time. It is readable, that is good
My above message was meant to reply to you
other languages could use && to short-circuit i guess, but c# is not one of those languages
btw can i make functions take optional arguments?
thx
How in render graph can I apply full screen pass to culled objects texture then blend into original texture ? The culling pass from RG samples works, but I can't have the culled objects to have a pass on it, and can't blend it into original texture. If I try to do this with camera stack as camera overlay with culling layer set, the pass is used by the other camera
why are you crossposting this everywhere ? its a bit obnoxious also against #πβcode-of-conduct
Sorry, wasn't aware
Which channel is best for this kind of issue?
animator channel where it was.. If the code is trigger the transition then its not a code question
if its not being answered then its difficult to know the issue from that video alone so you can provide more info.
I am trying to research how games (like elden ring) get clean movement when enemies are jumping/dashing around. I don't have a specific video example but for example an enemy could jump up in an arc then lunge at you from the air.
My question is how should I replicate these kind of movements from a code perspective?
Correct me if wrong: My understanding is animations + root motions would work here, but not respect physics since this moves the transform itself. What I'm thinking is I should still use the animator but use OnAnimatorMove() and the .deltaPosition to move it in a way that would respect physics. Then i just disable other stuff like gravity in the meantime. I'm not exactly sure how that'd work in regards to aiming the lunge but does this sound like a reasonable approach?
what do you mean by "clean movement"?
most "movement" in ER is just an animation that is oriented to play towards the player.
it appears to me there is no physics simulation in ER (for combat)
I'm not too sure how to word it but I mean it just looks nice and they aren't dashing through walls at the same time.
they will probably validate if a "dash" is possible through a navmesh
but the dash itself is an animation and the arenas are designed to be quite open and non-obstructive
I understand its a different engine though so I cant really ask how they coded it. I'm more so wondering if my current idea with OnAnimatorMove would let me replicate it
if a fight is in a complex space that is usually tied in with the boss' move set
does anyone know an extension for vscode where i can see a preview of a color next to a color32
i can't really see what you are going for, just that you have to decide before the move whether it is possible to play the root motion without hitting an obstacle, physics reactions should not happen
the entire combat design of ER is built around playing out animations fully. the player's actions have no impact on the boss' animation (once started).
the boss decides on an action, moves to a start position, (optionally) aims for the player, and executes it, that is really all there is to it
unfortunately i just dont have examples because ive only seen friends play it. though i get what you mean about the arena being designed around it. i'll just try and see where i get with this because i havent used root motion much
Hello everyone, I am trying to make a ball simulation. But i have a problem with my fps. Every ball in the scene has Update method to calculate if they're outside the cirlce or not.
public class BallScript : MonoBehaviour
{
public float distance;
public BorderManagerScript manager;
private void Update()
{
distance = Vector3.Distance(transform.position, new Vector3(0, 0, -9));
print($"{distance} + {manager.borderRadius}");
if (singleBorder)
{
if (manager.borderRadius <= distance)
{
Destroy(gameObject);
}
}
}
This code cause's a lot of FPS drops, how I can optimize it?
might be worth considering that the hit-responses in ER seem to be 'overlays' on top of an animation that is playing uninterrupted, and that in idle/walk states these hit effects are stronger. Knockback etc. may be allowed on top of the underlying root motion. you often see the animation clip slightly into the environment. so they aren't too worried about making the root motion "perfect"
hm i think i understand, thanks
use the profiler to see whats causing lag. this code alone with ~30? objects shouldnt cause any lag
especially not so much to be running at 1 fps
what is the profiler
https://docs.unity3d.com/6000.1/Documentation/Manual/profiler-introduction.html it is the profiler. you see a lot of information about what is running and when
how can i use it to find out what is causing the lag
start by reading the docs... you open it and look at it.
ok i understand it, it is beacuse of physics calculation here. too much colliders and rigidbodys. thank you for help
Hi, I am trying to create a mesh for an irregularly shaped sprite mask for a 2d game from a script. Could someone explain what a mesh βuvβ is? I donβt care about the texture of the mesh because it will just be used to make something else in the scene transparent.
Am I fine leaving the UV as an empty Vector2?
https://docs.unity3d.com/2020.1/Documentation/ScriptReference/Mesh-triangles.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Mesh.html
Uvs define how a texture is mapped to the vertices. If you don't use textures, you can keep them zeroed.
Unfortunately, this is all the information it gave me :/
'Editor' is a namespace but is used like a type
Oh, it also shows this:
none of the 'Potential fixes' it offers are valid though. That is ok, for now. i am fine qualifying it as UnityEditor.Editor
well that doesn't seem right
it seems to be just a 6.2 issue, and does not seem to apply to previous versions. a little research suggested the new roslyn compiler integration is stricter
anyone had problems with unity editor scripts not working in unity6?
showing the actual error would be the best, to get help
yeh theres no error, it just doesnt run
you did something wrong and nobody can tell you what unless you supply more info
well i have a script like this WaypointsEditor : Editor which includes this [CustomEditor(typeof(Waypoints))], i expected that OnSceneGUI() would be called when i click on an object with Waypoints script on it
and i see people in forums talking about it like it works fine, so was wondering if maybe it was unity6 bug
or make one script which updates them all, every Update() has overhead.
it works fine. Is your scene view visible?
damn i worked it out, there was another editor script with the same name
lol oh wait im completely wrong, thats something else
I run into this recently as well. It does happen if you have an Editor namespace somewhere. In my case the type is directly in that namespace
You can F12 it and it would show you the definitions:
hmm so yeh i cant get OnInspectorGUI() or OnSceneGUI to call even if i make a test editor script
unfortunately it only allowed me to F12 after i qualified it. before that, it said, 'cannot navigate to the symbol under the caret'. So, i am unsure of the initial location of the non-UnityEditor Editor namespace
This screenshot here seems to point to Unity.2D.Enhancers.Editor assembly.
Ah! so that was accurate. I was having other technical issues with a screen, so had not yet verified
Sounds like it's in the new AI tools. Well, nothing you can do about it. Just qualify the Editor type explicitly.
cool deal, thank you for the insights
DOH, WAS MISSING editorForChildClasses: true
Hi, I'm trying to create a tracking UI arrow for objects in my 3d env. Right now I'm trying to stick the UI object to the 3d object, I followed some guides online but it doesn't work right. The canvas is set to overlay, and the UI object moves in the lower quarter of the screen, as if the screen was 1/4th the real screen... That's the code:
public void UpdateTrackingArrow()
{
Camera cam = Camera.main;
Vector3 screenPos = cam.WorldToScreenPoint(trackingObject.transform.position);
if (screenPos.z > 0)
{
Vector2 viewportPoint = new Vector2(screenPos.x / Screen.width, screenPos.y / Screen.height);
Vector2 refResolution = canvas.GetComponent<CanvasScaler>().referenceResolution;
Vector2 canvasPos = new Vector2(
(viewportPoint.x - 0.5f) * refResolution.x,
(viewportPoint.y - 0.5f) * refResolution.y
);
trackingArrow.GetComponent<RectTransform>().anchoredPosition = canvasPos;
trackingArrow.gameObject.SetActive(true);
}
else
{
trackingArrow.gameObject.SetActive(false);
}
}```
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ugh, sorry but it's a real pain to use the code markup with the italian keyboard. It has no backtick key and the Drevo keyboard I'm using doesn't have the numpad so I can't even use alt + 96 to write it π I have to copy and paste that from Google
It behaves as if the screen was that small and it moves the square (the placeholder for the tracking UI object) around that zone, according to the position of the object in the screen
i think referenceResolution is not the right property
it's not the actual resolution, it's just the one you design at, and then it can be scaled up or down according to the actual resolution
i think this is the value you need
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Canvas-pixelRect.html
likely a lot easier to use RectTransformUtility, something like this should do the job:
var cam = Camera.main;
var screenPos = cam!.WorldToScreenPoint(trackingObject.transform.position);
RectTransformUtility.ScreenPointToWorldPointInRectangle(trackingArrow, screenPos, null, out var worldPos);
trackingArrow.position = worldPos;
probably don't need/shouldn't have that !
I did this, same result... Also I noticed that position is negative:
that's the position of the square
(the object is NOT behind the camera)
oh right nevermind
that would only matter for the z position
the 0/0 is the center of the screen
are you sure you're using the right camera? maybe your screen point is just not right
Yeah.. it is also right, the position of the square is just "scaled down" to the lowest quarter of the screen, but it's correct
is it a problem that the camera output is a texture?
With the debugger I noticed that the cam output is the same size as the render texture. I'm pretty sure that's the problem, since the canvas has a larger size
public void UpdateTrackingArrow()
{
Camera cam = GameManager.instance.player.GetComponent<PlayerController>().playerCamera.GetComponent<Camera>();
RectTransform canvasRect = canvas.GetComponent<RectTransform>();
float widthRatio = (canvasRect.rect.width / cam.pixelWidth) * canvasRect.localScale.x;
float heightRatio = (canvasRect.rect.height / cam.pixelHeight) * canvasRect.localScale.y;
var screenPos = cam.WorldToScreenPoint(trackingObject.transform.position);
RectTransformUtility.ScreenPointToWorldPointInRectangle(trackingArrow.GetComponent<RectTransform>(), screenPos, null, out var worldPos);
worldPos.x *= widthRatio;
worldPos.y *= heightRatio;
trackingArrow.transform.position = worldPos;
}``` This fixed it, thanks for the debugging help π
Is there any way for me to make CallerArgumentExpressionAttribute work in Unity 2021? https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute?view=net-9.0
I made it work on 2022 LTS, but can't get it working on 2021
Hopefully you are only using it for debugging stuffs, and not using it for some dark magic.
I'm using it for some dark magic
You would have to patch the C# compiler in your Unity installation, not something you want to do.
Yeah no, I would strongly recommend not to use it like that.
In 2022 it works quite straightforward
Mmmmm, i guess I will have to go back to placing nameof() all around
Whatever you are doing, can likely be written in alternative and less magical ways.
less magical, but longer
Something as pretty as this
protected override void SetInputValues(BranchData branch)
{
TryGetInputData(branch, out Input);
}
would become
protected override void SetInputValues(BranchData branch)
{
TryGetInputData(branch, out Input, nameof(Input));
}
π€’
Absolutely better to write it longer.
I wouldn't even use nameof(Input).
When you read code, the fundamental assumption about things like member names is that the names don't matter. If I press F2 in my IDE and rename Input to something else, it should behave exactly the same as before. The fact that renaming a member can potentially completely change the logic of a piece of code, is very problematic.
In the scenario of this specific code which relies on purely runtime stored data, the logic wouldn't be affected by the name itself, it's only being used both when storing it, and when retrieving it. Technically, requiring the typed name/key would make it worse since there's another place where the names could differ from storing and retrieving
Without context I'm not exactly understanding what that means, but if your problem is "what if I have two pieces of code that wants to deal with the "Input" key and they might accidentally drift out of sync" then the answer is simply centralize the access.
how do i fix a redundant varible???
aye u got the collider working? πͺ
Are you asking this because your console is telling you that you have a redundant variable?
yes
don't crosspost please
!code
Hey,
I'm trying to check if the left tile isn't out of bound, but apparently I'm doing something wrong and it says about never being "null", so I'm not sure to understand how to check for out of bounds please π€
indexing an array out of bounds gives an error, not null
you have to check the indices themselves before you index into the array
so I have to check if index < 0 ?
if you're sure i itself is in bounds and j is in bounds, sure
value types by default are never null btw, ints is a value type so its always starting at default value, for int is 0
you just need to check x >= 0 && x < size.x && y >= 0 && y < size.y
here I'm checking if the 8 neighbours of my tile and not the tile itself are in bound, and for each one them calculate the amount of mines around it
Then do the same checking for those neighbour positions
I think I can't do all these checks in a single if statement like yours, I have to go through each tile 1 by 1 do the conditions 1 by 1
If you improve your neighbour checks to create a stack allocated list of the positions you can loop and do this check easier. It's something I have done in the past.
Hey, can someone help me understand where my procedural generation code is going wrong? The GenerateChunks() function infinitely loops because for some reason it is getting to a point where it doesn't think there are any valid chunks left to be placed. However that shouldn't even happen, any advice?
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.
How do I use a C# that supports Halfs? I am using unity6
you don't because unity does not use a .net version high enough that includes that type
Half's have been out for over 5 years :/
yes, but unity does not yet support .net 5
Well in that case is there a solution (ie library/package) to convert two bytes (that represent a float16) into just a normal float, or am I going to have to just write that myself
Unity Mathematics has a half type. There is also Mathf.FloatToHalf / Mathf.HalfToFloat.
is there an equivelent to BitConverter.ToHalf?
Im reading some serialized data that contains halfs
Mathf.HalfToFloat converts a ushort, a 2 byte primitive, to a float. So if you reinterpret the 2 bytes you have into a ushort, you can use Mathf.HalfToFloat.
ah I see ty
i have a json file formatted like this, is it possible to turn it into a list of strings?
i tried this but it gave me an error
jsonutility does not support collections as the root object, you would need to use a different json serializer to deserialize that
any suggestions on what one might be? if not thanks anyways
json.net is a popular one with a unity package available and should support collections at the root
or if you have control over where this json comes from you could instead just make the list a property of some object and deserialize that
will look into it, thanks again
Heyo, feel free to bump me to another chat if applicable but I've got a strange one - I'm having issues compiling new files in Unity (2022.3.23f). I've been trying to write an AudioManager script to handle SFX & Music, but I'm unable to actually compile my progress in-editor. I did a little investigating and the issue is only affecting newly created files - I've created three C# scripts all under different names and none have compiled, but I have managed to get existing scripts to compile successfully & update in-engine. Anyone have any idea what could be going on?
What do you mean by them not compiling? What kind of errors are you seeing?
so when I update any script I'd created prior to today, it functions totally fine (see first image) - showing that unity registered the changed script and recompiles. I even added a comment and confirmed in the script preview that it did update.
this simply isn't happening when I create & update a script. the script is added totally fine, it can be a component on an object as normal, but any changes I make aren't detected by unity and doesn't cause a script recompile. The second and third images are what the script actually contains in my IDE vs what unity percieves it as containing.
Unity isn't flagging any errors at all - it's just not noticing the changes.
DO you have any compile errors in youir console window?
no - as stated it isn't flagging any errors
actually hold that thought - jetbrains is flagging that it wants an update now
- Try Regnerating Project FIles from Edit -> Preferences -> External Tools settings
- Make sure your IDE plugin in Unity is up to date
- Restart everything
this fixed it, luckily. No clue why it took a second restart for it to ask for the update but whatever, all fixed now anyways
I'm reworking the movement system in my game for the last time.
First i just set the final position and rotation immediately.
I updated it to move between using MoveTowards.
The final solution i want to use is using AddForce and Torque to simulate a ships actual engines but i dont know how to use these to get to an exact position in the world
AddForce is very good for a space ship thruster. But having it arrive at certain position is not easy.
Engine power, drag, mass and gravity are parameters that define the behavior and top speed.
Why would you want to control where the ship ends up, and not let the player just steer?
because the ship has automation which the ai versions use to navigate and they have an ordered mode which works like an rts controller
if you want totally realistic behaviour i imagine there's a lot more maths involved, but in my experience with a similar type of spaceship game it's usually good enough to get the ai 90% of the way there then fake the rest π
tried faking the last alignment before, it messes up the physics
ever heard of PIDs? its how quadcopters keep their flight smooth
Proportional Integral and Derivative..
it may be something that could be added to ur system to make it perform better.. and let u focus on the bulk of the ai
Guys why my code (mainly the method GenerateOtherTiles()) does mess everything and mines don't show up and look so empty.
When I remove the line tiles[i, j].Value = minesAmount (line 142), Mines are visible again but the other numbers saying how many miens are around each tiles don't show up, so I'm kinda confused on why it doesn't work properly π€
Does anyone know please ? π€
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
reread the conditions in your GenerateOtherTiles method
I just reread it and I don't see the issue π€
Okay let's start with the first condition you have in that method. What value do the mines have?
-1
Okay so how do you know if a tile is a mine tile?
oh ok
so that's the first issue
because I have to skip it when it's == -1 and not != -1
Yes
Stupid mistake π€¦ββοΈ Thanks, I think it works properly now π
Do you think it's possible to simplify that long chain of if statements ?
and the minesAmount++ that's repeated alot π¬
i would personally store all eight directions (just the directions as a Vector2Int) in some collection and just loop through the collection, then check if currentPosition + direction is a valid tile and if it has a mine. that way you don't have eight separate if statements for pretty much the same thing
Oh that's smart, thanks π
public struct TroopInfo
{
public TroopData data;
public GameObject visual;
}
public class Tower : MonoBehaviour
{
public int CurrentLevel;
[Header("TROOP")]
[SerializeField] TroopInfo Info;
public void SpawnTroop(Vector3 spawnPosition, Troop generic)
{
Troop troopToSpawn = PoolManager.SpawnObject(generic, spawnPosition, Quaternion.identity, PoolManager.PoolType.PlayerTroop);
troopToSpawn.Initialize(Info.data, Info.visual, CurrentLevel);
CurrentSpawnTime = SpawnTime;
}
}
public class Troop : MonoBehaviour
{
[Header("STATS")]
[SerializeField] TroopData data;
[SerializeField] TroopStats stats;
[SerializeField] GameObject visualsHolder;
public TroopData Data => data;
public TroopStats Stats => stats;
public GameObject Visuals => visualsHolder;
public float currentTime;
private void SetData(TroopData newData)
{
data = newData;
stats = data.ReturnStats();
}
private void SetStats(int TowerLevel)
{
stats.MoveSpeed = stats.MoveSpeed * TowerLevel;
stats.Damage = stats.Damage * TowerLevel;
stats.Health = stats.Health * TowerLevel;
}
private void SetVisuals(GameObject troopVisual)
{
visualsHolder = troopVisual.gameObject;
visualsHolder.transform.localRotation = Quaternion.identity;
}
public void Initialize(TroopData data, GameObject troopVisual, int TowerLevel)
{
currentTime = 0;
SetData(data);
SetStats(TowerLevel);
SetVisuals(troopVisual);
}
}
Hello, I'm trying to set-up a pooling system for a tower-defense game. Thing is, player can spawn towers which spawn troops. In my pooling system, i'm setting up a "generic" troop prefab which is supposed to override the info of the curren troop it holds, allowing every tower to use it.
I'm having issues with the visual aspect of it. Is there any way to replace the empty GO with the prefab one?
Maybe there's another approach that would work better than what I'm trying to do.
If you want to use a single prefab solution you'll be swapping out all the rendering parts so stuff like the mesh renderer and mesh filter
Hello yall, im having an issue trying to create this super auto pets simulator where the characters wont move forward in the positions, can anyone help?
https://paste.mod.gg/zjosrmvscqpz/0
A tool for sharing your source code with the world!
movement lines at 44 and 62 but dont work for some reason
debug the values you're trying to assign, make sure they're what you expect
it possibly may be the animation overriding the position change?
the character that was beat moves away through the animation, then the next character should move with the bugged code to the next position
so the animation shouldnt be affecting the next character
if the animator has "root motion" enabled i believe that kinda controls the position directly? i'm not too familiar with that aspect of animations tbh
you could check for it by commenting out the animations and just doing .gameObject.SetActive(false) or similar
and also disabling the animator
realized i probably shouldnt have the character objects as children of the spawn point images, but also realized that i cant actually move them around
tried pulling all the axis arrows and they dont budge
any suggestions?
or maybe theyre stuck in the animation...
hey guys, i'm currently new with unity. Im having an issue with my char prefab. it keep flickering the whole time. when I uncheck the animation controller the flicker are stopping.
Could anyone help me solve the problem ??
if disabling the animator makes it stop, then the issue is likely in your animation(s)
also did you put the character at a higher order in layer than background ?
doesnt seem this is code related though..
but yeah could be the animation also messing with the positioning or something
thanks for the help guyss, i forgot not set the char order in layer
https://docs.unity3d.com/Packages/com.unity.testframework.graphics@7.3/api/UnityEngine.TestTools.Graphics.ImageAssert.html does anyone have examples on how to use this? also unity doesn't seem to recognize my UnityEngine.TestTools.Graphics package: The type or namespace name 'Graphics' does not exist in the namespace 'UnityEngine.TestTools' (are you missing an assembly reference?)
is the package installed ?
are you using asmdefs in your project?
i'm not sure about what asmdefs are so probably not, but i forgot to install the package π€¦ββοΈ
do you know the name, i can't seem to find it
is that the same ? i have no idea I never used
did it work ?
i believe so, the package is downloading and it says experimental
which makes sense
wait
hello and good day to everyone,
i tried to make a couple of games with raycasting interaction in them, and when the player interact with an interactable object mouse randomly gets dragged down to a random position on the screen, and it only happens when player looks at the first interactable object and after that looking at every other interactable object is normal and cause no issues
and i know the problem is with my raycasting script. here is the raycasting script
public class RaycastInteraction : MonoBehaviour
{
public static float distanceToTarget;
public static RaycastHit currenthit;
RaycastHit hit;
float _maxDistance = 5f;
void Update()
{
Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
if (Physics.Raycast(ray, out hit, _maxDistance))
{
distanceToTarget = hit.distance;
currenthit = hit;
Debug.Log(hit.collider.name);
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.green;
Gizmos.DrawRay(transform.position, transform.forward);
}
}
does anyone came across this problem before? any help is Appreciated.
i still get the error The type or namespace name 'Graphics' does not exist in the namespace 'UnityEngine.TestTools' (are you missing an assembly reference?)
this code does nothing that would cause the issue you described. in fact all it does is assign a variable (and you're also abusing static instead of getting references to objects)
Using the Graphics Test Framework
Before you can use the Graphics Test Framework in your project, you need to add the Engine and Editor TestTools.Graphics assembly definitions to the test assembly (asmdef) in your project. Alternatively, you can add com.unity.testframework.graphics to the testables section of your manifest, but that will add the Graphics Test Framework tests to your test runner window.
ah ok thanks
i just noticed the problem was with my canvas when the text "Press e to pickup" appears on the screen it causes the mouse to get dragged down, why does this happen? how can i fix this?
how could i possibly know why that is happening if you haven't shown relevant code
just wondering, i'm trying to use this to compare two textures (one is drawn in-game)
would you say i'm looking in the right direction to compare the two textures
sorry for that
here is the script:
[SerializeField] GameObject interactionText;
[SerializeField] GameObject interactionKey;
void Update()
{
if (RaycastInteraction.distanceToTarget < 1.3f && RaycastInteraction.currenthit.collider != null && RaycastInteraction.currenthit.collider.CompareTag("Key"))
{
interactionText.GetComponent<TMP_Text>().text = "TO PICKUP";
interactionText.SetActive(true);
interactionKey.SetActive(true);
if (Input.GetMouseButtonDown(0))
{
GameObject key = RaycastInteraction.currenthit.collider.gameObject;
Destroy(key);
GlobalInventory.hasKey = true;
}
}
else
{
interactionText.SetActive(false);
interactionKey.SetActive(false);
}
}
tbh dunno much about graphics, what kind of comparison we talking?
lemme send a sc real quick
now explain what you mean when you say it "causes the mouse to get dragged down" because this does not manipulate anything related to the mouse in any way. nor can you with the Input manager
can i send a recorded video of the issue in your dm?
(don't mind the quality of the drawing)
so basically the idea is that you have to draw a reference image and i wanna compare how similar it is, just very simple, as if a human glanced at it and decided how well you drew it
you can send it here
ok give me a minute
perhaps not the best way but I assume you normally use GetPixels/GetPixels32 and compare those two ?
right now i'm using get pixels and then literally just getting the difference of the histogram values (like the total rgb), i'm assuming that's what you're talking about?
yeah something like that I was thinking
I think you can do check if the color values of each pixel match exactly,
color difference, use a color difference formula, such as Euclidean distance in RGB space.
or structural similarity ?
I don't know much about this stuff to give a concrete answer here, I'd research if there is maybe a github/asset that already solved this problem or maybe a thread
i see i see
well thanks for your help π imma look through this stuff you talked about
by the way thank you so much for mentioning euclidean distanace in rgb, i was trying to hard to think of something like that but i couldn't put my finger on it
best of luck
thanks π do you want me to ping you if it works or should i just sent it somewhere and maybe you'll see it
Sure you can ping me no problem.. curious about this as well, may come in handy one day lol
then something is probably rotating the camera
is something wrong with the canvas setting?
the canvas's settings would not rotate the camera. it's likely something you're doing in an object's OnEnable or OnDisable
i dont understand whats wrong
//member variable
private bool initialized = false;
public void Deserialize()
{
Debug.Log(initialized);
if (initialized) return;
Debug.Log("honk");
var copy = new List<BlockEntry>(blockEntries);
blockEntries.Clear();
occupiedCells.Clear();
foreach (BlockEntry entry in copy)
{
RegisterBlock(entry);
}
initialized = true;
}```
Any reason why initialized stays true after domain reload in the editor? Shouldn't it revert back to false? I've nothing else acting upon it. Even tagging as Nonserialized still returning true. Maybe Unity bugged
well you'll have to look through more of your code
!code
π Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
my bad
here it is:
https://paste.myst.rs/nhmzk9tr
a powerful website for storing and sharing text and code snippets. completely free and open source.
how to most efficiently allow a test assembly to be able to access the internals of all other assemblies?
I'm doing tests
I have about a million testing-only functions and this really isn't making much sense anymore
now look at the rest of your code
whats wrong with it?
how should i know? i haven't seen it
i just sent it
i said the rest of your code
Couldn't you make an assembly that has a dependency for every other assembly and use that first assembly as a dependent on the test assembly?
this gives me access to public members only
made some progress, but things still bug out where the characters snap back to the original position and dont move forward, any suggestions on how to fix?
https://paste.mod.gg/vnzbgbkyrqbh/0
A tool for sharing your source code with the world!
Internal? That seems weird to need access for that . . .
it's for tests
I figured out I can access internal ones with a file I put in the assembly, but not private ones
I'm trying to dynamically change font on my TMP asset in script
I have this, but the text will display "[...] <font=Vintage Poison SDF>f"
Help?
I've verified my imported font is spelled correctly. Multiple times.
I have two circle prefabs for a college project, one is supposed to be a fruit and the other one is supposed to be a bomb. How can I differentiate them in code (not color) so that my program can do certain things depending on which one it's handling? I'm really unfamiliar with how Unity works so I'm not sure how I would go about doing this
what differences are supposed to happen between them? you probably just want a dedicated Fruit class and Bomb class to handle the functionality. Both can derive from one base class
forgot to mention about that. I should and how I have it currently isn't good, but I'm low on time and I can't entirely rewrite how that stuff works right now. Is there another way?
one is supposed to add points and the other is supposed to subtract lives and delete all of the former ones
visually they will be differentiated
then you essentially have no difference between them. saying you're low on time here really doesnt change anything. this takes like 5 minutes to write.
so how do you differentiate there? different components?
or is that where the issue is
if you don't actually have any real difference between them, now would be a good time to introduce that difference, with separate components or tags or something
yeah that's more of what I meant
I thought I would have to change another system I had, but I thought about it and I can actually do classes for these
thank you, sorry about such a question
hello quick question so i made an assembly definition file in a folder to put all utility plugins but how do i know which assembly reference a script (plugin) uses so i can add them without just guessing
A script is always part of the assembly of the asmdef file in its folder or its most immediate parent folder that has an asmdef
moving some plugins to the folder i made that has the assembly file will cause some plugins errors but not all plugins
how can i avoid that
You shouldn't be moving plugins into your assembly folder
Can you back up and explain what you're trying to do?
hmm i mean to make code compilation faster some youtube videos suggested to do that so that you only recompile what changed and not everything
So what are you trying to do? Put your game code in an assembly?
no XD the editor tools
Which editor tools
if i recall correctly this is the vid i watched
The first 1000 people to use the link will get a free trial of Skillshare Premium Membership: https://skl.sh/gamedevguide05211
Learn how to get back into the Editor faster after making changes to your code by using Assembly Definition Files in your project!
Gameplay Logic using Bolt: https://youtu.be/tP9_YBpBBpI
Attributes and Reflection: htt...
like hierarchy designer
3rd party asset
Does it already have an assembly definition?
i call them plugins XD it caused some confusion my bad
lemme check
hmm i don't think it does have a file of its own i checked but if i move it to the folder i made it throws an error cause it needs a reference but i don't know which one or do i have to check each script to see
sorry for the confusion
for a plugin that has editor scripts and runtime scripts you would need to create two aseemblies for it
You shouldn't be creating Assembly Definitions for third-party assets or moving them anywhere
one for the editor, one for the runtime
and the editor one generally needs to refer to the runtime one
Your plan of just throwing all of your plugins into a single folder and plopping an asmdef in it probably won't work out.
most plugins already come with their own assembly definitions out of the box though
the ones that are well put together at least.
well i already got 10s of them in the folder then 2 or 3 that errored out won't be a problem anyways
i noticed some do yes
i'll leave them be
check the above video its what made me do it
Hi! I create a tracking arrow that follows an object (or a waypoint) offscreen around the player UI. It helps the player follow waypoints and objects.
Camera cam = GameManager.instance.player.GetComponent<PlayerController>().playerCamera.GetComponent<Camera>();
RectTransform canvasRect = canvas.GetComponent<RectTransform>();
//Calculating width to height display ratio to adjust the values
float widthRatio = (canvasRect.rect.width / cam.pixelWidth) * canvasRect.localScale.x;
float heightRatio = (canvasRect.rect.height / cam.pixelHeight) * canvasRect.localScale.y;
//Creating a Vector3 fromt the waypoint coordinates with the Y set the same as player (always under the camera)
Vector3 waypointCoordinate = new Vector3(trackingObject.waypointData.coord.x, GameManager.instance.player.transform.position.y, trackingObject.waypointData.coord.y);
var screenPos = cam.WorldToScreenPoint(waypointCoordinate);
//Getting the (unscaled and unadjusted) Screen position of the object
RectTransformUtility.ScreenPointToWorldPointInRectangle(trackingArrow.GetComponent<RectTransform>(), screenPos, null, out var worldPos);
//Scaling for display ratio
worldPos.x *= widthRatio;
worldPos.y *= heightRatio;
//Removing half the screen size
worldPos.x = worldPos.x - ((canvasRect.rect.width / 2) * canvasRect.localScale.x);
worldPos.y = worldPos.y - ((canvasRect.rect.height / 2) * canvasRect.localScale.y);
//Normalizing to get the edge position
Vector2 normalizedAxis = NormalizeByMaxAbs(worldPos.x * (canvasRect.rect.height / canvasRect.rect.width), worldPos.y);
//Applying back the normalization to the edges and applying the Canvas scale, finally having the arrow position
worldPos.x = ((normalizedAxis.x + 1) / 2) * canvasRect.rect.width * canvasRect.localScale.x;
worldPos.y = ((normalizedAxis.y + 1) / 2) * canvasRect.rect.height * canvasRect.localScale.y;``` That's the main code (edit: comments and format)
