#💻┃code-beginner
1 messages · Page 41 of 1
Prove that the function exists
Inventory is not an easy thing to dive into in the beginning 🙂 they vary in complexities but tomorrow Im at my main pc, I can show you a few examples I have from old tut
RemoveItem and AddItem are from the equipmentpanel script, which i reference, which in turn means it should work
IsFull
Where is IsFull
thanks, yeah i attempted making one when i first began and just gave up but that was probably 3 months ago, ive gotten much better since
Read the error
IsFull doesn't exist
Prove it
{
return items.Count >= itemSlots.Length;
}```
using System.Collections.Generic;
using UnityEngine;
using System;
public class Inventory : MonoBehaviour
{
[SerializeField] List<Item> items;
[SerializeField] Transform itemsParent;
[SerializeField] ItemSlot[] itemSlots;
public event Action<Item> OnItemRightClickedEvent;
private void Awake()
{
for (int i = 0; i < itemSlots.Length; i++)
{
itemSlots[i].OnRightClickEvent += OnItemRightClickedEvent;
}
}
private void OnValidate()
{
if (itemsParent != null)
itemSlots = itemsParent.GetComponentsInChildren<ItemSlot>();
RefreshUI();
}
private void RefreshUI()
{
int i = 0;
for (; i < items.Count && i < itemSlots.Length; i++)
{
itemSlots[i].Item = items[i];
}
for (; i < itemSlots.Length; i++)
{
itemSlots[i].Item = null;
}
}
public bool AddItem(Item item)
{
if (IsFull())
return false;
items.Add(item);
RefreshUI();
return true;
}
public bool RemoveItem(Item item)
{
if (items.Remove(item))
{
RefreshUI();
return true;
}
return false;
}
public bool IsFull()
{
return items.Count >= itemSlots.Length;
}
}```
It could be a local function for all I know
This is a different class

