#archived-code-general
1 messages ยท Page 332 of 1
yes
Thank you :))
raycasting wont work , as some portoin of cuboid can possible still go inside terrain , bcz it only ensures hit.point be above terrain not the whole cuboid , and about boxcast i dont know what that is , i will see how to use it, thxx
i guess you don't know about the existence of math to determine where in relation to that hit.point you would put the object?
as far as i know , hit.point gives a vector of position x y z of the point of intersection of ray and the collider
yes
but that wont work , bcz only the transform.position = hit.point , not ensuring if the whole bounds of cuboid are above terrain , bcz terrain is not flat
again, do you not know that math exists? you know you can use the bounds of the collider to determine how far you need to offset the position from the hit point, right?
Don't directly set the object's position to the hit point but rather set it to that with some offset.
ok , how to calculate the offset tho?
is it something like , the bounds of overlapping collider - hit.point for X and Z axis?
the distance from the pivot point of the object to the point on the bounds where you want the object to rest is the offset
yes, you can ask for help in here like literally everyone else
the thing is though, is that you have to ask a question if you want help
it's a link. click it and read it
ip grabber
phisher
stay away pal..
ight na seriously tho @somber nacelle U tryna help me with sum
it's not even my website, genius. and it is a permitted link
no
you haven't even bothered asking a fucking question
ight my bad
Basically instead of asking if someone's available to help, just ask your question. If someone who is on the server feels like they want to answer/help you, they will.
how do i make my player die after contact with object
Break the problem down.
Define contact. Define die.
ight so
or just like google the question
For example: On collision enter and Destroy
when red touches white
i want white to
die
and game over screen happens
also sub question: do i make game over screen first then add the contact on death thing
Without knowing anything about your setup (physics or no physics), there isn't much that folks can suggest without fishing for more information or simply designing your game.
i dont really get it
what more information do i provide
im ngl what is physics
ohh
i searched
ye i am
and i am evaluating contact by when on screen red touches white
Alright, so you need to break the problem down and consider how you're going to be actually evaluating "contact" between objects.
alr just lmk this
since I want to make it so that when red comes in contact with white a game over screen shows up and users get option to restart or exit, do i make the game over screen first
Your eyes can perceive it but how is your application going to be evaluating contact?
when like two coordinates are in the same place
So.. with rigid body physics, character controller, collider cast, other physics casts or ?
rigid body
Google Unity Rigidbody collision
There ought to be plenty of tutorials on this. After acquiring this feature, determine how or what you'd define as "die".
bro i aint gon lie
u the most useless person i met in my entire life
i deadass just had a conversation w a brick wall
thx
You're expected to know the basics in the general channel. If you cant google, well the problem lies between the screen and the chair.
u think i would come here to ask before i googled ๐ญ
Yes, many beginners do.
surely if u googled u would have found something..
nah not anything that works
๐ idk if you know a lot about tech, but IP grabbing is basicly useless. The only thing what's dangerous about it is that they know your location.
That seems to be the standard, yes
i was joking bro ๐ญ
Hopefully this was a joke too
#archived-code-general message
pls stop talking to me
It's so that the people, posting here, are usually expected to already have some intermediate knowledge about coding. If you don't, consider posting in #๐ปโcode-beginner. There, you're expected to at least be able to use any suitable browser to find the information you're supposed to know. If this is beyond your skills, consider not asking at all.
One thing is when jm moving from top of ladder to bottom its not going on the launder(ladder is slanted so i want it to roll it over it). Its kinda launching itself and landjng luckily
Also the turn its making from red platform to ladder is instant, I want it to be seemless
i have a tps character and im using a state machine, should i create a state for my character's aim state or should i check if im aiming in other states (if anyone can help i can send you the project, because something feels wrong)
the character's movement system changes while aiming
Hi, im working on a door raycast script and im pretty new to this raycast stuff so i may not understand completly but logically why isnt this working.
public class DoorRaycast : MonoBehaviour
{
MyDoorController mydoorcontroller;
public void Awake()
{
mydoorcontroller = gameObject.GetComponent<MyDoorController>();
}
public void Update()
{
if(Input.GetKeyDown(KeyCode.E))
{
RaycastEvent();
}
}
public void RaycastEvent()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, 100f))
{
mydoorcontroller = hit.collider.gameObject.GetComponent<MyDoorController>();
if (mydoorcontroller != null)
{
mydoorcontroller.PlayAnimation();
}
else
{
Debug.Log("NotFound!");
}
}
}
}
When e is clicked it sends an raycast and if the object that was raycasted has MyDoorController script then the PlayAnimation() Inside it is called, or Debug.Log is called. However when i click E on the door nothing shows up in the console at all
Place a log and see if the method was called
to start with add a debug if the raycast fails
I have debugs in both scripts and for some reason nothing shows up in the console
well it wont if the raycast fails
You need to debug at a higher scope
I think i found the faulty one.
public void Update()
{
if(Input.GetKeyDown(KeyCode.E))
{
RaycastEvent();
Debug.Log("E was clicked!");
}
}
It never debugs anything in the console
Bug the code looks correct so why is that
the object or sript is disabled
Is the object inactive? Is the component disabled? Did you save?
Are logs enabled in the console window?
Have you tried turning Unity off and on again?
Alrighties i fixed the E problem, so now E is debugged, Raycast gets sent out successfully but the other script is not found
I have a GameObject called DoorPivot, and inside it a GameObject called Door. Now the DoorPivot has the script but it doesnt have a box collider, while the Door itself has the Box Collider but not the script, could that be whats causing this?
Since i thought because that Door is a child of DoorPivot it automaticly is detected too
Please don't be a bully to people that are actually helping people
Consider logging or drawing the ray to verify if it should indeed be hitting
I found it, it was just that i had to give the pivot itself an Box Collider and it cant have an box collider because the pivot doesnt move, only the door does. So istead im just making a third door controller script which will be in the door itself then call the Pivot to play animation
there is a reason why windows and Browser bring updates every now and then , Grabbing IP is a stepping stone for an attack , I use Google Chrome , and it has some network vulnerabilities now also , I got a browser hijacker with a keylogger too , by just opening a fishy redirected ad link , not even downloaded anything .
I talked to 3-4 more people who opened that website , they got it too . The best guess is , the hackers have used my IP adress to connect to my network and find network vulnerabilities in chrome , and installed a malicious plugin in chrome and other browsers , after that my browser had this " Managed by your Organisation" , with 2 russian malware pugins installed in my edge browser .
So never underestimate hackers and always use an adblocker .
Although rare , but u can be a victim of an exploited vulnerability of a browser ( altho they are patched quickly in most cases)
You clicked on a link which gave more than your IP.
what do you mean ? i didnt understood?
I'm just saying that an IP grabber can't do stuff like that. It just gets your IP adress. Nothing more. You clicked on a malicious link which had way more stuff added
i am just saying grabbing your IP can have implications like these, if you are really unlucky .
What implications?
Because the stuff you listed above is not because of your ip
a hacker who has your IP can use various techniques to compromise your network and gain unauthorized access , If they manage to connect to your device,
altho to my knowledge its only limited till browsers hijacking, they cant install an exe file tho
the hacker must have grabbed my ip adress first and then tried to connect to my network to exploit any existing chrome vulnerability or maybe any general network vulnerability . Altho its all a guess noone knows how he did it .
It was certainly not from your ip
You can't do that with an ip
It's like your local address. if we have it, then we can't teleport to you
Even if you had the IP address of some random individual, you'll likely not be able to exploit them unless you're aware of some application that they're using and if you're given consent to launch the application without constraint.
thats what i said , it cant launch any application , but it can still affect browsers , because browsers are connected to network .
Everything connected to your network is still vulnerable , your data , your online games and all
sorry, no. you are wrong
No offense, but you have a profound misunderstanding about what an IP address is and what it can do
do static attributes persist between scenes, assuming they aren't tied to an object
If you've got active x and java script enabled with no constraints and whatnot, then perhaps your computer could be compromised if you accepted and launched whatever web app embedded in the site requested you to.
even if they are tied to an object, static variables always survive until the end of the application domain
More than likely though, you've contracted a virus or malware through installing some component/app or have given permission you weren't aware you were giving.
static attributes?
public static int, so on and so forth
ohh a field, yeah as SteveSmith mentioned they will
In C# an attribute is something else, eg. [SerializeField] is one
(these cannot be marked as static)
I am certainly not a cyber security expert , but i know that grabbing IP address is the first step to any cyber attack , it can tell a hacker which system to attack ,
I have experienced it myself so i believe it in it , and i have read some blogs from Microsft , nordVPN and This forbes blog also i am attaching , i am not trying to convince u or so , but i believe in this, bcz i suffered a whole day bcz of it and always now use an adblocker
Your issue... had nothing to do with the ip. Simply having the ip will not allow what happened to you
It is also NOT necessary for what happened to you. You likely downloaded a virus
Lastly, someone can get your ip in many ways
if I assign a field to a prefab (like the value is a script attached to a prefab) can I change that? like is it an instance I can alter
Okay lets close this convo . was just trying to tell my experience , i certainly dont have sufficient knowledge to justify myself more than this
no
So you'd reference some class with your field and you'd be able to create/modify an instance. What's the concern?
You are spreading harmful misinformation.
I definitely would appreciate it if you stopped
ah, so I have to rewrite it then?
ah whatever
ill figure it out
this is not misinformation , its true and happened to me , and as far as i know my explanation is correct , u are not counterattcking me with points . thats why i am not contnuing this convo anymore , again no offense to this . please lets believe what we believe .
Believe what you want, that doesnt change how attacks work
If I have two empty gameobjects in the same position acting as "connecters" how could i find other connecters starting from a connecter? Hope I made myself clear
just so you know, for future reference, your public IP address has nothing to do with your computer. It is actually is linked to your router
I believe the truth. You are objectively wrong. And that is ok, but please stop
What you are doing is akin to saying clouds are made of fish, and you have tons of people saying no they aren't, and your response is that "well I saw a fish"
It's hard to argue with something that obviously incorrect without just saying you are wrong
you would need some type of query maybe physics or just position based
Realistically you wouldnt want to do this. Youd be comparing positions, you should have a more defined system of what connected objects are
Cant use physics if they're empty
Can we move on from this IP thing, it's not even Unity related
lets say I have public Ammo myAmmo and I set that value to a prefab gameobject that has an Ammo attached
then, in some other script, I say player.myAmmo.damage += 1
when I fire the gun, hence instantiating myAmmo, is the damage increase there?
You just gave me an idea, thanks
Prefab would be an asset you'd want to reference to spawn. If you're needing to keep track of persistent data, perhaps consider a Singleton manager
keep stored stats in a POCO
Sorry, can you explain me more ? I'm not sure to understand completly
var x = GameObject.Find("Hidden Layer Node 2/Input value");
Debug.Log(x);
var y = x.GetComponent<Text>();
Debug.Log(y);
Somehow y is null here?
x is logged as Input value (UnityEngine.GameObject) so I'm not sure what's going wrong here
I just want to grab the text elment
Was there an error?
This is the input value so it is a text element... Is the Text class referring to the legacy Text element?
No, just y being null
dont use find/get component if possible ie you can reference it
use TMP_Text
Text is old yes
That likely means x isn't what you think it is or that it really doesn't have said component
Text is def not TMP_Text
also no reason this should be a find. As @fervent furnace mentioned use a serialized field
Ah TMP_Text does the trick. Should've just answered my own question :p
I'm building a graph (essentially) so have to dynamically grab many elements, hence the find
What is the time complexity of Find?
Should I store all the objects or is it fine to keep re-calling
its extremely slow and makes decent amout of garbage, thats all i know
O(number of gameobjects in hierarchy)
๐ Cheers guys
if you're on 2022+ use the physics debugger
if you are on a version older than that, you'll need to draw the raycast with debug.drawray or something
Cool new debugging features inside Unity 2022+
im using unity editor 2022.8.3f1 but cinemachine 3 is not available
2022.8 ?
did you check package manager?
i did
pretty sure you can manually install it by name in that version. but is there a particular reason you are using such an old patch of 2022.3?
hmm maybe you could manually change manifest
a friend suggested this ;-;
which is the best version other than unity 6?
then just update to the latest patch if you don't have any real need to be on that specific patch version
ok thanks
2022.3. but you're just on a really old patch for it
the latest 2022.3 version is 2022.3.31. you are currently on a patch that came out in august of last year, which is also before cinemachine 3 was actually released from beta
thank you ๐
please use a better site for code !code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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.
have you actually enabled the physics queries in the physics debugger?
it looks like this for me ๐ฆ
nothing is changed in the code, if you're using physics queries the code is not important to draw debug them
this video will show you how you can see them in the playmode with built in analyzer
(window -> analysis -> physics debugger)
if you do not see any raycast after enabling the queries in the physics debugger then you need to check your conditions to make sure that they are actually allowing the raycast to be fired
can you show it where you enabled
but yeah now im starting to lean towards your code being sus
if (isShot == true && ammoClipLeft > 0 && isReloading == false)
ook good. Just double checking
maybe throw some debug.logs in there and see if that section is even being hit
do you see anything if you also enable Cast there?
which part of the shooting?
Ohh
you know what you need that
thats your raycast
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
what do you mean by that
the ray is working
so you do see it then?
don't
I think you're assuming its supposed to come out of the gun
if you want ray to come out of the gun, you need to set the ray start and direction from your shooting point
just an empty gameobject
call it (firePoint) or some shit
ideally its child of the gun and if its child of camera, they should have correct look direction
make sure (blue) arrow points forward in local mode (not global)
then you can just do
ray = new Ray(firePoint.position, firePoint.forward)
it's very common to use empty game objects as reference points
game objects don't have to have any components on them (other than the Transform)
that's not jank at all
I'm saying I would consider creating a specific class, which might store the essential data for the merged ScriptableObjects. This class can also have a static method, which takes a List of the ScriptableObject as its parameter, and updates the necessary variables
public class Spell
{
public Spell(...) { ... }
public static Spell Merge(List<SteamoxSO> steamoxSOs) => new(...);
}
//
public List<Spell> spells = new();
//
spells.Add(Spell.Merge(selectedItems));
whats jank about it ? its pretty common
do note it also depends on the game, some games the ray does not come out of the gun just the visual FX
Counter-Strike is a good example of this
(the weapon ray always fire from center of screen)
I need a heap with a decrease-key operation. Any suggestions for a library?
I'm looking at implementing a Fibonacci heap, and it's mildly scary looking
certainly compared to a binary heap
C#'s PriorityQueue does not have a decrease-key operation (and it's not available anyway)
I might just insert duplicates. This is for A*.
What is "decrease-key"?
It lets you reduce the value of an existing item in the heap
so in A*, you might discover a cheaper path to a node that you haven't visited yet
you store all of the unvisited nodes in a heap
you can either push a duplicate element with a lower value or decrease the value of the item already in the heap
I'm...not using a heap at all right now, so maybe I should do that first ๐
Would a SortedList be good enough
Just remove and re-add an element when you find a cheaper cost
adding items into a SortedList is O(n), which can be pretty punishing if you're adding and removing items at roughly the same rate
heap insertion (and removal) are both logn
Sorted dictionary?
(and fibonacci heaps apparently get amortized O(1) for insertion too, scary)
a SortedDictionary is a binary search tree, which is also worse than a heap for this purpose
I completely forgot I wasn't actually using a heap yet, so I'm going to do that first lol
hey guys can i have some help? for some reason im putting a text on my screen in unity and its not showing up in game view
also in scene view its all blury so im not sure if im doing something wrong?
im a beginner by the way
this is not a code problem
hm , can i show you a picture of show my screen over a muted call perhaps?
I see ! But create a JSON file for each spell created and in it write every stats and stanza used is a good thing ?
Share screenshots in #๐ฒโui-ux
getting it handled in unity talk rn thank you tho!
what will be the best method to make these lazers?
Line Renderer maybe ?
they seem pretty simple
I used a similar approach drawing with a Raycast, you just need a good material
It's good !
I created sript for generate and use JSON (JSON contain the list of stanza)
Now i have a good thing for storage, initializing and use spell ๐
Amazing, that idea you gave me works perfectly, thanks!
With that I solved a problem i was trying to fix for 3 days
Glad it works, although what I said was barely an idea ๐ just told you to make a system for it
Guess your message made my last neuron work for a few seconds ๐คฃ
how do I rotate a rect transform around it's center? regardless of where the pivot / anchors are. I've tried iconRT.RotateAround(iconRT.TransformPoint(iconRT.rect.center), Vector3.forward, (rotated) ? 90 : 0); but it still rotates around the top left corner of the RT and not the middle.
edit: nvm im stupid
Is it possible to fork unity and contribute to it/modify?
the engine itself is closed source, except for the c# bindings. there are open source packages though. i'm not sure if they accept contributions though
at least, packages whose source you can look at; they aren't FOSS-licensed
does anyone know any good melee combat tutorials? for punching?
So, as you can see from the GIF, I have a problem where the mesh renderer appears to be very selective when rendering the areas that have been dug out. What I've been able to deduce so far is that this is caused by the fact that, rather than the ground being a single 10x10 mesh it's 10 1x1 meshes linked together. However, I don't want to fix this by making a single 10x10 mesh since it's not going to scale well with the project. So how do I solve this problem without doing that?
is it normal for memory to not be released in editor?
ive destroyed game objects containing mesh data, but yet the amount of memory that belongs to mesh according to profiler does not decrease
Nothing is being shown but yet 1.8gb in meshes?
- Asset unloading happens on scene unload. You can force unity to unload unused assets manually by an API call.
- If it's a generated mesh, you might want to destroy it as well, before destroying the object.
- Editor might behave differently than a build.
To clarify point 2, assets are not unloaded or destroyed by the GC as objects do(when all references to it are lost).
And mesh data is considered an asset.
I see
I know GC would not be called on some unity objects, so i ttried clearing out mesh before deleting, but even that did nothing
Strangely enough, it seems the editor frees the memory if you need more
How did you do it?
And is that during play mode?
Maybe DestroyImmediate(sharedMesh) instead.
copy
let me see
sec, let me restart scene and test
picture 1) Empty scene
pci 2) scene after work
pic 3) scene after clear.
didnt work
Using DestroyImmediate?
There's also a possibility of you having a leak. If you generate several meshes during the session and reassign them where previous meshes were assigned without destroying the old ones.
hey so I am making a wave type system however for some reason when the next wave comes it refers to the previous wave sorta like this:
Wave 1 > Wave 1 > Wave 2
{
//Calculates the number of enemies in a wave to spawn (this is set in the Wave scriptable object)
for (int waveNumber = 0; waveNumber < currentWave.NumberToSpawn;)
{
int enemytoSpawn = Random.Range(0, currentWave.EnemiesInWave.Length);
int enemySpawnPoint = Random.Range(0, spawnpoints.Length);
Instantiate(currentWave.EnemiesInWave[enemytoSpawn], spawnpoints[enemySpawnPoint].position, spawnpoints[enemySpawnPoint].rotation);
waveNumber++;
enemiesAlive++;
}
}```
Wdym by "refers to the previous wave"? How do you know that?
so I use waves as scriptable objects so I can customise each wave and well when just having 1 of them in the waves stay at 0 for some reason but when I add Wave 2, it repeats Wave 1 then goes into wave 2... Sorry if that doesn't make sense xD
How do you know that? How are you confirming that that's what happens. And what does it even mean "to go into wave x"? How is it expressed in code?
when I used
roundNum.text = "Round: " + currentWave.ToString();
instead of
roundNum.text = "Round: " + waveNumber.ToString();
I got the name of the scriptable object so when the 1st wave started I could see which wave was initiated, then once all the enemies are done it should have initiated the timer which it did then move on the the next wave but it seemed to have initiated Wave 1 instead of 2.
I used this code to increase the wave
{
//increase wave
if (waveNumber + 1 < waves.Length)
{
currentWave = waves[waveNumber];
currentTime = 10f;
}
else if (enemiesAlive > 1)
{
//stop spawning once limit is reached for the wave.
stopSpawning = true;
}
}```
So, to put it simply, waveNumber doesn't have the expected value?
pretty much yeah
You should debug it then whenever you're modifying the value
thats pretty much what I'm doing though I will say it's weird when I take out waveNumber++; the engine crashes xD
As well as when the it is used
Must be resulting in an infinite loop
I don't see any debugs in the code you dhared. Are you stepping through the code via the debugger?
If you mean removing the ++ here, then yes, that results in an infinite loop
Use proper debugging methods and you'll figure it out in no time. You're supposed to be able to debug if you're asking in this channel
I usually take out the debug logs before posting xD
Don't do that. That's the worst thing you can do to people you're asking help from
yeah thats my bad xD just picking up programming again
Share the code with the debugs and the result in the console.
Since it might be a lot of code, share it all in one code paste link.
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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.
Hey guys I'm having a little problem
So I have an overlay canvas and inside of it I have an Image of my character. The character in the UI is a parent of another Image component that is basically acting like an accessory, player can move it around. Later when player confirms the accessory on the character, local ui position of the hat/accessory image is saved and I want to apply that to my character in the world space.
Basically, original character is a SpriteRenderer in the world space and he also has the accessory spriterenderer transform as a child.
How would I convert the screen space local position to the world space local position?
Character sprite is the same in the image and the spriterenderer
You should debug the waveNumber value. Logs that debug the same thing don't really help at all.
this is really cool, how is this done
The mesh vertices are pushed down
That's basically it
how does one do verticies editing?
You need to know the relation between your screen space positions and world space positions. If you have 2 points of reference that are equivalent in screen space and world space you can do that. For example, if you know the vector from your character pivot to it's head both in world space and screen space.
this is after the
{
//Calculates the number of enemies in a wave to spawn (this is set in the Wave scriptable object)
for (int waveNumber = 0; waveNumber < currentWave.NumberToSpawn; waveNumber++)
{
int enemytoSpawn = Random.Range(0, currentWave.EnemiesInWave.Length);
int enemySpawnPoint = Random.Range(0, spawnpoints.Length);
Instantiate(currentWave.EnemiesInWave[enemytoSpawn], spawnpoints[enemySpawnPoint].position, spawnpoints[enemySpawnPoint].rotation);
Debug.Log(waveNumber);
enemiesAlive++;
}```
Where?
Looking at this it's always a unique value.
Also, you should make your logs meaningful like that: "on wave incremented wave number: x" or "on waves reset wave number: x". Just numeric values can make it very confusing especially if you're debugging it in multiple places.
yeah I need to remember that my bad xD
But yeah I think I know what it's tied to since there are 5 unique values, I believe it is tied to the amount that is spawned which is kinda strange I think I need to untangle my code
did you recalculate the bounds of the mesh?
I'm not sure if that happens by itself
Yeah, I was told in another server to try doing that
it looks like the meshes are vanishing once the original bounds of the mesh (which is flat ground) go off screen
Haven't done it yet though
Show the code that modifes the mesh
Okay I found the issue turns out if I have just Wave 1 this code won't initialise:
{
if (waveNumber + 1 < waves.Length)
{
waveNumber ++;
currentWave = waves[waveNumber];
currentTime = 10f;
SpawnWave();
Debug.Log("Wave: " + waveNumber);
}
else if (enemiesAlive > 1)
{
//stop spawning once limit is reached for the wave.
stopSpawning = true;
}
}```
Fellow SO enthusiast using them for waves
my mate is like "why" and I'm like "what if I want to reuse them later??"
Makes sense. 0+1 is not smaller than 1.
Not quite sure what that condition is testing.
can someone help me i changed this little character i made from using character joints to configurable joints and the character fell through its self
so after doing this:
{
waveNumber ++;
currentWave = waves[waveNumber];
currentTime = 10f;
SpawnWave();
Debug.Log("Wave: " + waveNumber);
}```
I get the following:
oh nvm i just had to turn xyz motoin to limited and turn collision on
Thanks! I did it ๐
Yes, because after reaching the last element and running this code, it would try to access an index that is out of bounds.
Make sure you don't run this code if you reached the last element
Well atm I am trying to do is start the wave then use the wave to begin the spawn i figure that way it's easier to debug
It doesn't matter what you're trying to do. You should handle out of bounds correctly. Imagine you have 5 boxes with apples, them you try to take out an apple out of box 6(it doesn't exist). What would happen?
Hey guys I'm trying to make a button object that has a cool down in between presses, but I am unsure on how to do so.
yield keyword can only be used in coroutines(IEnumerators to be correct), not in regular methods.
How can I use the coroutine and onMouseUpAsButton together?
Also, it is yield return
Then you can pass a new WaitForSeconds (or cache one)
StartCoroutine
It'd continuously run the code over and over? Ngl I feel dumb xD
You'd crash the world. You can't access something that doesn't exist.
true xD well I guess I am sort of making progress now
is this how it should be? And if so where do i put my WaitForSeconds() because its only waiting to run my code. Its not really a cooldown.
Yes, that's a coroutine. Now a cool down would need some more logic.
This would delay the Farm call by clickCountdown time
Cooldown could be handled with bools around a wait call. Check the bool before allowing the coroutine to start again (just one simple way to do it)
Thanks I got it working with just a cooldown bool
you're checking cooldown twice for the same thing ?
also coroutine would've been better than Invoke not sure why you changed it lol
void OnMouseUpAsButton()
{
if (farming) return;
StartCoroutine(Farm());
}
IEnumerator Farm()
{
farming = true;
farmerManager.Farm(level, Color);
yield return new WaitForSeconds(cooldownTime);
farming = false;
}```
lmao thanks for the help. I am new and am still learning. Just to clarify, the "if (farming) return;" part makes it so the code under it ("StartCoroutine(Farm());") doesn't run when farming is true?
exactly, it "returns" early out of the function
since the function is void (does not return anything) you can just return no value
Is there like a list of good practices for making a game more moddable
why doesn't the value out equals 6 but 5 ?static void Main(string[] args)
{
int value = 5;
Console.WriteLine("Value before increase: {0}", value);
IncreaseValue(value);
Console.WriteLine("Value after increase: {0}", value);
Console.ReadKey();
}
static void IncreaseValue(int value)
{
value++;
}
because of the difference between value types and reference types. also this is a unity server, not a general c# server
I'm sorry but can you explain a bit more into that, I will send them to a c# server later
there are beginner c# courses pinned in #๐ปโcode-beginner
you should probably start there
I'm pretty sure I could implement this one of two ways, but I wanted to ask you guys for advice and thoughts on this.
I want to use a State Machine to control combat in my Turn Based RPG, and my plan is that each action is its own series of States, OR its own state machine.
This means, for example, when you hit "Sword Swing", the game will load a state machine that asks for a target in one state, moves the player to that target, then performs the attack, making the character perform the state machine's states in sequence.
Would it be better to have Scriptable Objects that just hold a list of states, which are loaded into a State Machine attached to the character, or have a Scriptable Object that holds an entire State Machine, and the player merely switches between those?
All numeric types are value types. Classes for example are reference types.
When it comes to value types, the variable is passed by value and not by reference. This means you make a copy of the value and pass it over to the method. You will not edit the actual initial value because of this
Other instances of value types are structs, Vector2, Vector3 and Quaternion, for example. Your IDE usually differentiates value types from reference types when they implement a struct type rather like a class type (like the ones mentioned here)
You can fix your code to pass a reference type. Just change the method signature to this:
static void IncreaseValue(ref int value)
And the call to the method:
IncreaseValue(ref value);
For clarification, the reason why this difference exists is performance. Especially with vectors the difference is very big when computing values as the reference must be cleared otherwise. This is done with garbage collection and it can impact your game significantly if left done improperly.
So.. your states are only sequential then what is the difference between list of states and state machine?
Honestly, not much, which is why I ultimately ended up just using a system to switch thhe states in the state machine.
I assume your character can only have single state across all actions
Only one state at a time, yeah
So character should be something that knows what state they are on
but if your action needs to override something about states
Action should have some way to hook it ig
I mean I wouldn't really think this as state machine tho
Just list of tasks maybe
Some of those tasks need their own logic and behaviors, though, and need to be able to backtrack, since combat actions need to be able to request UI input and wait for it, and be able to be backed out of with the cancel button and things like that.
Sure, but those logics are defined in each states right?
What's actually running those state doesn't seem that important in this case
I made an options menu so the player can change resolutions and quality, but when i start a game and then go back to the main menu this settings reset, any idea why?
Btw this reset is only at a visual level, but if the res is changed it stays, only happens with the HZ
I'm trying to use BatchRendererGroup to make my own "MeshRenderer" for most of the two most recurring meshes (Cubes & DoubleFacedQuads)
However what troubles me a lot is how I'm meant to sync the transformations of the Transform's transformations with the BGR instances
How am I meant to sync all the data? I could try SetData and calculate the offset for each individual movement however... Well, I can bet that the performance implications of SetData is nothing like that of just copying stuff into an array
I can't use GraphicsBuffer.LockBufferForWrite either cus Unity crashes if I create the buffer for BGC's instance data with that flag on
So the last resort in that case would be SetData once every frame, it would seem
Since there're prone to be many cubes moving... SetData once for each cube's movement is really bad, Setting once per frame for everything might be costly too but maybe it's not as bad
Nvm overlooked something- In one of the articles they recommend making one such buffer on the cpu
Still needs to perform SetData every frame... Hopefully it's for some reason extra performant copying the whole buffer over
How do I convert a base64-encoded audio string I receive from a websocket message into an audioclip to run at runtime?
you will need to convert the base64 string back into a byte array and then this may help
https://forum.unity.com/threads/byte-to-audioclip.911723/
Hello all,
I've been messing around with sockets on unity and had the idea to make an online voice chat system, It sends the audio clip to the server...
Has anyone seen behaviour like this in the profiler before? The rendering numbers keep dropping to 0 and back to normal again?
Hi, I have a reasonably big unity project with around 30 scenes, and made a big refactoring process, the thing is, i have added a lot of serialize fields, i want to see for each game objects if he has some fields with none values inside in all scenes (or minimum one scene)
Is their someone that could help me finding a tool or something like this ?
Screen.fullScreen works properly? Because im trying to update an image to be enabled or disabled depending on if the game is fullscreen or not but its not working
rider/resharper will show usages in assets inline on the field, i think that should show usages in scenes too?
i'll tryl
Hi, my plan in the function MoveChildToParent is to delete the desired item from the string, but for some reason it randomly deletes another item
https://gdl.space/enoyuqojeq.cs
I don't understand what you're asking for
Are you looking for fields that have nothing assigned to them?
I have added serialize fields to some scripts, and since they are used in a lot of scenes and objects i want to edit all of them and not forget any, also since i changed multiple script i could miss a script
the idea is to have some tools that will find each object that have empty fields
I've written code to do this, actually
it's still very rough, but maybe you can use it
i would love to have it
https://gdl.space/idiyidabob.cpp
This is most of the code. You call ReferenceValidator.ValidateOneObject with any object, as well as an optional Unity object as a context for the log items
it also takes a visited hash set. you can use that to remember which fields you've already alerted as being null, so that if you validate many objects, you won't get duplicate warnings if they all reference the same object that has a missing field
Here's an example of how I used it in my code
[ContextMenu("Validate References")]
public void ValidateReferences()
{
HashSet<object> visited = new();
ReferenceValidator.ValidateOneObject(this, this, visited);
ReferenceValidator.ValidateOneObject(defaultBrain, this, visited);
ReferenceValidator.ValidateOneObject(defaultLocomotion, this, visited);
foreach (var module in GetComponentsInChildren<Module>())
ReferenceValidator.ValidateOneObject(module, this, visited);
}
notice how I'm passing the same visited hash set to everything
The validator will stop when it sees a class from a different namespace. I did that because third-party components had many fields that could safely be null, and I didn't want to have to go modify them and add my [MayBeNull] attribute
For each null field, it logs the path it took to get to the field. The log message's context is the closest unity object
If it went into a prefab, clicking the log will just highlight the prefab. Running the validator with the prefab open (sometimes) highlights the component properly
If you want to validate objects in scenes, you'll need to open the scene and then use FindObjectsByType or something similar to scan for the component you're interested in
Thanks a lot i'll try making it into a plugin
https://docs.unity3d.com/Packages/com.unity.ai.navigation@1.1/manual/NavMeshSurface.html
Generate Links
If this option is enabled, objects collected by the surface will be considered to generate links during the baking process.
See the Links Generation section for more information.
Where is this links generation section?
https://www.youtube.com/watch?v=WBXti5pea88 OK this video has an example of it
Part 5 of this series on Unity pathfinding to look at how to link different nav mesh surfaces together.
--
Support our tutorials on Patreon for access to our finished projects and vote for new topics.
https://www.patreon.com/tableflipgames
--
Table Flip Games
We are a team of specialists in video game development and technologies with experien...
I wonder if they forgot to port that page over
The navmesh stuff mostly moved into a separate package
tbh the old Github NavMeshComponent documentation is far better than the new AI.Navigations ones and there is very little functional difference
Unity moment
How unity handles toggles to make the image inside dissapear?
Yeah, I suppose, this is what you'd usually do for this
Great, make sure this all is managed by a Singleton. Also, make sure each Spell has its own unique name e.g. Spell 1, Spell 2 etc., which can also be adjusted by the player
How does it make the Image disappear?
- Are you talking about how it makes its background a bit more transparent? It reduces the
Color'salpha. - Are you talking about it changing the sprites? It... changes the sprites.
right now if i go to another scene and come back
the toggle is always activated (which is what i want if the screen is fullscreen)
but even if my screen is windowed
the toggle is activated
Alright?
wdym by alright hahaha
I don't seem to get your question
the toggle is used to change between windowed and fullscreen. When i click it the image inside dissapears so only the borders are left. I want the image inside to be on if the gameis fullscreen and to be off if its windowed
The problem comes when i activate windowed mode, which leaves the image inside off
but if i go to another scene and come back
even tho im still in windowed mode
the image is activated again
yes ! Thanks for the help ^^
did you get it?
i have a lightning wich i want will follow after my swipes. i want to create a line from 2 points (start swipe and end swipe) and make the lightning follow the line thaht create. help?
do u guys have any idea about spawn manager? , like in a endless runner game, how to manage what is the next map to spawn ?, my idea is base on the score, i will add maps to a possible list then choose a random map
sound like a good idea. must be a toturial for endless runner
i am asking, i don't have enough experience to teach anyone, sryy
no i mean, you can search for a toturial for this
there is gotta be
here
take
Hey friends! Let's learn how to generate infinite levels and platforms in Unity with Procedural Generation! This is a follow-up to a video I made about Subway Surfer, and I thought this would be a good overview on how procedural generation works.
๐พ Join the Discord! https://discord.gg/MYAujpE4xG
๐ซถ Access Code Files and Projects! [patreon.com/...
how about zombies?, my game is endless shooting zombies game, how to manage what zombies to spawn ?
i really need help

about this sorry
Do u mean about mobile?
Yes. The image inside you're talking about is a Checkmark. Simply reverting your condition fixes the issue.
{
// Comprobar si los valores de la resoluciรณn estรกn almacenados en PlayerPrefs
if (PlayerPrefs.HasKey("ResolutionWidth") && PlayerPrefs.HasKey("ResolutionHeight") && PlayerPrefs.HasKey("RefreshRate"))
{
int width = PlayerPrefs.GetInt("ResolutionWidth");
int height = PlayerPrefs.GetInt("ResolutionHeight");
int refreshRate = PlayerPrefs.GetInt("RefreshRate");
// Establecer la resoluciรณn guardada
Screen.SetResolution(width, height, Screen.fullScreenMode);
Application.targetFrameRate = refreshRate;
}
}```
why my fps doesnt cap at my HZ chosen in the dropdown for the resolutions?
Time to use Debug.Log to check if this code is running and with what refresh rate
yeah i already fixed it but i still have one last problem, sometimes (Random) when i go into a scene and i come back i get always 600x480 resolution
Again - Debug.Log is your friend
so whats the problem exactly?
Well, probably, because that's what your width and height are
Also I don't think there is a need to check for all 3 strings being in PlayerPrefs, as you shouldn't access one of them without having the other two. Am I right?
im on 1920x1080, and sometimes i get reset to 600x480 and others to 1920x1080
So that's your width and height, as I have previously assumed?
Why don't you consider printing it?
i cant do that on a build
If in the build, print the text directly on the screen
i sent the build to a friend, when he opens it the new playerprefs i added to the code should be created on his computer?
cause they are not getting created
Yes, the PlayerPrefs is created on the device the game is played on. You shouldn't expect the PlayerPrefs, which exist on your device, also exist on the device of the other person.
They should be created if you do this via code. The shouldn't if you don't.
ok so the problem is that from time to time the bug occurs which after changing back to the scene of the main menu the screen gets automaticc biggest size
like it happens maybe 1/10 times
If i change res, execute level 1, go back to the main menu scene and check the res sometimes it gets automatic screen size
time to learn json
Do you understand hexadecimals?
I don't think I can give you a solution without more information on setting and getting your PlayerPrefs provided. You gotta put some prints to see what's actually hapenning first
hi
Better ahah !
someone know how to stop transmit speed between two objects when one have big force?
Alright, now this looks a bit more lively. Now you should consider making the unique names for the Spells ๐
Not entirely sure what you mean
In fact, they have unique name , its just to short for show it but i will work for have something else to show spell
Then you should consider making the text smaller or the objects wider. You can also put ... at the end of the name if it's too long.
name: The great spell of Water
display: The great spell o...
I explained
I think i will remove the name and only display an image but if player place his mouse on it, he will see the name
Yeah, that's a better idea
For now, i just try to use and setup animation
Good luck!
I want to stop bullets from bouncing enemies
Bouncing OFF enemies, or making the enemies themselves bounce
Assuming the latter, it would depend on how movement occurs.
You could make the enemies kinematic,
or add a larger trigger area around the enemy and detect then destroy the bullets before they actually collide,
Or disable collisions between the enemy and bullet layers and use spatial queries instead
Just depends on what you want
You want trigger Colliders. This way, the bullets are going to go thru the enemies, but it shouldn't matter, since in this case, I assume, they are meant to be destroyed immediately when the collision appears.
Bouncing OFF enemies
Ok, then destroy it when you collide
OnCollisionEnter
I tried to do that, but it doesn't detect collisions
Do one of the two objects have a dynamic rigidbody?
Do both have colliders, and NEITHER are a trigger?
No, I did not
If you want to use OnCollisionEnter, then neither can be a trigger
If you want to use OnTriggerEnter then exactly one must be a trigger
so @gray mural sayed that
He said that as a suggestion for using OnTriggerEnter
Which would mean there are no physical collisions.
Is that what you want? Then go with OnTriggerEnter
If you want them to physically collide, and just not bounce, then OnCollisionEnter but destroy the bullet
It is entirely up to you
For some reason I completely forgot that they should simply destroy them. In this case no trigger is needed, as there is no time for the bounce to happen
So I don't think there are any other options you might require. Or do you, perhaps, want to not destroy, but simply stop your bullet and make it fall when the collision happens?
the last 3 words of the message tells you
sorry, kinda bad at unity Ihave no idea
sorry if i'm dumb
you are trying to use an Animator without assigning an Avatar
alr ty
You're not dumb. Just learning
ty man :)
so sorry, but how would I resolve it?
sorry for the bother
Somewhere you have an Animator component attached to a gameobject. You need to supply it with an Avatar
is there any way to find the gameobject without going through all assets? thanks
you can search for
t:Animator
you are looking for something like this
Thanks for the help :)
so sorry, but still nothing
It links to a script I think?
presumeably you only checked the scene objects. You need to check any prefabs in your project that you instantiate as well
Okay thanks
Clicking once on the message may highlight the source of the error in the hierarchy
links to a script
I go to the line [996]
once, not twice
double clicking opens your code editor
(and you should do it while the game is running)
if that doesn't work, search for t:animator or t:mrider while the game is running
btw it highlights the player
okay, so the player probably has an Animator or MRider component on it
Hi, I am currently writing a movement script and I am trying to implement movement on a slope. I got everythign working except for that I always get stuck on the transition from a flat piece of ground to a slope. How do I fix this?
If I sprint at the slope or jump on it it works fine but the transition while walking doesn't work.
In the screenshots you can see how I detect if I am on the ground and if I am on a slope as well as a Screenshot from inside the engine with my scene.
Consider a spherecast instead of ray.
Everything should be the same except the method name
That will widen the area you query, letting you hit that leading edge of your player
Or do multiple rayasts
I will look into that, thank you very much
that doesn't really seem to address the main problem
I agree that you should use a spherecast rather than a raycast to determine if you contact the ground
but what do you mean by the transition while walking not working
i presume OnSlope doesn't become true and they get stuck
I assume the mean the common issue of when you start to go up the slope, the player lifts up, and you no longer register as grounded. (Or OnSlope in this case, as fen said)
But yes, that was an assumption
Fen is right, OnSlope doesnt change to true initially
Is there a way to display the sphereCast? Like Debug.DrawRay but for the sphere?
Welll... there is Gizmos.DrawSphere
Or Debug.DrawLine and approximate what you need of the sphere
yes: the physics debugger!
Is it a good idea normally to use NativeArrays?
I don't see any real reason to use them if I'm not passing them to Jobs
I'm using it in BatchRendererGroup
window > analysis > physics debugger; you can turn on queries
note that only newer versions of unity have the query visualizer, iirc
More specifically, to keep a local copy of the instance data
I practically have to use the functionality to write a bigger type into a collection meant for a smaller type
you'll have to show me what you're doing
I have it fortunately and boy is it helpful
Thank you so much
Oh dang. That is awesome.
This is the place where it really clashes if I try to use a normal array
Span<PackedMatrix> objectToWorldMatrices = new Span<PackedMatrix>((byte*)localDataBuffer.GetUnsafePtr() + byteAddressObjectToWorld, maxInstances);
Span<PackedMatrix> worldToObjectMatrices = new Span<PackedMatrix>((byte*)localDataBuffer.GetUnsafePtr() + byteAddressWorldToObject, maxInstances);
Span<Color> colors = new Span<Color>((byte*)localDataBuffer.GetUnsafePtr() + byteAddressColors, maxInstances);
Uh, lemme just show the whole code
oh, yes, you absolutely have to use a NativeArray when packing different kinds of data into a buffer
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.
This is my script
Uh, after I randomly swapped the native array for an array, just pretend localDataBuffer is still a NativeArray
yeah the thing is ev en I print on screen i cant have a tracking history because the textmeshpro can only have 1 text
IT WORKS, you guys are legends! thank you again, Spherecast was the way to go and the physics debug is the best thing i have ever found!
Unity crashed with stack overflow errors tho
Although... To be fair pretty sure it's cus I forgot to dispose and ended up creating a memory leak... haha...
Still, would this NativeArray be eating up the stack?
It wasn't recursion... Maybe it's when you start playmode they allocate a lot of stuff on the stack
this is something in the UI breaking
Honestly... It was probably a side effect
Not the first time errors say this but it's that
The crashes stopped as soon I added localDataBuffer.Dispose() in OnDestroy
That's why I'm guessing that the heap was very much packed and then enter playmode made it crash
-
- What's the problem in testing it in the editor?
-
- What's the problem in printing the full stack trace for the method on the screen?
Does a visual effect clean up itself when all particles lifetime has passed or do I need to clean it up myself?
you mean by adding a text mesh pro?
What are you referring to?
to print in the build
I see, I'm sorry, I meant "in the editor"
in the editor i cant test the resolutions bug cause it doesnt affect
in the editor theres no resolutions
It still won't give you an error when trying to assign it
If you're talking about partical systems, there's a setting for that
If "CleanUp" means destroy
You can also set it to Callback, never used it but I think that it should allow you to make something execute when all particles expire
i know but whats the point on doing that if i cant try if it works?
You'll still be able to see the PlayerPrefs' values. It's just that the resolution set won't be visible
i have a plugin to check in real time the player pref values
So what's the problem then?
resolution changing randomly to max or 640x480 for no reason when switching scenes, and is not even consitent
is just random
VFX graph particles, not the particle system
I want to make sure compute shaders aren't still running in the background after all the particles have disappeared
Seems kinda absurd if they still do, it's a tool meant to be highly performant. Although I can't be sure about this one
Uh, although, in my case at least it ain't uncommon to still keep the memory to avoid re-allocating everytime
But that things are still running is another story
I noticed in the scene if I play the visual effect without reinitializing it some attributes of the particles existed as if they had been going along this whole time, but that might just be a matter of the system knowing when they original were spawned and lerping the values from there, not updating while they had disappeared
I'm working on a game that involves both the player controlling a car as well as AI cars. I got a somewhat decent physics system working on my player car controller, but I know I'd like to make changes to the car physics in the future. AI cars should use the same physics. So naturally, I'd like the physics to be split into its own script rather than having a lot of duplicated code between the player controller and AI controller scripts. I'm struggling with 2 possible approaches. The first is making a base class "CarController" that the PlayerCarController and AICarController classes can inherit from. The other approach is to just make a separate CarPhysics script that can be called by the player car controller and AI car controller (for example, they could call "ApplyAcceleration", which would be movement input from the player and whatever input the AI decides for the AI). I tried the inheritance approach but it got kind of weird when considering the 2 separate inputs, does the CarPhysics separate script sound like it could possibly be better?
if you know all the things you would need to interact with and how, a separate script is cleaner imo
separate components, where the input from the player and the input from the AI can be added along side the component that actually applies the input
Just wanna mention that a separate script can also cause you a bunch of hassle, if the two was meant to be more complexly coupled or stuff
I've had this struggle with my Health before- IHealth interface or Health component?
So you think the car physics separate script is cleaner then? For more context, yeah the current base car controller script is just applying a lot of forces (such as suspension, natural deceleration) each fixed update. The only 3 things it really needs input from an outside entity (player or AI) is acceleration, turning, and manual deceleration. So I'd imagine I can just call these from the controllers like "ApplyAcceleration, ApplyTurning, etc"
Yeah, if those are the only things you'd be good keeping them separate
I forgot what the deal was but it got pretty annoying when the health was a separate component from the creatures, so... Sometimes separate components ain't really optimal
Ok, thanks for the help that does seem better, was mostly finding inheritance examples online so just wasn't sure. I guess it does depend on the situation, I usually use health as a separate component but I also haven't made anything all that complicated yet to be fair
Inheritance gives a hell of a lot of control imo, drawback is how messy the inspector can become and if you don't watch out how messy the script can become too
its always case by case, I usually go with separate script for reading inputs, and common scripts that could "handle" that input. than AI can have its scripts to provide its own input
Yeah I think inheritance would work here if there weren't so many implemented physics functions in the parent class. But there's just so much going on in the base script that the child classes never override that it seems like it should just be its own script
I won't be able to answer this without seeing your code. You should be able to solve this by printing the variables?
cant send you the code right now, my partner is trying to figure it out and he has the script. Btw meanwhile, do you know how to work with tiles without getting lag? If i try to paint in the scene i have an insane amount of lag but if i use prefab i get this import load everytime i paint something
No, no idea
Haven't used the tiles much
hello, im having an issue with accessing animation rigging components through scripts
i have the package installed in my editor
try regenerating project files and restart visual studio
nope
doesnt work
are you using asmdefs in your project
yep
oh
damn
you are right
it works now, thanks
Okay so im super confused, if I can have a default virtual function in an interface, add it to a class, but not call the default implementation, what else would they be used for?
you can cast your object to this interface type and call it than
Hi, I'm currently trying to wrap my head around DOTS & ECS.
I'm prototyping a tower defense game so I've got lots of entities that will share the same data (waypoints along a path from their spawn point all the way to the "exit"). I've tried making use of ISharedComponentData to store the waypoint positions (as a list of float3) but I couldn't manage (having a float3[] inside a ISharedComponentData didn't sit right for some reasons). Many paths can exist so all entities might not follow the same path.
So I've just encountered BlobAsset and they seem to be one of the right tools to use in this case but I'm wondering about how to actually use them, should I:
- Store a
BlobAssetReference(in aISharedComponentData) that's created at bake time and Unity will figure that a lot of other entities share the same content hence use the same pointer thanks to some BlobAssetStore magic ? - Store a
BlobAssetReference(in aISharedComponentData) from a map ofBlobAssetReferencethat's created atGameObjectConversiontime ? - Do something else that's more idiomatic of
BlobAssetand DOTS ?
Noted, thanks
Thank you, feels ind of weird to do it this way.
don't treat interfaces and default interface methods as inheritance and it won't feel weird to do that at all
I mean why let me do it then real talk
this is the code:
https://hastebin.com/share/olupagaxop.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
only problem is when I close the game windowed
just because you can treat it like that, doesn't mean you should. interfaces are not a substitute for multiple inheritance and should not be treated as such. interfaces are to provide a common interface to interacting with different objects
Then, after opening again I only get 3 resolutions and without the HZ
Okay let me propose a question then, If i want to have multiple objects to be buyable, but they can be different objects, and some require different implementations of the same method, whats the best way to implement them.
there is no "best way", and what you've described can be achieved in a number of ways, none of which require you to try and use interfaces as a sort of multiple inheritance situation
For some reason this code doesn't return anything when on my mobile device, is there something I may be missing?
are you sure it's being given valid data on your phone at all?
yeah the correct data gets passed
but nothing comes out for some reason
works perfectly fine on desktop though :/
Should I use scriptable objects or whats the best way for a modular gun system? with fireRate, damage, rounds, other characteristics, etc.
scriptable objects are useful for storing data as an asset
useful for storing parts of a weapon, perhaps
but the actual definition of the weapon can be a plain old C# object
Is there any way too do something in an audio so it sounds like if it was far far away?
or behind a door
there are audio filter components you can add to the same object as an audio source
a reverb filter plus a low-pass filter can give you a "muffled" effect
I make my SO hold my stats in a POCO for the base stats, this way i only copy the poco to add modifiers and stats to
whats SO and POCO
ScriptableObject and Plain Old C# Object
I got this but still not feeling completely nice
does anyone know why i cant change an objects parent and position/rotation on the same frame?
AnchorPoint.transform.up = plcCon.ConnectionPoint[1].TransformDirection(Vector3.up);
placing.transform.SetParent(AnchorPoint.transform);
AnchorPoint.transform.up = -conPoint.up;
this code works but it it doesnt rotate the child and parent. it only rotates the parent
same code but without the messy variable names:
A.up = B.TransformDirection(Vector3.up)
C.SetParent(A)
A.transform.up = -D.up
A's position/rotation is correct but C's is not
basically im just rotating it, adding a child and rotating it again
for some reason unity doesn't seem to rotate the child
nvm, I'm dumb
i forgot to delete a line i added like 3 days ago ._.
You'll want to use a cusatom reverb preset and mess with the dry level
The dry level is how much of the un-processed audio is kept (measured in decibels, so 0 is 100% strength)
huh? wdym
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : ScriptableObject
{
}
a "POCO" being a "plain old C# object"
a class that isn't inheriting from MonoBehaviour, ScriptableObject, etc.
You store the weapon definition as a Weapon. If you want to make a weapon preset, you make a WeaponPreset scriptable object that stores a Weapon
class WeaponData : ScriptableObject
class WeponStats etc.
all in one script?
no just showing for brevity
You can only define one MonoBehaviour or ScriptableObject per script file.
You can wedge other classes in, if you want
this work?
using UnityEngine;
[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class Weapon : ScriptableObject
{
public string weaponName;
public int maxAmmo;
public float fireRate;
public float reloadTime;
public GameObject weaponPrefab;
public AudioClip fireSound;
public AudioClip reloadSound;
}```
I would do it a bit different
How so?
Seperation of concerns
public class Weapon : MonoBehaviour
{
public WeaponData WeaponData;
}
public class WeaponData : ScriptableObject
{
public WeaponStats Stats;
//other sutff like
//AudioClip FireSoundl;
//etc
}
public struct WeaponStats
{
public float FireRate;
public int MaxAmmo;
//etc.
}
So, why would I separate the WeaponStats in two diferent categories?
makes senese
I'd rearrange it a bit
well no reason to mix Stats data , with AudioClips or other assets
just personal preference
using UnityEngine;
public class Weapon : MonoBehaviour
{
public WeaponData WeaponData;
}
[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class WeaponData : ScriptableObject
{
public string weaponName;
public int maxAmmo;
public float fireRate;
public float reloadTime;
public GameObject weaponPrefab;
public AudioClip fireSound;
public AudioClip reloadSound;
}```
so that WeaponData is also a plain old C# object; you can create SOs to hold a WeaponData as a "preset", as well as other types to hold stuff like muzzle flash definitions
easier to copy the whole WeaponStats to modify it on the instance
public class MuzzleFlash : ScriptableObject {
public ParticleSystem particleSystemPrefab;
}
(you might add more fields later)
hm interestin
so does this work?
yeah it works fine
yeah ik
However, if you want to be able to modify the weapon as you play the game, you probably don't want to shove all of the stats into a scriptable object
if two places use the same scriptable object (e.g. you have two of the same weapon type), modifying one will wind up modifying the other
use ScriptableObjects to hold definitions of things, like a kind of muzzle flash
Whereโs the channel to get help
indeed , thats why I made poco on it to copy basestats and then modify
id:browse pick one
How could I go about doing this.
I don't use pocos much
you just make a class
mark it [System.Serializable] so you can serialize it in the inspector
Huh
should I just slap the weapon.cs on the gunHolder or the gun?
i don't know what a "gun holder" is here
do note I usually make the weaponStats struct so it can just be copied values
Weapon represents the actual weapon in your game world.
ik, but I have a parent to the gun model called gun holder
but I can just put it on the gun GameObject
well the model shouldn't be your root object anyway
why not
because graphics should always be separated from logic
looks fine
yeah
now how should I access the weaponData properties properly in the weapon.cs script
so yeah Lets say I made weaponstats a struct,
I can just do ```cs
public class Weapon : MonoBehaviour
{
public WeaponData WeaponData;
public WeaponStats currentStats;
private void OnEnable()
{
if (WeaponData != null)
{
currentStats = WeaponData.Stats;
}
}
public void IncreaseFireRate(float amount)
{
currentStats.FireRate += amount;
}
}```
on the weapon for example
wheres the struct
on the SO
public struct WeaponStats
{
public float FireRate;
public int MaxAmmo;
//etc.
}```
but yeah you would make them System.Serialiazable so they can be modified in inspector
hold stats, audioclip sounds, model, etc
where is the class WeaponStats supposed to be initialized?
it makes it so you can just swap an SO and your weapon is now different
in WeaponData?
you do it in the inspector
put it in a different file, doesn't matter
like I said this is fine, is just more annoyance to copy individual fields than a whole struct
if you plan on modifying those stats that is
if not then yeah don't worry about it
hello everyone, i need some help building my unity project. I need to make a build with il2cpp for windows. Right now i only have access to a linux machine, and i can't find a way to build for windows using il2cpp backend. I already tried using a virtual machine but the build gets stuck. Does anybody know a way to build for windows from another platform?
Unity Cloud offers a service like that
https://build.cloud.unity3d.com/landing/
Unity Developer Dashboard
using UnityEngine;
[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class WeaponData : ScriptableObject
{
public string weaponName;
public int maxAmmo;
public float fireRate;
public float reloadTime;
public GameObject weaponPrefab;
public AudioClip fireSound;
public AudioClip reloadSound;
}
public struct WeaponStats
{
public WeaponData weaponData;
}``` this look correct?
or do I have it backwards
I think I do
idek
well its confusing because you have the same variables in each one
try putting maxAmmo fireRate and reloadTime in WeaponStats, then declare WeaponStats inside WeaponData
[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class WeaponData : ScriptableObject
{
public WeaponStats WeaponStats;
public GameObject weaponPrefab;
public AudioClip fireSound;
public AudioClip reloadSound;
}
[Serializable]
public struct WeaponStats
{
public string weaponName;
public int maxAmmo;
public float fireRate;
public float reloadTime;
}```
using UnityEngine;
[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class WeaponData : ScriptableObject
{
public WeaponStats weaponStats;
}
public struct WeaponStats
{
public string weaponName;
public int maxAmmo;
public float fireRate;
public float reloadTime;
public GameObject weaponPrefab;
public AudioClip fireSound;
public AudioClip reloadSound;
}```
oh
wait whats the point of separating them
ideally you only want value types inside struct
they are both useful to the gun
I would only seperate if you plan on modifying the stats
oh bc the fireSound doesn't change?
the prefab and sounds are not "stats"
still going to modify them tho
they can be considered part of the data for the weapon, but they are not the weapon's statistics
so idk what the point of separating them are
also is better to not put references inside structs because they get passed by value
okay thx โค๏ธ
but im modifying them both
so how does this not work?
What if I am changing the gunModel because I am adding a silencer to it. but only for one person.
thats not something you would ever change on a SO
if you change it on a SO it will change it for everyone who has that same SO
what if I am changing the sound for a silencer? @rigid island
look for example, If i want to change fireRate Im only doing it on this weapon.
Im not changing it for everyone that has this weapon
exactly whats wrong with changing the audio due to a silencer then>?
it all depends on whether you want the change to persist on disk or not. if it has to persist in the same scene only, make a routine that changes the model on the MonoBehavior
if you change it on the SO it will change it for everyone
not if you do it on the copy version tho
on the currentStats
Reference types work differently
also, you can use Instantiate on scriptable objects to get a copy, and then reassign the new one
thats why i dont mix them in struct as much
ah okay
they cannot be copied, only bring the original with you
getting a bit lost in the weeds here
using System;
using UnityEngine;
[CreateAssetMenu(fileName = "NewWeapon", menuName = "Weapon")]
public class WeaponData : ScriptableObject
{
public WeaponStats WeaponStats;
public GameObject weaponPrefab;
public AudioClip fireSound;
public AudioClip reloadSound;
}
[Serializable]
public struct WeaponStats
{
public string weaponName;
public int maxAmmo;
public float fireRate;
public float reloadTime;
}``` there
yes tbh to me this makes more sense
if you want to allow upgardes to have effects on the weapon's visuals and sounds, you need to make it so that each "modification" to a weapon gets a chance to modify the weapon's vfx/sfx
for example, each modification could be allowed to attach extra models to the weapon
ah alr
a "silencer" modification would add models to each barrel on the weapon
can I just go ahead and put whatever for these?
pretty much
and, when you fire it, the silencer would override the audio clip that gets used
it's a non-trivial problem
I did something like this during a game jam once
WeaponName might have to stay in WeaponData
since you're not gonna be changing that
modifiers could also prepend or append text, yes
That would be another field
"silenced armor-piercing glockinator"
make yourself defaults and only ever read from them
yes, you would not modify anything on this one, only a copy of them
gothcu
so I could change these ones tho
alr
yes that REGEX preventing spam
ah okay
btw @heady iris do you know why in this code:
https://hastebin.com/share/olupagaxop.csharp
when i restart the game while being on windowed resolution changes for some reason
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Can you download unity on a school chromebook or chromeOS just wondering
I do not believe so
I mean, you could probably download the file. But not install it
A concern might be the size/capacity of your hard drive - some chrome books have limited eMMC memory.
I have several scripts that work in tandem to make a very good VR bolt-action handler. I updated some things and it no longer works, for some unseen reason
They are also executed in a specific order:
(1) GoTo: tracks one local rotation axis and any/all of the position axis to another object. In this case, rotates toward my hand along only the local z axis, and also moves only along the local z axis toward my hand.
(2) TransformLimiter: flag enum to allow limiting of x/y/z rotation and x/y/z position. clamps the local rotation/position for each enabled axis to a low & high number in the inspector
(3) BoltAction: dumbed down, changes the relevant (in this case onl z rot and z pos) low and high clamp ranges when the bolt is in a certain area.
when TransformLimiter is disabled, GoTo accurately follows my hand along the z rotational axis. no issues with tracking and there is no unaccounted for offset. Its local rotation in the inspector also falls within the range limited by TransformLimiter
when TransformLimiter is enabled, the object snaps to its high range value and no longer rotates at all.
the BoltAction script seems to have no effect at all.
below is relevant portions of code
GoTo
//rotation
. . . . .
if (transformConditions.HasFlag(toggles.RotZ))
{
newAngle.z = Mathf.Rad2Deg * Mathf.Atan2(relative.x, relative.y) * -1;
from.localEulerAngles = new Vector3(from.localEulerAngles.x, from.localEulerAngles.y, newAngle.z);
}```
TransformLimiter
//rot
. . . . .
if (limits.HasFlag(Toggles.RotZ))
{
limitedTransform.localEulerAngles = new Vector3(limitedTransform.localEulerAngles.x, limitedTransform.localEulerAngles.y, Mathf.Clamp(limitedTransform.localEulerAngles.z, zRotationLimit.x, zRotationLimit.y));
}```
oh btw originalReference has the exact same starting transform as the object with these scripts
I'm trying to change the color of my played particle system with a script to a green color. But when it plays, it's gray. If I change my particle system's color using the inspector, 51, 204, and 40 is the correct colors for green. What am I doing wrong?
public void PlayParticle()
{
ParticleSystem currentParticle = Instantiate(gas, foo.transform);
var main = currentParticle.main;
Color color = new(51, 204, 40);
main.startColor = color;
currentParticle.Play();
}
Color expect values between 0f and 1f https://docs.unity3d.com/ScriptReference/Color.html
Oh.. that's unexpected.
I was trying to set it to the RGB values that go up to 255. Is there a different method I can use?
The Color32 constructor would take values between 0 and 255
Color color = new Color32(...)
Hmmm maybe I won't be able to use Color32.
It's basically a color range right?
Look through the docs. It returns a Color but it's something more. There are properties at the bottom of the page that you might be interested in.
This contains two Gradients, and returns a Color based on ParticleSystem.MinMaxGradient.mode. Depending on the mode, this may return the value randomized.
I decided to go back to Color and divide by 255 to get the same number, but one that Unity accepts, and it works.
Color newColor = new Color(51f/255f, 204f/255f, 40f/255f);
main.startColor = newColor;
I have a lot to learn about particle systems though, and colors are clearly a staple of them, so I'll look through the article you sent.
Pretty sure you could implicitly acquire a Color from a Color32
Thanks for helping me get to the solution Dalphat.
Hey guys I need some help, I have a 2D rigged character with an animation. I want to create a character editor at runtime, where I can swap out the sprites for the head, torso, legs etc. But when I change the sprite of the head it is no longer attached to the rig and the character becomes unusable. I do have 'Auto Rebind' checked as well. Is thre something specific that I am missing?
But when I change the sprite of the head it is no longer attached to the rig and the character becomes unusable
Why?
Are you using skeletal animation?
Yes
Thank you, this does help. But it requires me to copy the rig and have the other skin also be rigged. At runtime I want to download sprites and then swap them out in the skeletal character.
Download from where?
Cloud storage
The users, the user could potentially upload their own sprites
If it's users, this doesn't seem possible because how do you expect the sprites to become rigged (weight painted etc)
Maybe if you have them author the sprites with Unity, rig them, and upload them as AssetBundles?
If it's just like, an image file, that doesn't contain enough info to do skeletal animation
I would have to do this at Run time I can't ask the users to get unity to edit and upload
Not sure where you expect to get the animation rigging data from then
The alternative here is to use spritesheets/multiple sprites without any deformation
I'm actually doing that right now. I wanted to see if there was a rigged character solution
Well someone has to rig it.
Either build a tool that lets your users do the rigging
Or build something with AI???
Is there a way to generate the geometry at runtime?
Maybe?
You'd have to dig through https://docs.unity3d.com/Packages/com.unity.2d.animation@10.1/api/UnityEngine.U2D.Animation.html
but again
I don't see how you could take an arbitrary user-provided image and know how to generate the geometry procedurally
The only feasible solution I can think of is training an AI to do it.
ok thank you I might have to try something else
solved: apparently, it doesn't like negative numbers as the low and high values. adding 360 to both inputs made it work flawlessly
I've some problem for a while now, maybe someone here can solve it:
I'm working on a simple input script using Input.GetAxis for horizontal and vertical movement in a 3D game. The player object moves with a Rigidbody based on this input.
Before actually moving the player object (using rb.velocity = ...), I'm saving the input vector to a list so I can "replay" the input later. This works fine: I can move normally and replay the input to replicate the same player movement.
The problem arises when the player object physically interacts with other Rigidbody objects in the scene (e.g., a new Cube object with a Rigidbody). Here's what happens:
When I push the cube around for a few seconds (like a soccer player dribbling a ball) and then replay the input, the playback behaves differently. The replayed player object ends up slightly off from the original position, losing the cube it was pushing, and finishes at a different location than expected.
Important to note that the playback itself does actually get the same result every time; I mean, I can replay it over and over and the results will be 100% consistent and identical, even with physics interaction.
Any ideas?
it might just be unavoidable floating point error if the playback you made is, at the base level, doing the exact same thing you do when you use input. weird issue
it could also be the execution order being slightly off now that i think about it
some things execute instantly and some on fixed update
so depending on your implementation it might be fractions of a frame off, but enough to cause a difference
ive had that issue come up so so many times making my vr game, things happen in between frames but it still affects the physics output
replay by exact coordinates, not by functionality of the physics system
could maybe record yourself a timeline and replay it as an animation clip
its possible using physics is necessary for scarlet
there might be ways you can fake it though if you want the effects of physics on things
just lerp it all, it'll probably be fine
im saying the rigidbody might be necessary
like to push stuff around, bounce, slide, whatever
Yes physics are crucial for my purpose, but how is the physics interactions are always the same when replaying the same playback over and over?
unity's physics engine is pretty good, so most of the time if you have the exact same starting conditions, youll get close to the exact same ending conditions
But If order of execution might be the problem, why doesnt it affects this case?
well because the order would always be the same
I'd try messing with the detection modes maybe
could be that messing with the second rigidbody then does a sweep for other rigidbodies
quick question, are you recording the input on update or fixed update?
Input recording on update and movement itself (changing the rigidbody) happens on fixedupadate
ok try adding to the input recording list on fixed update instead
that way it is recorded at the same rate its later re-played
Yea thats what happen atm
unfortunately i told myself id go to bed almost an hour ago and here i am still so im heading out, hope you find the help u need
Lol np , good night
Yep i tried all the modes, no success
My assumption is that moving the rigidbody probably takes in consideration of others once you move it. Perhaps something to do with interpolation settings and whatnot.
But I'm just kinda throwing out guesses here
I just know that rigidbody vs rigidbody calcs require a bit more setup, and it's not as deterministic as saying bouncing a ball across a static environment.
Hm, but i dont think that it still explains why replaying the same record over and over is still deterministic
True. I'm surprised you do get accurate results by replaying it with that single rigidbody.
After all, the different only lays between whether the player object get the input directly from the input system or from the list
hi guys, so basically im using Animation to move car, does anyone knows why when I play on editor suddenly the object attached got un-attached?
void Start()
{
animator = GetComponent<Animator>();
}
public void Something()
{
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);
if (stateInfo.normalizedTime >= 1f)
{
gameplayTwo.SetActive(false);
checkpointTele.SetActive(true);
}
}```
How accurate is timeline with playing audio clips? I have the playable director on DSP time and have been using the timeline to sequence a rhythm games interactions, but the timing feels slightly inconsistent across plays
I'm not sure if there's an issue with the playable director itself, or if it's something with my own code
Post a clip
I will get home later and I will post hete
Is there anyway to check where a script is being used in unity?
Nothing in this code has anything to do with unattaching anything, please share a video and more context
okay let me record it
In Visual Studio, you should be able to see above the class name which assets are referencing that script, I believe you can also right-click the script in Unity and "Select Dependencies"
Their question was wether it was used in Unity. I assume this is related to if the script is being used as a component of a gameobject and not referenced by other scripts
You should be able to search for a component using the search feature, though I forgot the specific term to search for
Otherwise put a log in its awake method like this:
Debug.Log("Awake", gameObject);
You can then press it and navigate to the component
There are more ways but these are the easier ones from the top of my head
And is there anyway to check if a method is being used in unity? Like by a keyframe event or in the inspector in a button with onClick
or something like that
Ah, I thought the visual studio reference would tell you if its referenced on for example, a prefab, its likely a component of that prefab, though I guess it might not tell you which scriptable objects in your project use that script or more fine details
When using SHIFT + F12 on visual studio it doesnt detect StateBehaviourScripts?
do unity limit FPS on UI for android build, if yes how can i change the limit
Hello. I am new to using the ScriptableObject behavior for my scripts, but I thought I'd try again by making a set of collectible objects in my game that would go to an inventory system. Right now it's in the early stages, but I ran into an error I'm not sure how to fix:
https://gdl.space/oqafuzamox.cs
When the object is collected, for now I just want it to say in the debug log what item was collected. However, it gives this error:
ArgumentException: GetComponent requires that the requested component 'Weapons' derives from MonoBehaviour or Component or is an interface.
UnityEngine.Component.GetComponent[T] () (at <55fbbbd17b724c15b6abe8c1a3e3289c>:0)
Player.CheckTile (UnityEngine.Vector3 target, UnityEngine.Vector3 raycastStart) (at Assets/Scripts/Player.cs:116)
Player.Update () (at Assets/Scripts/Player.cs:27)
I think I understand what its saying, that the Weapons SO component attached to the game object isnt derived from monobehavior or component, but I have no idea how to change the code or SO so that it works
ScriptableObjects are not components, and cannot be fetched with GetComponent
In your screenshot the component is called "Collectible" @wooden pawn
Got it
That makes a lot of sense
Too many things I'm learning at once
My brain starts to combine everything
public string collectedItemName { get; private set; }
collectedItem = hit.collider.GetComponent<Collectible>().Weapon.WeaponName;
is this the best way to do it?
then I can use Player.collectedItem in the debug log message
public void GetItem()
{
Player p = GameObject.FindWithTag("Player").GetComponent<Player>();
Debug.Log("Attempted to grab item: " + p.collectedItemName + "\n" + "With attached value: " + p.collectedItemValue);
weapons.Add(p.collectedItemName, p.collectedItemValue);
}
Trying to add the key and value to a dictionary called "weapons", but it keeps giving a null reference exception.
The debug log works, saying the items name and value, but it gives an error on the dictionary add line
weapons is null
public Dictionary<string, float> weaponsDict;
this is at the top of the script(i changed the name to weaponsDict to be more precise)
Yes, that's null. You haven't put anything in the variable
No, that tries to add items into the dictionary but the dictionary itself doesn't exist
public Dictionary<string, float> weaponsDict = new();
Oh right I forgot I had to do that
Does "new()" work with other things youre initializing, like Vector3s and stuff
I've always written it out as = new Dictionary<> etc
You can omit the type in the latest Unity versions, yes
Thank you
Hi everyone, i was updating my project on two different devices, and my player moves at different speeds corresponding to devices, while the values are the same. got any ideas as to why?
would it be related to screen resolution?
Depends on your movement !code, post it here.
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ 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 guess is that you don't account for FPS.