InventoryManager is what you're trying to call it on
mbmb
I'm explaining your problem
You are calling the function on the wrong object
Show where you call the function
{
if (Inventory.RemoveItem(item))
{
EquippableItem previousItem;
if (EquipmentPanel.AddItem(item, out previousItem))
{
if (previousItem != null)
{
Inventory.AddItem(previousItem);
}
}
else
{
Inventory.AddItem(item);
}
}
}
public void Unequip(EquippableItem item)
{
if (!Inventory.IsFull() && EquipmentPanel.RemoveItem(item))
{
Inventory.AddItem(item);
}
}``` in the inventory manager script
So what type is "Inventory" here?
Show that variable definition
Make sure you saved all of your scripts
Because the error is clearly saying you tried to call it on an InventoryManager
What is the filename and line number of the error
fixed that and now its js saying this Inventory.OnItemRightClickedEvent += Equip;
those went away
mb for ts im tired asffff
your method has the wrong type
Your delegate expects Item but your function has EquippableItem
okay, what would you reccomend to fix that?
doesnt ide autofill that for u after the +=
Make another function that takes Item as the param and tries to cast it to EquippableItem and if so calls that function
bold of you to assume they have a working iDE

mine litteraly doesnt work after configuring it the way the guide told me too
pisses me off
bro this configuration thing is biggest meme for me personally cause I legit never configured it myself only set default editor in settings thing
configuring wont work while you have compiler error
it just comes configured what yall do
ive had vs code for like a year before unity so idfk
aa idk abt vs code
they have a new extension. makes the process quick
giga stupid question but if ive got Color32 property and now I want to check if its set to anything at all what do I do? check if its not 0,0,0,0 ? why != default doesnt work
Wdym "set to anything at all"?
unless they have some override for == that wont work cause of floats
I have class with Color32 property and constructor with optional param to set Color32 to something so if I dont use that param to set the color
what is it its not null
its a struct
It's a struct they can't be null
cant be null
yea thats the problem
If you want it nullable use a nullable type

E.g. Color32?
Sorry, busy day. I will look into this one!
This is the error I get with this script I made now
[UdonSharp] Source C# script on TextureSwapper (UdonSharp.UdonSharpProgramAsset) is null
UnityEngine.Debug:LogError (object,UnityEngine.Object)
UdonSharp.UdonSharpUtils:LogError (object,UnityEngine.Object) (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/UdonSharpUtils.cs:329)
UdonSharp.Compiler.UdonSharpCompilerV1:Compile (UdonSharp.Compiler.UdonSharpCompileOptions) (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/Compiler/UdonSharpCompilerV1.cs:285)
UdonSharp.UdonSharpProgramAsset:CompileAllCsPrograms (bool,bool) (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/UdonSharpProgramAsset.cs:295)
UdonSharpEditor.UdonSharpGUI:DrawUtilities (UdonSharp.UdonSharpProgramAsset) (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/Editors/UdonSharpGUI.cs:393)
UdonSharp.UdonSharpProgramAsset:DrawProgramSourceGUI (VRC.Udon.UdonBehaviour,bool&) (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/UdonSharpProgramAsset.cs:204)
UdonSharp.UdonSharpProgramAssetEditor:OnInspectorGUI () (at Packages/com.vrchat.worlds/Integrations/UdonSharp/Editor/UdonSharpProgramAsset.cs:601)
UnityEngine.GUIUtility:ProcessEvent (int,intptr)
At first when the initial line is dragged, the travelling balls, move perfectly even after changing the endPoints of the line. Now when another line is created, the balls move perfectly as I want. The issue arises when I try to move the first line after the 2nd line is created. Then as shown in video, the balls don't move along the 2lines.
I have 2 scripts as follows:
Can someone tell me what the issue is?
not sure on this one , it says error is with TextureSwapper but your class is called TextureSwapper1
I never used Udon sharp
Yeah, i made a copy of it to see if it was just a import error
!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.
how to reload a scene without using loadscene twice?
What??
It was an import error, but now its telling me Assets/UdonSharp/UtilityScripts/TextureSwapper1.cs(31,5): Nested type declarations are not currently supported by U#
Is there something I did wrong in the code?
use the pastesites for your codes
Alright wait, thanks
Use it once? I don't understand the question
it is inconvenient for people to help with discord turning your codes into file
dont i have to unload the first one first?
Don't make copies of asset files that's just asking for trouble
No
Unless you're using additive loading
loading bar 
oh
Anyway that'd involve a second scene (loading scene)
It wasn't updating with my edits when saving so I copied and saved to it. fixed import issue with "Null" but now it gives me not supported
i can just reload the same scene and nothing bad will hapen?
Why are you making edits?
havent tried it before, lemesi
To fix issues it said i had
99% chance you don't need to edit the framework to fix your issue
but why
its telling me 31,5 is not supported, I had it as
public enum Texture OR Material
not
public enum Texture_OR_Material
yeah u cant have spaces in the variable name
but it still says not supported
The first one is nonsense
Sounds like your udonsharp install is outdated or corrupted
Delete it and reinstall from the source and make sure you follow their instructions on unity version etc
LeftWallController.cs https://pastebin.com/XC5Xvnm7
TravellingBalls.cs https://pastebin.com/jE8sfLwE
Definitely due to this weirdness
hit.collider.gameObject.name.Split('-');
if (nameParts.Length == 2 && (nameParts[0] == "LeftBall" || nameParts[0] == "RightBall"))
AssignGameObjects(int.Parse(nameParts[1]));```
This kind of GameObject name shenanigans are a bad idea
And GameObject.Find is a bad idea
that looks unholy af
Use real object references
I have tried this out. This simply assigns sphere1, sphere2 endpoints of the same line. I know the coding style is bad. But for now I just want to make it work. Then I will optimize it
Put a script on your lines that has references to its spheres directly.
Interact with it through that script
What you're doing is causing your problems
It's not about optimisation
This isn't a way to do things
what do I do exactly?
use script to differentiate it and store data
I'm sorry, can you pls elaborate & simplify
It isn't that straight forward, but you should try to encapsulate your logic better
one of the code smells I see is having class-scoped variables for these objects in your controller
Your wall controller script is way too aware of what's going on inside the line
why does the controller need to track these objects, when it should just be finding them when you click on them. It should only hold onto them for as long as they are being dragged, and nothing more.
And it's causing issues
hey, I'm trying to make a pong clone in order to practice, and I'm wondering if I really should make two different player objects, or if I should make a parent object
which one would be better here?
two player objects
prefably 1 prefab
oh, so I should make a prefab, with the two player objects inside it?
no just a prefab of the player
then clone it and use it as player 2
Reinstalled 0.20.3 and still get the same not supported error
oh alr, thanks!
this way when you apply changes into one prefab (eg changing movespeed and stuff/ change visual) you can easily just apply to the other player
Hey, i am in the process of making a top-down(2D) tower defense game, and I have started with a tilemap for the ground and I want the specific tile to highlight when the mouse hovers on that tile, any tips on how to implement it ?
use a tilemap that is above the your current one and make a sprite for highlight sprite, switch the tile sprite on that tilemap above based on mouse pos
by above i mean it has bigger number for **order in layer ** in tilemap renderer component
if i have a monobehaviour that inherits another, say Eagle inherits bird, and bird and eagle both have private void Awake(), would they both be called or would only the eagle's awake be called
You should mark the base class's Awake as virtual, and then when you override it in the subclass you should call base.Awake().
Only the most derived class will have Awake called otherwise
alright
Isn't that an outdated version?
Requirements
i managed to make it work, thanks
https://hastebin.com/share/egugawesek.csharp
im having a bit of trouble with code i want to alter. i want to change my nodeui so it shows the tower/turrets stats at lvl2. i was able to make it so it changes for each specific turret. but i am struggling to do it for the upgraded variants. im sure i have added all relevant code files. any help is appreciated. thank you
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
towerStats.text = target.turrentBlueprint.towerStat;```
when you change your tower, does the blueprint not change?
you should update the tower when you upgrade it with the new blueprint, or make a whole new tower that includes the blueprint,
my movement screen struggles to move on any surface that isnt completely and utterly flat 💀
how do i fix this
what
theres the script
Ah, may need to rasterize the navmesh with a smaller voxel size
and increase the height of which the agent can walk over
oh sorry im sleepy, I'm thinking you're doing a navmesh cause you got a minimap ;)
Unfortunately I've not used unity's rb and physics together much
is it bad practice to use gameObject.SendMessage() to manually call OnTriggerEnter?
OnTriggerEnter is automatically called by the engine. you don't manually call it . . .
you can't do that
also, why must it be OnTriggerEnter?
cant you make your own function to call?
also, using SendMessage is bad practice . . .
why come?
Using the SendMessage and BroadcastMessage functions is a bad convention in that they are very resource-intensive and difficult to debug. An alternative to these is calling methods directly via a reference or using a delegate/event setup
SendMessage has to go through every script, look for a method with the same name using string comparison (slower), and call it. The GetComponent finds the script through type comparison (faster) and calls the method directly. GetComponent can also be cached, which is the fastest alternative . . .
also, i believe SendMessage does not report errors when the method is incorrectly spelled since it uses strings . . .
the only reason you're facing difficulty now is lack of understanding of the available tools. i'd second learning to use a delegate/event setup, aka the Observer pattern
no clue what sendmessage is but it throws errors on the editor when I create new meshes and I wish it would shush
but also wondering about this
yes but's that's a bitch in a half with my code base. Basically i have 8 different weapons in my game, that inherent from a "weaponBaseClass". the base class has a "shoot()" function that sends out the rayCast that checks what im hitting. the issue comes that 5 of my 8 weapons need to override this function to do their own special thing (like shotguns using a For() statement for it's pellet spread) and my explosive based weapons not using raycasts at all.) so if i wanted to add a new check for the "TargetTrigger" class, i need to go through 6 different scripts to add in the new check
no no
i have like 6 different fucking scripts to show, man
jeez louise
okay
i got you, hold on
how do you expect anyone to help if we don't know what you're talking about? it's hard based on your description of:
so if i wanted to add a new check for the "TargetTrigger" class, i need to go through 6 different scripts to add in the new check . . .
i got you, gimme a sec
this is my base Shoot() function
i know what i can do is just add in a new if statement for my TargetTrigger class like i have for Enemy and regular Target
but the issue is that i have 5 other weapons in my game that do not use the base Shoot() function, they have their own Shoot() functions
i dont know what to make of this
whatta mean
that's my shoot function
okay
what's the issue with it?
i can see it uses raycast
so what's the problem you're facing now?
it's that i have 5 other weapons (and therefore scripts) that use different shoot functions
so i would need to add the new if() statement for my new TargetTrigger class for all of them
and the issue if, what if i want to add another class that needs to be shot at and do something different?
what can't they do that you want them to do?
and how about you show some of those shoot functions? so we can see how they're different
and again, show your TargetTrigger class? it seems really important since you keep mentioning it
public class TargetTrigger : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
Debug.Log("Taget hit!");
Destroy(gameObject);
}
}
This is all it does atm
i wanted my weapons' rayCast to collide with it
but now i know that rayCasts do not set off OnTriggerEnter
okay, do other Shoot functions do something that would trigger this OnTriggerEnter?
No, they wouldn't either
can you show those other Shoot functions please?
so why did you set up this OnTriggerEnter then?
okay
i now know they do not
is this TargetTrigger on the object that you're hitting with the raycast?
gimme just a quick segundo
yes
okay. i'll wait on those Shoot functions
so from what I can understand, the base Shoot function does these
- spawns a bullet trail,
- if you hit an enemy, the enemy takes damage.
- if you hit a Target, the target takes damage.
- if you hit a rigidbody, it applies a force
- and it instantiates an impact effect.
is the TargetTrigger a Target or Enemy?
or is it a separate thing that doesnt take damage, just destroys itself
https://gdl.space/qulufamoze.cs
https://gdl.space/xirewuwuce.cs
https://gdl.space/kisetatulu.cs
the shotgun and explosive scripts are used accross 2 weapons, respectively. These all override the base classe Shoot() function
i can see some duplicate code between the base and the overriding Shoot functions
TargetTrigger is gonna be a new class that just destroys itself on hit
yea
why wasnt the duplicate code just part of the base Shoot
then you just call base.Shoot() in the overriding Shoot functions
for the sniper, its because of how my recoil system works
then you wouldnt have to add the if statement in all the Shoot functions, since it seems like it should only be in the base Shoot
for the explosive weapons, they don't use Raycasts, they use an overlap sphere
I see
for the shotguns i need loop over the ray case sent out for each pellet, as they have a spread
my issue is that, i need to add a Target Trigger check to all of them, which would be easy, but tedious, esp because what if i want to add more Triggers to be shot at that do different things, like spawn enemies?
what im thinking of doing is to just add a generic case
basically, if im not hitting an Enemy or Target, then to just call the OnHit() function of whatever i hit
i'm afraid i dont have the time or experience to properly suggest a refactor
sounds like an idea
i have to go now. all the best
thanks, i didn't mean to come off as mad btw more so just exasperated i guess 
Could also derive like a projectile class and just have shoot handle how they come out of the weapon
raycast is an odd one out though
Hi did anyone ever got this issue? When saving TerrainLayer assets, it looks pretty normal (texture appears on the layer.asset). But whenever I click on the play button, all my layer's textures are being reset. The layers still keeps other settings
still can be a projectile though and do a conditional check
i think what im gonna do is just make TargetTrigger a parent class with a virtual function, and if i need to do something unique other than just move a door/barrier, then i can just override it with a child class
so i still need to add in the if check to all my scripts, but it'll be the last thing i need to add for this project
i don't think im gonna add anymore shootables that aren't triggers
Recoil and stuff here can also just be another function on all your guns which you can make virtual
such that you'd have a bunch of other virtual methods that shoot calls
Stuff like your explode is just a condition for when a projectile hits, so it doesn't necessarily need to be tied to a specific weapon, but rather you can have an onhit trigger method for projectiles that will call these extra methods.
Sniper hits -> look through onhit triggers -> Explode();
Shotgun pellet hits -> look through onhit triggers -> Explode();
I'd just chop up a lot of your functionality if you want to make it reusable and stick it into their own methods.
true
Because technically all weapons can have multiple projectiles, but the ones you want you can just change that 1 to a 5 and so on
but im much too lazy to rewrite my weapons code so im just gonna do my idea
hey, anyone knows how to make a piece of code repeat for specific time? I tried smth but it doesnt seem to work (unity editor has frozen)
wait wat
i don't follow this
if I create a Monster class for which the only purpose is to store values for my monster for my Combat class
is there a point in making the Monster class values private? or can I just leave them public, since I need them in the Combat class?
share the script you tried
Where ever you register a hit, or if you have like some onDestroy method for projectiles, I was suggesting to tie some functionality to that if sphere casting seems odd for a shoot function.
uh do i just paste it here or is it gonna flood the chat
use 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.
oh i think i see what you're saying but as i said, i think for my purposes it's easier to just make TargetTrigger a parent class and if i need a trigger to do something else, i cna just override it
private void Dash()
{
if (Input.GetButtonDown("Dash"))
{
if (canDash == true)
{
rigid.gravityScale = 0f;
StartCoroutine(doDash());
while(canDash == true)
{
if (sprite.flipX == false)
{
rigid.velocity = new Vector2(10, 0);
} else if (sprite.flipX == true)
{
rigid.velocity = new Vector2(-10, 0);
}
}
}
}
}
private IEnumerator doDash()
{
yield return new WaitForSeconds(2f);
canDash = false;
rigid.gravityScale = 3f;
}
you're starting the coroutine and while the coroutine is waiting for 2 seconds, you go into the while loop. that while loop never ends, so unity crashes.
at least, it doesnt end before unity crashes
no clue where that is in your code, but this idea means you can basically do a raycast + spherecaster
add the while loop inside the coroutine
and check for certain time lapsed
oh i see
idk if that works for my game, since the nade launcher and RPG basically just instantiates their respective projectile, and when that projectile hits something or runs out of it's life time, then it calls Explode()
what do you want raycasted that then needs ontrigger?
what? sorry i don;t think i understand what your asking fully. all my ballisitic guns use a raycast to see what im hitting. what i wanted to do is to have that RayCast or overlapSphere set off the OnTriggerEnter of my targetTrigger and then activate whatever i wanted activated. I would find this useful as i don't have to add new if() checks in my weapons scripts everytime i make a new shootable
but, i think im fine with adding one more if() check that just calls a targetTrigger, and if i need to add a new shootable that does something else other than just open a door (like say, turn off the lights and spawns in a few enemies) i can just make it a child of targetTrigger with an overrided OnHit() function
Not seeing any of this code... but if this is like some class where you're comparing layers/targets, you'd just give your weapon types an enum that points to a layer mask that they can hit.
wat
i don't think we're on the right page, thjat's my fault, im awful at explaining things
im not comparing any layers or targets, what i wanted is to just have the raycast that comes from my weapons scripts to call OnTriggerEnter() on my targetTrigger class
But i learned that raycasts do not call or set off OnTriggerEnter for colliders that they hit
as far as if statements go, I'd just use them even if they don't apply to the current weapon. Usually the idea is to take advantage of virtual methods, but if you can't minimize it to that, it's not that big of a deal.
no, im saying that the if statement i have to add needs to be added to all my weapons, not just a few
but anyways, i already implemented my idea and it seems to work, so i think i am vibin'
Ah, alright. Anyway I'mma sleep. If you do want to refactor it all out throw me all of it so I could get an idea. But if you're fine with it all, just go with it ;p
yeah, i appreciate your thoughts none the less! it still something i will keep in mind for my future projects
that will hopefully be ALOT cleaner than this project, lol
move the camera also not a code question
When i scale up the size of my screen all my gameobjects scale up with it but my text my buttons any canvas element doesnt scale up in size and doesnt move to the correct position of the scaled up screen
not a code question #2
I have a Monster class with several fields
Their only purpose is to be used in the Combat class
Is there a point to make them private? Or can I just leave them public so I can get & set them easily from the Combat script?
I think most ppl here use Visual Studio instead, at least it's easier to set up with Unity
Something is going to eventually have to access those properties if it's not part of the hierarchy. Though, there's other ways you can go about it instead of giving other classes the full reference access, such as subscribing to methods or passing around interfaces of this monster class but only with the properties you want accessed.
c++ has like the friend keyword, but I don't think that's a concept in c#
it's literally a class I just made to reference in my combat script
I have a MonsterSO that I use in the editor and then it just moves all the values I need in combat to Monster
I've never made a codebase big enough to actually see why you use private, I understand the concept, but haven't experienced it
doing monster.health just seemed better than monsterHealth, since there's quite a few monster variables
It seems cleaner
Does anyone know how I can make a code for getting on and off the car?
Can you help me how to create a code to get on and off a car?
Yeah, that's totally fine. You can also expand on the property fields which are basically getter/setter methods.
no, we're not here to write code for you
we can help you debug your code if you have any
Yeah looks like Visual Studio.
#854851968446365696 should have instructions on how to install Visual Studio iirc
i thought you were going to bed, lol
Once I can get this damn code to compile
yeah that's what I've been doing for my other more complicated classes
but it seems so pointless for this one - and I really don't completely understand what the use of private is lol (like I said, I know the theory, but that's not the same as actually understanding how to use it)
like how is a private with a get & set different from just public?
unless you have to apply logic in those get & set methods, which I won't ever have to do for Monster
it's just a concept which doesn't necessarily need to be enforced, but it's a good habit to have like adding comments
I don't even know how to create code anymore...
I haven't scheduled anything for 1 month now.
to prevent your teammembers or whoever else touched your code in the future and decides they can access something they shouldn't and break your code
And since I forget things quickly
there's tons of guides for free on YT or more advanced stuff on Udemy and similar sites
lots of youtubers who offer courses as well
But it is paid and I don't have a fifth
like I said, there is a lot of free content as well
Did u try learning C# first? 
Private get set is just private I think? It's still a thing cause you can expand on a property field of logic.
Coding is largely a problem solving thing. Imagine doing puzzles but the rules aren't explained to you.
There's a pretty good reason (for me) why i use protected, internal, or private. They exist to answer the question of "Am i supposed to fiddle with that from here?"
They also stop flooding intelisense suggestions when i don't need to which i like.
Getter and setter break it down more by having their own security. Normally, get; private set; is common since the class wants to set something from that field but not any other classes outside but still need it to be accessible.
Another example using getter and private setter is this [field: SerializeField] public var Value { get; private set; }. Since you can't do serializefield with a readonly, this is as close you can get. The Value isn't meant to be set by anything other than in the inspector, only referenced by other classes so you want to make the set part private. There's no higher security than private so the class that owns it can still set it though. 
By default, try making them private and if you know that they need to be accessible outside the class, make them public, see how that goes. 
yeah that's pretty much what I've been doing
Accelerate and everything but it doesn't turn
!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.
can anyone explain switch statements to me and how they can be utilised
What don't you understand about them? https://learn.unity.com/tutorial/switch-statements
does anyone know why the enemy isnt moving towards the player? its like its being constantly teleported back, as shown in the video when i disable the animator i can move the enemy, pls help i dont know whats happening been stuck on this for ages
i havent watched the video yet but are you forcing position with your animations
wdum
you're moving the "ant" gameobject, right
well yeah, the script is attached to the ant and im just increasing its speed when player goes near it in the players direction
Are the values set correctly in the Enemy inspector?
so the problem is definitely animation if when you disable the animator it moves alright
is your animation overriding the "ant" gameobjects position?
yeah the problem is animation i know i just dont know what exactly
yeah
Yeah, that's true, I usually set up the animated object as a child so it doesn't override the rigidibody
is this the only way to fix it? and what would i have to do to do it
Yeah the issue is that your animation is on the root object, and there are position keyframes so it applies the position of the animation
Usually, the object you animate is a child of the object you move
damn, would that be hard to change?
You can probably just make a new gameobject, make "Ant" a child of it and put all your enemy logic on that parent
No, just create an empty parent, and move everything (rigidbody, collider, scripts) except the Animator onto it
You might need to reference the Animator again from the movment script, since it changed
okay thanks will do
so remove all of them from the child object aswel?
Yes, you can use the options menu of the components (three dots icon top-right) to copy and paste the components values
yup doing that
Click > Copy Component on old object, Click > Paste Component As New on new object
thanks everyone that helped it worked, i was literally having such a hard time figuring that out!
Best way of having instant acceleration on a player movement script for 3D.
hi i just finished my top down movement code for animating both walk and idle but when i stop moving it stop on idle_down animation not on the idle animation that corespond with the axis it was previous on
Can't say much without seeing the animator.
Fun tip, you can write that log
Debug.Log(animator.GetFloat("PosX") + ", " + animator.GetFloat("PosY"))
as
Debug.Log((animator.GetFloat("PosX"), animator.GetFloat("PosY")) and it will print out with the comma
Tuples are handy
Not that it really matters, just a little quality-of-life thing I started using recently
does anyone understand why the instantiate brackets don't have a space for size?
like i can control where it spawns and in what rotation, why can't i add a place for what size I want it to spawn at
because scale is not relevant to all objects you can instantiate
so how do i control the size of stuff that I spawn
apply it to the instantiated object
oh i guess that would work for me since I always want it to be in random sizes
but what if I only wanted the random sizes to exist on the instantiated objects, and wanted to keep the original prefab without random sizes
do i just duplicate and use them differently
that is why I said 'instantiated object'
Space? 
im reading the instantiate documentation and there's no area for scale
object instantiatedObject = Instantiate(prefab...);
i already have the code with the position and rotation filled in but the documentation only shows I can add "parent" and "instantiateInWorldSpace" which don't seem to be what i'm looking for
just apply position on the next line of code homie
object instantiatedObject = Instantiate(prefab...);
instantiatedObject.localScale = new Vector3(...);
ok I think I wrote it correctly but it doesn't recognize "instantiatedObject"
show code
how to I reference to it
the object's prefab is called "Baddie"
so far it spawned from right to left on a random Y position, so I wanted to add scale randomness
and how does your instantiate look like this?
object instantiatedObject = Instantiate(prefab...);
idk how it looks
is my instantiate not on this screenshot?
lmao Im sorry i started today
yes, and it looks nothing like mine
needs to be GameObject
@calm osprey also post code correctly
!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.
// Your code herepublic class BaddieSpawner : MonoBehaviour
{
public GameObject Baddie;
public float spawnRate = 2;
private float timer = 0;
public float heightOffset = 7;
public float scaleOffset = 2;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer = timer + Time.deltaTime;
}
else
{
float smallestSizeX = transform.localScale.x - scaleOffset;
float biggestSizeX = transform.localScale.x + scaleOffset;
float smallestSizeY = transform.localScale.y - scaleOffset;
float biggestSizeY = transform.localScale.y + scaleOffset;
float lowestPoint = transform.position.y - heightOffset;
float highestPoint = transform.position.y + heightOffset;
Instantiate(Baddie, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
instantiatedObject.localScale = new Vector3(Random.Range(smallestSizeX, biggestSizeX), Random.Range(smallestSizeY, biggestSizeY));
timer = 0;
}
}
so you wrote
Instantiate(Baddie, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
I wrote
object instantiatedObject = Instantiate(...);
See the difference?
Needs to be GameObject, no?
my instantiate is for the position tho
yes, but I'm trying not to spoonfeed
Probably worth using var in examples, not object
your trying to do two things
spawn the object
change the object size*
two steps
but you need to have an object on which to apply the scale do you not?
so I need to create another gameObject for the instantiated objects?
and then I can reference it in the "instantiatedObject" line to make it scale?
because the position code works
You need to use the instance returned from the Instantiate function if you intend to modify the instance https://unity.huh.how/references/references-to-prefabs
Guys I have my custom cursor set as you can see in image and it works when i click play in Unity but when I build the game its normal mouse cursor...do I need to have some kind of script for it to work when game is built or?
Hey, anyone know if a disabled unity script can still utilize static variables of a class?
Disabling it means only that some Unity functions (Start, Update, FixedUpdate etc.) will not get called automatically
Other than that, the code will work normally
yes -- there's no "magic"
you can still call methods on the object and use fields from the object
even destroying a unity object doesn't stop you from doing that (you'll just get errors if you try to use Unity methods/properties)
So public static variables should still be able to be accessed. Huh. I'm getting a strange "null" in place where a game object should be in a grid.
Its like a string typed null too which just adds more to my confusion. lol.
is it better to use properties instead of fields everytime we want to access them from other scripts?
its from a very large chunk of code. I don't expect to find a solution this way but if you want a shot... here:
Hey most people seems to use this code to move a player in a 2D platformer game :
void Update()
{
playerRigidbody.velocity = new Vector2(inputX * walkingSpeed, playerRigidbody.velocity.y);
}
public void Move(InputAction.CallbackContext context)
{
inputX = context.ReadValue<Vector2>().x;
}
But I can't use this because it doesn't seem to work well with SpringJoints2D. When my player is connected to another object with a SpringJoint2D, the physics break. I don't know how to fix that.
Is your player always connected to a spring joint?
No physics work fine but when I enable the spring joint it's doing weird things. And I tried without the movement code and it works fine
please share it in a paste site -- !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.
https://github.com/MerlinVR/UdonSharp/releases
0.20.3 is the latest they have
so, what is the problem?
On the static public variable Grid. Once a piece becomes gravity disabled. Instead of the piece appearing on the grid i get a value of "null" from the debuger.
And thats with the quotes.
you set grid elements to null in several places
Yes. But that should only be if tags match and have an appropriate top and bottom
In the debugger does a new null appear as "null" ?
Guys this is what my gameplay looks like. Along with the character control script https://hatebin.com/wcpmpalgah.
The jumping feels so off. I tried changing jump force, then damping then gravity. It just does not feel like jumping. I want it to jump in an arc but it just goes up and down almost in a straight line.
also, which line is logging this unexpected null? There are several places you log in your code.
that drag is pretty massive
Once a piece falls upon one of the same Type so i would imagine line 47
I notice the drag in the video
You don't have to imagine. Double click the log entry.
also, your paste is off by at least one line (you put ```cs on the first line). You'll need to copy the line that you're talking about.
Its not the debug log entry its the actual Debugger. (I'd take a screenshot if it wasn't imposible to do so with the pop out windows in studio.)
I increase the move speed then the jump is just like i want but then I move too fast.
I removed UdonSharp from the script and it works now, but my drop down isn't inciting a show/hide selection base still.
Oh! that kinda makes sense. But its sprite is still rendered.
Again, look into lowering the drag
Thats what makes you fall down vertically
Because at that point the jump force is totally drag'd and you only get gravity
Hmm
Okay I made the drag 1. I get slightly higher air time
You can always change the drag depending on if youre walking or jumping too
but again. Is there any way to like make it feel like im actually leaping forward
Less y force, more xz force
so increase move speed and decrease jump force?
I mean make the X and Z of the jump force larger
Actually idk even how your jumping works
Do you even add horizontal force when jumping? Or just vertical/y?
I got the script here
Ah you posted code
you're constantly setting your X and Z velocity
so you won't be able to make a jump that "leaps forward" without changing that
Yep. You could handle the movement differently when you are in a jumping/falling state
For example, with AddForce instead of the current rb.velocity =...
Do you need sharp turns in the air?
No not in the air.
@swift crag ! Thank you! I figured it out! After destroying an intermidiary piece for ice cream, destroying part of it made it appear as "null" on the grid. Thanks for your help!
That'll do it -- destroyed unity objects will compare equal to null
I said use addforce when jumping/falling
So in the air
Yeah
Make a variable that tracks if you are on the ground or not
Maybe you already got that
I have a ground check object
If grounded, use rb.velocity.
If not, use addforce
(Bonus: read about 'coyote time')
coyote time helps me jump after missing the platform a bit though no?
How are they related
Yeah that
Just asking dont get me wrong.
It might become relevant, but forget it for now
All right thanks a lot.
Sorry but does anyone have an idea on how to solve my problem ? I can't find anything
.
you're going to need to give us more context than "the physics breka"
You just linked a page from 2021 lol. You're supposed to install from the VCC now
What does "show/hide selection base" mean?
if texture is selected void the material swap selection
It's not in VCC
It's VRChat SDK base
Without, then with the movement code
Ah, it might be a conflict with 0.20.3 and VRCBase?
I'll remove 0.20.3
0.20.3 is ancient, you should not be using it
This overrides the velocity so any force added by the joint will be canceled
float runSpeed = 10f;
Requirements
why do u have to type f at end when it is already declared to be of float type?
In this case you don't have to
You dont have to really
If it was 'var' then yes
It just needs some clue that it is a float
so how does this help?
But normally it's because 0.5 for example is a double in C#, so you have to use f to make it a float.
limit the number of decimals?
Yeah that's what I thought, but is there another way to do the movements ? Maybe adding to the existing velocity but I would need to make a speed cap or something because that would increase the velocity indefinitely otherwise ?
In your example it doesn't help at all
got that
5 is an int literal which is implicitly converted to float
Double cannot be implicitly converted to float
anyone have any idea why the last 2 events on my animation arent triggering?
You must use a float literal instead, hence the f
Yeah I would do it with AddForce
Limiting the velocity is easy, either just directly clamp it (Vector3.ClampMagnitude with rb.velocity) or add a canceling force
Are you transitioning out of the animation before they come?
but why would i want to convert it to float when double can hold more decimal values that float?
Ok thanks I'll look into that
the only 2 transitions from this animation have exit times which have 0s transition offset
so i dont think they should
Vector2 playerVelocity = new Vector2(moveInput.x, 0f);
I don't know why you want to do anything. You made a float variable, I'm just answering your question
in this case how does the f help here?
Because Vector2 uses floats not doubles
why would you need a double as opposed to a float? just curious
like i dont think this transition should be interrupting before the events run right?
Here again it does nothing, 0 would become a float too.
If it was 0.0 then it would nag about it being a double
the last frames in the animation are running too
Looks like it transitions before the end
is that what the little grey end segment is?
I see
that should be the problem then
thank you very much praetor
yep that solved it : )
Um, how do you make it, so the whole map is dark, and the units have a light within a radius of them? I can't find a tutorial.
I heard it's called fog of war but I don't want to memorize the pathway and making it lit up too
Just the units and everything that is within a radius of it
Like this
and without memorizing pathway
Because doubles take up literally twice the space. Using doubles instead of floats for vectors would instantly double the memory requirements of your game for basically no real benefit
Why did you put a comma?
Also you can't use a field as the size like that
You cannot use a field to initialize another field. Create that array inside a function instead
Not in the initializer
cuz ill add other stuff, but that isnt error as when i add anotehr value it still had the same thing
That's not how array literals work
Values go in {}, check some examples
Also as mentioned above you can't use the field in it in the field initializer
It would have to go in Awake
= new int[] { minTime, maxTime };
If you put it in the square brackets, it denotes the length of the array, which is not what you want
anyone 😞
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
Maybe if the contract is smart enough it'll be able to find your missing capslock key
can a raycast be shaped more like a cone for an enemy field of view?
No, a ray is a laser, it has no shape.
You can use an overlap sphere to determine what is within a certain radius of the player, then filter them out based on angle from the players forward direction.
I think the best way to do this would be to use an OverlapCircle (or sphere if 3d) and then check if the object is within some angle range of the center of the "cone"
okay. how would i check if the player is within a angle of ths circle overlap?
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapCircle.html
Or use OverlapSphere in 3D.
To determine the angle between the players forward direction and the direction to the object you're checking.
arrays lists etc we aint got no tables 
thanks 🙂
Use a 2d array, or the DataTable class I guess
https://learn.microsoft.com/en-us/dotnet/api/system.data.datatable?view=net-7.0
But I question whether you need a table for your use case. You could just make a struct or a POCO 🤷♂️
I'm trying to create a simulation
similar to those evolution simulation things but instead for economics
what would I need to use for this
Explain what kind of data you are trying to store.
So far you have said "How do I store multiple things?"
I don't think he knows that yet either
If you want to store many copies of something in order, use List<T>. If you want to associate keys with values, use Dictionary<K,V>.
I want to have a bunch of individuals that make decisions based on variables
so like
every index on the table has code run for it
okay, so you're going to have a list of actors
yes
so at the top level you'll have List<Actor>
and an Actor could have some variables in it for internal state
I have this error I got, after adding some packed gameobjects to the inspector of a script and deleting them from the scene, any way I can fix this without having to add them to the scene?
well, your Outline script is trying to modify the UVs of a mesh
but the mesh is not marked read/write
sounds like that's your problem
How do i fix that tho?
find the mesh in your Project folder and check "Read/Write Enabled" in the inspector
this keeps a copy of the mesh data in memory
instead of just uploading it to the GPU and forgetting about it
Okay thanks
what do you mean by "packed gameobjects"?
are you talking about prefabs?
Yeah, basically I have a script which spawns ore when you mine, but I dont want to have the ores in the scene already so i packed them into a prefab. And then added them to the script whioch spawns the ores
The error is unrelated to whether or not the objects are prefabs.
I know, it's just i want them to be prefabs since they have scripts etc. Btw ur read/write thingy worked
how do I get each actor to store multiple variables?
lists only let me assign one variable
well, Actor would be a whole class
public class Actor {
public float happiness;
public float timeSinceLastAction;
}
e.g.
If you want some actors to store data that other actors don't, you might want to make more classes that derive from Actor
Or you might want something composition-based, where actors, themselves, have a list of modules/components
ok so I have the class set up and I have a foreach set up
how do I access the variables inside of the class
it sounds like you need to do some introductory C# tutorials
these are really fundamental concepts
the C# docs have some nice tutorials, and Unity Learn has pathways for learning about scripting in the context of Unity
ok cool
is there a way to add collision to some of this tileset object?
fot the moment i added 2 2d box collider
but i dont think its the best idea because i need to do it every time
huh? put a tilemap collider
were and how?
on the tilemap obj. Add Component -> Tilemap Collider
thx, now i iwll see how it works, the for the help
but, how can i chose what is with a collider and what dosent have a collider?
put different tilemaps
one with collider and one without
oh,its the only way?
no other way that I know of 🤷♂️
you get used to it
how come ?its not diffcult at all.
how to create one?
thx!
My entire game I'm about to publish soon is based on that effect. If you need it, you can always dm me 🙂
well, this teach me how to create one in unity but not how to put the sprite that i want in the tile palette
just drag the sprite onto the palette..
yeah, but how do i create a image were i have all the sprite in a square (like all the other tileset)
are you talking about a tilemap?
spritesheet?
yes, the problem is that i dont have the sprite and i have tomake it as all the other tilesset
like this^^
export the whole sheet
remember the grid size (8x8?)
i dont have the sheet, were do i need to create it
just realissed my question may have been better asked in the cinemachine fourm so have removed it to there, sorry 😛
the screenshot you showed me
i need to create it
the image you showed me is a spritesheet, what do you mean create it
i found it on google
i have to create it with my sprite
i have a lot of sprites but not only 1 image
yes exactly
you slice. it
thats wht a sprite sheet is for
i dont remember that in the tutorial
true
set the spritemode to Multiple
then use sprite editor
click slice by grid size and do 8 x 8 if thats the size
ok
you did it wrong
no no i fixed
list.RemoveAt(index)
will that leave an empty index or will it actually delete the whole thing
Complete removal
Let's say I have two lists, one List<GameObject> and List<Collider2D>, and I want to sort both by the same Func<List<GameObject>, List<GameObject>>, but i want it to basically look into the collider2D's gameobject field/property for the sorting. Is there a clean way to define one method to do it all?
Custom wrapper?
I'm trying to use Linq's: x => x.OrderBy().ThenBy().ThenBy(), to define that function
maybe I could use an IComparer instead?
since I just have a few specific sorts I plan on doing a lot
maybe Comparison<GameObject>?
what exactly are your ordering by?
why not order them separately?
or do you want to merge them?
Does anyone know what this error means? Graphics.CopyTexture called for entire mipmaps with different memory size (source (RGBA8 UNorm) is 1024 bytes and destination (Alpha8 UNorm) is 256 bytes)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
not merge
I will likely need to define a function that:
- looks up each gameobject in a dictionary to get a different class
- compare field 1 of that other object
- if tie, compare field 2
- if tie, compare field 3
but idk the most performant way to do this
nor generic way to do this
are the sort fields all comparable?
Can you back up and explain what you're trying to do overall here?
i.e. are they all primitive values of comparable types?
your comparer needs to reference to something other than the two arguments, i will make a new comparer class implements IComparer<T>.....
I currently have a giant tree structure as a linked list. Specifically, it is one class that stores many trees (as in graphs). I have a List<GameObject>, which describes the root nodes of the tree, and Dictionary<GameObject, List<ITreeChild>>, which takes in one node and outputs all the children
ITreeChild is only implemented by monobehaviours, and ITreeChild has a .gameObject property. Not all nodes have a monobehaviour implementing a common interface.
why isn't it just a Dictionary<ITreeChild, List<ITreeChild>>
generally in a tree structure you treat all nodes pretty agnostically
because root nodes might not have an ITreeChild
perhaps that might be better
also a tree only generally has a single root
root is still tree node
the class is a collection of trees, yes
because every time I delete something in the middle, I want to define everything below it as its own separate tree, if that makes sense
right so that's so much easier when everything is just a node
that might be the better way
you cant distinguish root from "normal tree node" since each node can be the root of its subtree
like:
void DeleteNode(ITreeNode node) {
foreach (ITreeNode child in node.Children) {
child.parent = null;
roots.Add(child); // each child becomes its own tree
}
if (node.parent != null) node.parent.Children.Remove(node);
}``` as a quick pseudocode
delete node is a lot more involved, tbh. Because we need to know if we have children, and if we have children, move them all to be root nodes. And also remove the node to be deleted as a dependent of anything it is a dependent of.
that's exactly what my pseudocode above does
it covers all of that
this is relying on a .parent reference which might be a good idea too
I might be able to refactor. The thing I need to wrestle with is some objects allowing themselves to only be a child, to only be a parent, and some allow both
so what happens when you delete the parent node of a node that only allows itself to be a child?
do you just throw the child away?
anyway you can add:
public bool CanBeParent { get; }
public bool CanbeChild { get; }``` to the ITreeNode interface
and handle that as needed
in that scenario, we need to check if child has dependents. if child has no children of its own, delete from tree. Else, promote it to a root
that's part of what makes this structure kind of involved to manage
you need to stop treating these things as different things, they really are all the same
a root is just a node with no parent
healthBar:
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
public Image healthBar;
public float healthAmount = 100f;
void Update()
{
// Check for the "Return" key press
if (Input.GetKeyDown(KeyCode.Return))
{
TakeDamage(10); // Apply damage to the player's health when "Return" key is pressed
}
}
public void TakeDamage(float damage)
{
healthAmount -= damage;
healthAmount = Mathf.Clamp(healthAmount, 0, 100); // Ensure health doesn't go below 0
healthBar.fillAmount = healthAmount / 100f;
// You can remove the knockback signal to the player here
}
}
PlayerMovement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Animator animator;
public float StandStillSpeed = 0.1f;
public HealthBar healthBar; // Reference to the HealthBar script
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
// Get input for movement in the x and y axes.
float moveX = Input.GetAxis("Horizontal");
float moveY = Input.GetAxis("Vertical");
animator.SetFloat("SpeedX", moveX);
animator.SetFloat("SpeedY", moveY);
if (moveX > StandStillSpeed || -moveX > StandStillSpeed || moveY > StandStillSpeed || -moveY > StandStillSpeed)
{
animator.SetBool("Still", false);
}
else
{
animator.SetBool("Still", true);
}
// Calculate the movement vector.
Vector2 moveDirection = new Vector2(moveX, moveY).normalized;
// Apply the movement.
rb.velocity = moveDirection * moveSpeed;
}
private void OnTriggerEnter2D(Collider2D collider)
{
Debug.Log("TRIGGER");
}
}
!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.
Hm actually use a paste site, it's not small
I think my issue is that I coupled the node to an interface of a monobehaviour, instead of making a simple node class.
I see now that was a mistake.
Can I get some help with reading contents from a .txt file and displaying it in an inputfield?
fileIO
uh quick question, is this how a script is supposed to look? it looks grayed out so i assume something's wrong
Do you have compiler errors?
In the console
Or did you change the name of the script?
alright thanks
try to right click in project folder and do Reimport
unless you got compiler errors lol
did reimport not work?
where do i right click
where your assets are
what does the scene have to do with it lol
yeah ok i have no idea how unity works
all it was supposed to do was trigger a refresh of your scripts..
is the script still missing the label /header?
where is the script now
Wherever you had it before
had it inside a canvas
this? did you check it
Did you ever save that scene? Or did you create a different scene?
And the script would be in the project window
it doesnt auto save?
No
:teacher: Unity Learn
Over 750 hours of free live and on-demand learning content for all levels of experience!
start with Unity Essentials first
this is my script, when i change jumpForce the player doesnt jump any higher, but when i set the maxSpeed to higher values. the jump is also higher, any idea how to fix? thanks
is your rigidbody set to dynamic?
your AddForce stuff all needs to be moved to FixedUpdate except perhaps the jump (also Time.deltaTime should be removed)
let metry
i just had to check first
when i do that do i change the time delta time to fixed delta time or keep it the same?
maxspeed operates on all of velocity, not just the X
you remove it entirely
it's never correct to use deltaTime with AddForce
you will probably need to reduce your force values somewhat
where do you see that?
i would calculate jumpforce/jumpspeed by jump height
but yeah honestly not seeing anything in the code that would cause the described issue with jump height
in the fixed update
they're comparing velocity.x to the max speed
so move the jump into the fixedupdte too?
not the whole magnitude
maxspeed should not fuck with Y velocity at all
do you need help calculating jump force from jump height?
whats the difference between those
could this be the issue?if so how do i compre velocity.x.magnitude to maxSpeed
velocity.x
instead of magnitude
let metry
?
the line inside would have to be:
Vector3 velocity = rb.velocity;
velocity.x = maxSpeed;
rb.velocity = velocity;```
I just started coding on unity and it my code doesnt seem to work even though i followed a tutorial can anyone help, maybe my version of visual studio is old or something
This code should help you. You should stick it in at some point:
gravityStrength = -(2 * jumpHeight) / (jumpTimeToApex * jumpTimeToApex);
//Calculate the rigidbody's gravity scale (ie: gravity strength relative to unity's gravity value, see project settings/Physics2D). Assign this value to the rigidbody
gravityScale = gravityStrength / Physics2D.gravity.y;
// Calculate forces. impulse force is more like velocity. Use vf^2 = vi^2 + 2a*dist
jumpForce = Mathf.Sqrt(Mathf.Abs(gravityStrength * 2 * jumpHeight));```
you copied the code incorrectly
you have compile errors
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
like so?
okay thankyouu
yep
do i put it in fixedupdate? what does it do?
I just modified it. It should go into Awake, probably
okay ill insert it
the code I gave you takes in a desired jump height AND desired time (in seconds) until you hit the top of your jump arc. And it calculates for you the gravity scale you need to set on your RB and jump force you need to use to make it happen
changing jump height by playing with a value of force in units * units / s^2 is suck
i see, when i put the code it shows me the following
do i need to set those as variables or am i missing a directory
you need to define them
jumpTimeToApex and jumpHeight are both floats
these are the two numbers you serialize
gravity scale can be directly fed into rigidbody.gravity
jumpForce is the variable you're using, but you no longer need to define it in inspector. We are overwriting it to make the jump height and hangtime match
does this make sense?
kind of
and also, you need to use rigidbody.AddForce(jumpForce, ForceMode.Impulse)
Impulse mode applies all the force at once, as though we are changing velocity
i used impluse mode when writing the addforce
what do i do with the gravity strength
what is it
ok that's good
gravityStrength is a float. We don't need to store long term. We just want to hold it for that calculation because it is gravitational accelleration in units/s^2
alright
btw I updated this once. just making sure you have the line with gravity scale
make sense?
yes
so when i modifty the gravity scale according to it, it applies the time and jump height
the point of what I'm telling you is not to fix your problem, but to let you express how your jump works in terms of time and jump height, which are a lot more intuitive to work wit
yes i undersstand\
its just a different way to modify the jump
yeah, so what unity does is it has Physics2D.gravity, which is a vector for gravitational acceleration
rigidbody2D has a gravityScale property that multiplies gravity by that much for just that one rigidbody
your RigidBody2D basically always has rb.AddForce(rb.mass * rb.gravityScale * Physics2D.gravity) every single frame
the gravity scale and force are both calculated to hit both height/time requested.
anyway, I think I went overboard. good luck
i understand, the way it works is really cool, thanks for your help, probably gonna use that in other projects too
sure. I recommend brushing up on basic kinematic physics if you are rusty. It’s extremely useful
unity mostly tries to obey classical Newtonian physics
Hey, I have a problem where When I change scene from the options scene to the main menu scene, the brightness (its just a panel that changes its opacity) works, but when I go back to options, it gets darker.
sounds like broken 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.
📃 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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BrightnessManager : MonoBehaviour
{
public Slider slider;
public float sliderValue;
public Image panelBrillo;
// Start is called before the first frame update
void Start()
{
slider.value = PlayerPrefs.GetFloat("brillo", 0.5f);
panelBrillo.color = new Color(panelBrillo.color.r, panelBrillo.color.g, panelBrillo.color.b, slider.value);
}
//Update is called once per frame
void Update()
{
}
public void ChangeSlider(float valor)
{
sliderValue = valor;
PlayerPrefs.SetFloat("brillo", sliderValue);
panelBrillo.color = new Color(panelBrillo.color.r, panelBrillo.color.g, panelBrillo.color.b, slider.value);
}
}
got it
a slider changes the alpha value of the panel
from the video it looks like your slider starts changing something else
show the inspector for slider @alpine mortar
yes
InBetweenScenes
exactly
why
to change the brightness
also for this you would use post processing
but anyway the code you showed is not really important, the one you spawn BetweenScenes stuff is
wait a sec
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Persistent : MonoBehaviour
{
public GameObject panelBrightness;
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
private void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (scene.name == "MainMenu")
{
if (panelBrightness != null)
{
panelBrightness.SetActive(true);
}
}
}
}
I want to make a game where you can stack blocks (kinda like tetris) but as soon as they touch each other, they get "glued" together and don't move relative to each other I want to however have the tower tip over if it's unbalanced. How can I achieve this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChangeScenes : MonoBehaviour
{
public void Play()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 2);
}
public void Options()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
public void Quit()
{
Application.Quit();
Debug.Log("Player has quit the game");
}
public void BackToMainMenu()
{
SceneManager.LoadScene(0);
}
public GameObject OptionsMenu;
public void ActivateObject()
{
OptionsMenu.SetActive(false);
}
}
I ain't got more code
probably lots of hinges/joints
Wdym?
the issue is being caused by DDOL and switching scenes
Hallo, I'm trying to rotate an object and read it's x rotation value using transform.eulerAngles.x, but as it rotates from 0 to 360 degrees it's returning 0, 45, 90, 45, 0 for the 0-180 range and 360, 315, 270, 315, and 360 for the 180-360 range. can someone please help me find how to get it to be 0-360?
ddol?
DontDestroyOnLoad(gameObject);
ok
this whole system is flawed
just use post processing
i have no idea why you even added DontDestroyOnLoad(gameObject);
break one thing to fix another
yes just use Post Processing
I am sorry. I just don't know how these work in my context.
thanks man, I subscribed to you for the help, looking forward for some tutorials
you want to stick something to another thing?
I said use Joint/ possibly fixed joint
then youwoudl typically llook into it
or just ask about what ur confused on lol
For a proper glue I would probably try removing the RB of the new cube and parenting it to the stack
oh yeah true, it could all just be 1 rigidbody with several colliders
ty! its been a while but I need to resume it 🙂
you'll want this one. Color Adjustment
thanks
hello I have a little problem with my shooting system in my multiplayer, in fact when I'm shooting I made a script to detect the colision between the ennemy and the bullet and if it detect a hit, the ennemy return hit in the console, but as you can see when i'm shooting the ennemy it don't return every time hit and it's a big problem. I think i have this issue because the amo is too fast and it go threw the player because it so fast that between 2 positions it didnt even detect that he go threw the player. do you know how I can fix this issue without reducing the speed of my bullet?
the ennemy code that detect if it has been hit:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ennemie : MonoBehaviour
{
private float MyID;
private float X;
private float Y;
private float Z;
private float YRot;
void Start()
{
while (MyID==0)
{
MyID = GameObject.Find("Player").GetComponent<CLIENT>().NewID;
Debug.Log("PlayerID is : " + MyID);
}
}
void Update()
{
if (GameObject.Find("Player").GetComponent<CLIENT>().NewID==MyID)
{
X = GameObject.Find("Player").GetComponent<CLIENT>().XValue;
Y = GameObject.Find("Player").GetComponent<CLIENT>().YValue;
Z = GameObject.Find("Player").GetComponent<CLIENT>().ZValue;
YRot = GameObject.Find("Player").GetComponent<CLIENT>().YRot;
}
Vector3 CurrentPos = new Vector3(X, Y, Z);
transform.position = CurrentPos;
Vector3 CurrentRotation = new Vector3(0, YRot, 0);
transform.eulerAngles = CurrentRotation;
if (GameObject.Find("Player").GetComponent<CLIENT>().DisconectedID==MyID)
{
Destroy(gameObject);
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
Debug.Log("Hit");
}
}
}
(sorry for my terrible english)
oh...lordy..
please don't start with multiplayer when you're a beginner
this is beyond cursed GameObject.Find("Player").GetComponent<CLIENT>().XValue;
Can anyone check my code quickly because my playeris supposed to be able to jump around multiple times but it only jumps once and thats it
while (MyID==0)
{
MyID = GameObject.Find("Player").GetComponent<CLIENT>().NewID;
Debug.Log("PlayerID is : " + MyID);
}
😵💫
yeah dont use a shitty method to check for grounding xD
where do people get this code from
third time i've seen this curse
seriously damnnn😢 but i got it from a tutorial on youtube from the GameCodeLibrary
its a bad tutorial
In this part, we will take care that our player can only jump while he is standing on the ground.
Github repository:
https://github.com/codinginflow/2DPlatformerBeginner
🎓 Learn how to build a 2D game in Unity (beginner): https://www.youtube.com/playlist?list=PLrnPJCHvNZuCVTz6lvhR81nnaf1a-b67U
🎓 Learn how to build a 3D gam...
try this one
hey! I'm having an weird issue
when I change the speed in the unity editor, the speed actually changes in the game
but when the speed is changed during runtime by the code, it doesn't seem to be affected, any clue as to why?
this is my ball script:
public class BallScript : MonoBehaviour
{
public float speed;
public float tracker;
public Rigidbody2D myRigidBody;
public Vector3 startPosition;
public float increaseFactor = 1.5f;
// Start is called before the first frame update
void Start()
{
startPosition = transform.position;
Launch();
}
// Update is called once per frame
void Update()
{
}
public void Reset ()
{
myRigidBody.velocity = Vector2.zero;
transform.position = startPosition;
tracker = 0;
speed = 5;
Launch();
}
private void Launch()
{
float x = Random.Range(0,2) == 0 ? -1 : 1;
float y = Random.Range(0,2) == 0 ? -1 : 1;
myRigidBody.velocity = new Vector2 (speed * y, speed * x);
}
and this is the method im using to track and to increase and update the ball speed:
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Ball"))
{
ball.speed *= ball.increaseFactor;
Debug.Log("speed tracked!");
}
}
any clue how to fix this? 
big scripts should be posted with links
Maybe but in my case it work perfectly fine or at least it work XD
ehh
where the heck are you getting the ball reference from there? Seems like you're probably referencing the prefab instead of the ball you actually collided with
maybe before making a multiplayer optimize the amount of calls and garbage you may create
anyway you shouldn't modify public fields on other objects. Poor practice. Make a public method and call that
GameObject.Find is very slow and doing it inside Update is a curse @warm raptor
as to why your bullets are not hitting it could be many things, knowing how you even move the bullet is important
Yes but i need to update constantly and I dont find any other way to get those values from m'y main script that receive the values