Okay, so, I'm trying to make a game based around lasso movement, and I made this animation at the start. I was wondering if anyone had any suggestions on what I could do to animate the lasso throw so it looks natural and aims straight to where you need it to go. I feel like I need to use linerenderer somehow, but I'm not sure how to make the throw look natural. any suggestions?
#💻┃code-beginner
1 messages · Page 224 of 1
not a code question
Good point, what kind of a question is it? Where would I ask?
#🏃┃animation I would guess
2 points
What error?
Where is the declaration of loadout?
like huh
forgot the bottom
so you are using () instead of []
thanks
for some reason this is still null.....
https://hastebin.com/share/evixewetaj.csharp
can someone help me find out what the issue is?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I don't get why afterImageObjects[i] is null
I set a reference to it before it
and it just gets ignored
you initialize the arrays but you do not actually put anything into them. The default value for each entry will be null
i do put values into them.
and the best part is
objectID for every single array element is 6
literally all of them
i think _afterImageCount<afterImageObjects.Length
try to log it
afterImageObjects.Length=_afterImageCount * _objectsToBeAfterImaged.Length
_afterImageCount is a constant
so?
it should be still less than the length of array
why
I need 70 copies of 7 objects
so I need 70*7 slots
and its correct
wait
I think I know....
I think my values are being overwritten here
because i gets reset for every element....
yes
oh my fucking god
you are filling the same entries in the array each time, you do not take the value of j into account in your index calculation
yes
I just figured that out
so I need a separate increment
no, j * afterImageCount + i
row*whole column length +column
wdym no
oh
I mean
that works too technically
but imo its safer using a separate increment
could also do
for(int j = 0, int k=0; j < _objectsToBeAfterImaged.Length; j++) {
for(int i = 0; i < _afterImageCount; i++, k++)
and use k as the indexer
yeah true
but idk
I just used an int for now
another problem arises here
it can't find the characters
oh wait
im stupid
i dont set where they should be
.-.
it works!
but I still get these logs
Also I think you misunderstand the usage of the internal keyword
doesnt it mean that it can be accessed inside of the file?
well not file
no
but class
it can be accessed within derived
non derived and within the class
but it can't be accessed within a derived with a different assembly
no, internal means it can only be acessed within the compiled assembly
well yeah
is it not ok the way I use it?
the way you use it will have no effect as everything is compiled into the same assembly
what should I set the protection level to then
so its the bare minimum
no such access modifier (only allow anything in same file access it) in c#
at least not now in unity
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/file
use public, your class is already private to the enclosing class
alright, I was just told that you should use public as rarely as possible
of course, but in this case public is necessary
just cuz it works with internal
as you have coded it internal and public do the same thing. It's just that internal makes no sense
Different Shader, read the error message
like it works
i dont use any different shaders
the errors would disagree with you
public class FadeAway : MonoBehaviour
{
MeshRenderer _meshRenderer;
private float transparency;
// Start is called before the first frame update
void Awake()
{
_meshRenderer = GetComponent<MeshRenderer>();
}
private void OnEnable()
{
transparency = _meshRenderer.material.GetFloat("_Transparency");
}
// Update is called once per frame
void Update()
{
Material[] materialToFade = _meshRenderer.materials;
if (transparency > 0f)
{
foreach (Material mat in materialToFade)
{
mat.SetFloat("_Transparency", transparency);
}
transparency -= Time.deltaTime;
}
else
{
gameObject.SetActive(false);
foreach (Material mat in materialToFade)
{
mat.SetFloat("_Transparency", 0.5f);
}
}
}
}
this is what I have
did you clik on the error to see which object it is complaining about
both
its complaining about a line which only has GameObject afterImageSMObject = Instantiate(afterImageGhost);
The actual Material asset
you are making assumptions
wrap your code in a try {} catch {} and output the material which is causing the error
try {
mat.SetFloat("_Transparency", transparency);
} catch() {
Debug.log(mat.name,mat);
}
Isn't the problem the GetFloat in OnEnable?
could be any of them, debugging them is the same
no prints
just errors
Material[] materialToFade = _meshRenderer.materials;
if (transparency > 0f)
{
foreach (Material mat in materialToFade)
{
try
{
mat.SetFloat("_Transparency", transparency);
} catch
{
Debug.Log(mat.name, mat);
}
}
transparency -= Time.deltaTime;
}```
What's the error again?
you need to apply this in the place the error occurs
This has no error message
how do I do that
Right... so that's pretty descriptive, no?
yea, but i only have 1 material
seriously?
private void OnEnable()
{
try
{
transparency = _meshRenderer.material.GetFloat("_Transparency");
} catch ()
{
Debug.Log(_meshRenderer.material.name, _meshRenderer.material);
}
}
Where are you setting the material? And what's the material?
fuck
right
sorry
I didnt do it in enable
I set the material in awake()
well not the material
Not in the code you shared
but thats where I get the reference to it
then I do Material[] materialToFade = _meshRenderer.materials;
So it's set in the inspector?
no
So where is it set?
the materials?
for the object?
in a different script
and the best part is
the shader is unlit
but the console is complaining about a lit shader
@quick pollen Use full sentences, please, don't spam the channel.
yes, because you haven't set the material yet!
that other code that sets it - it's probably called later
yeah, so OnEnable is first
this didnt work either btw
Awake and OnEnabled are called immediately as you Instantiate
Start is called later
How did it not work? No prints?
but the object is disabled by default?
yeah
are you sure?
yes
here comes this again
you get the problem in OnEnable, which was called from Instantiate
impossible based on the error you shared
because i dont want to use them immediately as I load in
wait what
that's fair, but it's not what the error says
it does, for objects that are enabled
yes, make the object disabled 😄
like SetActve(false)
the prefab
fuuuuck
the ghost prefab was activated by default
and it was set to be deactivated later
im so stupid
but also, start trusting the error messages man
these are like super descriptive and tell you exactly where and what is frogged up
well it was saying that there was a problem with a Lit shader
when I only had an unlit shader
Except that warning (the yellow one). It means nothing. Amazing it is still around.
so, apparently you don't only have an unlit shader
stop making assumptions. The error messages are always right
SteveSmith told me that it's really crucial
and that it means that something got seriously fucked up
the hotcontrol one yes
just don't touch it - it's hot 😛
because now Fogsight tells me that its irrelevant and SteveSmith told me it is
and that I should figure out what's causing it
The warning not error
yes I'm talking about the yellow warning
okay... you can check the warning, see what the stack trace is, see that it's only Unity and not you, and ignore it politely
I told you, it is caused by an Inspector or Editor error, something going wrong there
if it is caused by your code, then you should fix it, but it's probably not relevant to the error, because it's GUI stuff
also appareantly this doesn't deactivate it in time
yeah, and you told me that I should go try and fix it
absolutely, if you can locate it
because it can mess up some static values
of course it doesn't... SetActive is after Instantiate 🤷♂️
well yeah considering its GUI i cant do much
but I can't deactivate it before I create it
its like painting a wall blue before you build it
the prefab needs to be deactivated, if you don't want Awake and OnEnable to be called inside
but yeah deactivating the prefab worked ofc
I just thought of something like this possibly messing things up so I had that SetActive(false)
but it didnt really help
thank you all for the help!
I spent like 4 hours on this last night
Someone know where can i to put JSON file?
you need to learn more about debugging... logging every thing that is suspicious to you, or attaching the debugger and going line by line until you see the issue, etc.
AND trust the errors - they tend to tell you exactly what and where the problem is... from there it's your job to understand why is it like that, which isn't always easy, but hence the debugging skills being crucial
its not like i dont trust the errors
I just found it strange that it didnt have any noticable effects
and at first sight I thought it was on a completely different shader
Should ask a full question as well
omg
this works so well
it basically used to look like this back then
i think the fact that I instantiated them all the time was really slowing it down
Hi good morning
When I opened the code there was an error, why is this happening?
wrong server?
not even close to C# code?
for some reason, whenever i change walls to the whatIsWall layer, wallrunning doesnt seem to properly work even though the checkforwall looks for that layer
and these are the only lines that use whatIsGround And WhatIsWall
The purpose of this is to prepare a save system through JSON
But... for some reason JSON doesn't work
wilhelm typing a whole book lawd
but where do you get the idea that that is valid C# syntax?
so how do you set the whatIsWall mask?
I have an enum and a struct like this:
public enum DamageType
{
Circular,
Box
}
[System.Serializable]
public struct Damage
{
DamageType damageType;
public Damage(DamageType damageType)
{
this.damageType = damageType;
}
}```
and i wan't to **serialize **this struct with custom constructor in a class.
```cs
public class Damager : MonoBehaviour
{
[SerializeField] private Damage damage = new (DamageType.Box);
}
But it won't serialize as DamageType.Box. Instead, it will serialize damage.damageType as DamageType.Circular.
This thing only works if this is a class.
How can i achieve that for structs?
forgive me as i am incredibly new and am just studying a couple tutorials at the moment but can you explain to me what you mean
somewhere you have a variable whatIsWall, how is it declared and what value do you give it
OH
i must have misclicked when assigning that
and clicked whatIsGround instead of whatIsWall on the dropdown
I am surprised that even works at all
your types are not flagged as Serializable and damageType is private so wont be serialized anyway
Oh sorry i forgot that. The struct is already flagged with Serializable
public class Damager : MonoBehaviour
{
public Damage damage = new Damage(DamageType.Box);
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
[System.Serializable]
public enum DamageType
{
Circular,
Box
}
[System.Serializable]
public struct Damage
{
public DamageType damageType;
public Damage(DamageType damageType)
{
this.damageType = damageType;
}
}
Weird. The struct was a serializable class before. May it happen because of that?
nope, the rules are the same
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float ForwardForce = 2000f;
public float SideWaysForce = 500f;
public float fixedDeltaTime;
void Start()
{
rb.useGravity = true;
fixedDeltaTime = Time.fixedDeltaTime;
Application.targetFrameRate = 60;
}
void FixedUpdate()
{
rb.AddForce(0, 0, ForwardForce * Time.fixedDeltaTime);
if (Input.GetKey("d"))
{
rb.AddForce(SideWaysForce * fixedDeltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
rb.AddForce(-SideWaysForce * fixedDeltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
hello, can someone help me please figure out why the player movement speed is always faster when the game is tested in different machines ?
i've tried everything i know, but whenever one of my friends test the game, the sideways speed is either way too slow or way too fast
At a guess, because of the length of time the key is being pressed
hmmm, even with a single short press the sideways speed was noticeably different when tested on different computers
i tried locking the frame rate hoping it would solve it but it didn't
you do know what GetKey does I presume
not that i surely know, but i assume it detects if that certain key is pressed every update
pressed and held, which will be hardware and OS dependant
If you only want force to be added once use GetKeyDown or Up
hmm, can this be the cause of the inconsistency between the machines ?
i will try this!
not just the machines but also the person operating them
generally for physics stuff you want to collect inputs in update (so that you don't miss any) and handle them in fixedupdate (since that's where physics stuff might happen)
only moving the player on keydown or up doesn't sound like a reasonable solution for player movement
but he is adding force, not moving
ok but it's a player movement controller...you're telling me if i am trying to move a character in a realtime game and i press 'left' and hold it down, the character should get pushed left slightly then sit there? nah
no, that is not what I said
that's what would happen if you only apply force on down or up, no?
no
i guess i must be missing something then
is there a way to force your game to go into "x is not responding" mode in windows??
like i dont want my game to crash, i want it to become non responsive with the actual popups and evreything... is there a way to do that?
(dont ask why)
does a ball stop rolling when you let it go? does it fall to the ground the instance it leaves your hand?
is...this character a rolling ball? physically accurate objects do eventually come to rest, yes
Do a nop while loop that just counts to int64_max.
regardless that would still be an absurd way to try to control a character
yes and the operative word is 'eventually'
what does nop mean?
i tried fixedupdate, gave seem problem, then locked the fps to 60 but no fix
Do nothing
that doesn't sound like what i suggested
so will this send the game window into stasis as soon as the while loop starts?
like, obliterate it?
no exceptions?
basically an infinite loop of doing nothing
I’m not sure what your requirements are. I believe that if you have an infinite loop that doesn’t handle incoming windows events or something, windows will think it’s not responding. If you have a really long not exactly infinite loop, you’ll at least do that for a finite amount of time.
my mistake, i see what you meant now, should i also use a fixedDeltaTime value ?
i don't think you need to do anything with time deltas if you're just directly setting the velocity
okie
Adding force while holding down a button is a common way to control a character
oh VelocityChange isn't actually setting the velocity, my bad. but generally if you're dealing with 'forces' you don't need to do anything with deltaTime since the sim handles that and you're an abstraction away
It applies acceleration that works with unity’s mass and friction values
yep! adding force only when they press down or up on a button is not a common way to control a character and makes no sense
never made a pinball game I guess
would you controll the pinball directly with input in a pinball game?
I think he means the flipper
like a character?
is the flipper a character?
and you'd call your flipper mover "PlayerMovement"?
like i'm not sure what you guys are even arguing at this point but it seems very silly
what's the drama now? 🙂 my flipper is a total player 😏
wait, that's not how I imagined this would sound, sorry 😅
just people giving poorly thought out advice and then setting up unlikely scenarios to try to argue it's useful for some reason
Well for one you are saying controlling a character using an on-down impulse force is “absurd” but there are use cases for that kind of control.
no i am notttt
Isn’t that what you said above?
i am saying steve's specific suggestion that that character controller should only apply forces on keydown or keyup was not useful
for what this person is obviously trying to do
Ok fair
my advice was based on what he specifically said he is trying to avoid, not on what he is trying to do as he has not specified that as yet because no one has asked him
so something like this should work right?
void crashLoop()
{
int i = 0;
while(i < Int64.MaxValue)
{
i++;
}
}```
Try it I guess
good point
I'd start with a lower number and increase until a number I like for my testing purposes, but sure 😛
(this might be a bit too long and practically end in you having to kill the app)
True
thats the point
im trna add like an ARG thing
ah, okay 👍
hello all, im getting an error about not referencing an object in my script
heres the code
foreach (ContactPoint contact in playerCollision.contacts)
{
Debug.DrawRay(contact.point, contact.normal * 10, Color.white);
}
all debug statements are getting printed but chartcter is not moving
im assigning the playerCollision on another object in game and then reading the collision info from a global variable
😭
what does the get set do exactly? i still dont really get it
move speed too low?
no thats enough
not sure then
maybe try using .GetAxis("Horizontal");
to get input
store it in an integer var
then multiply it with speed
🙂
void move_player()
{
move = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(move * speed, rb.velocity.y);
if(move < 0 )
{
gameObject.transform.rotation = Quaternion.Euler(0, 180, 0);
}
else if(move > 0 )
{
gameObject.transform.rotation = Quaternion.Euler(0, 0, 0);
}
}```
this works for me
@rigid valve
I am not so confident with new input system
thats not the new input system
is that yuta lol
yes lol
i dont know
well
you didnt save it
the speed variable
you didnt press ctrl +s
try that maybe
hello
can I tell you something?
yes sure?
you don't have to write private RigidBody if you don't write private its private by default
can you try my code the one i gave
see if that works
move is?
please read #📖┃code-of-conduct
you should still always write private, for consistency and so that whoever reads next doesn't need to think
the move variable?
no
its okkkk. Its my opinion only I like shorter codes
its an int
or float
you can use any
what it does is it take 1 or -1 from your input aka a or d so if you press a it sets the value to -1 which is multiplied with speed then moves the player to left
its automated left right movement
Posting 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.
thats cause
remove the stuff in your update function
then call the function move_player();
in update
still nothing
just the sprite is doing a kind of flip when pressed a amd d
but not moving
remove the if statement in update
i think u need to use while not if but be careful to handle that while without entering infinity loop
😭
to start with you should not be mixing rigidbody and transform manipulation
@cobalt wing gave me this code and its working for him
thats rotation to rotate sprite according to the direction its moving
targetRigidBody.AddTorque(Random.Range(-torque, torque), Random.Range(-torque, torque), Random.Range(-torque, torque), ForceMode.Impulse);
targetRigidBody.AddTorque(Random.insideUnitSphere * 2f, ForceMode.Impulse);
I wanna ask a question. Which one is better? (torque=2f)
Removed torque variable and directly put 2f there
and 3 random ranges to random insideunitsphere
https://gdl.space/qadorokeyo.cpp
full code
the other script
that happens when you define a script, attach it to something, then delete that script
ah nice there's even a huh article for ya: https://unity.huh.how/common-warnings/console-warnings/missing-script
eh? but I have only 1 sript and still still presen tin game
well it could be one of the other issues, check the article
i wonder what went wrong
can you check my code pls is it good
void Couldown(){
if(CurrentCouldown <= WeaponCouldown){
CurrentCouldown - 0.1;
}
Current couldown is an int
it gets an error message
on the CurrentCouldown -0.1; anyone know a fix?
idk if I typed it right lol
Both of your options do the same thing, but always use a variable instead of magic numbers . . .
did you check my full code? is it good
!code
- and -= is not the same
also this probably frame rate dependent
Posting 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 ok
An int is a whole number. How can you subtract 0.1 from a whole number?
i tried it with both
float and it
lemme do the er
-= thing
with a float number
Well, you're not assigning currentCooldown and you should subtract using deltaTime . . .
ok!
Hey guys, I'm trying to make a aim trainer arena, when ever we hit a target, it will be disabled, moved to a new position in the list, and then reanable, but after hitting it once, it did moved to a new position but the same result doesn't happen when I hit it again
error CS0266: Cannot implicitly convert type 'double' to 'float'. An explicit conversion exists (are you missing a cast?)
0.1f is short hand for (float)0.1
And if you need to subtract using a float, the variable should be a float as well . . .
OML
All i had to do was right 0.1f first instead of -= and - and int and floats and random stuth
Thank you guys so much 🙂
the compiler will solve the type of var
so compiler got my back about that you say?
its workimng now lmao I just removed the rigid body then added it back
any idea why my script(UmbrellaMan.cs) cant find the assembly definition of SourceConsole?
some of the scripts im trying to access in UmbrellaMan.cs, are in a folder that is placed with the ASMDEF file SourceConsole, and the definition file for UmbrellaMan.cs is DELTAV. and DELTAV has SourceConsole in its assembly definition refrances. yet im getting an error saying that "The type or namespace name 'ConCommand' could not be found (are you missing a using directive or an assembly reference?)"
I said you should always use a variable, like torque, instead of a magic number, like 2. That way, you can use the same variable in other areas of the code, and changing the variable will use the new value throughout your code
You must replace a magic number everywhere it is used . . .
._.
great
dont sweat over it
happens
Also, this is nothing to worry about . . .
thanks my man or woman. Im obsessed with writing shorter codes with the same functionality need tosee a psychiatry soon
I even remove braces from if if theres only one line in between
my code was 95 lines brought it down to 44 now
I dont think I can make it any shorter
you know shorter code is very rarely better or more efficient code so this would be a good habit to break
that is horrible
Use comments explaining functions
Or else it will be hard to understand later
so what, the compiler does not care how many lines it is
yeaa can do that
they are considered blank If I remember right
so not compiled
Readability is preferred. There is no reason to try and shorten this. Your method braces should always be on their own line. Single line if statements are okay . . .
do you really think that the number of lines in your code makes the slightest difference to the compiler?
Your method name should explain what it does, and variable names should demonstrate its use or intent. Those are your comments . . .
Yep, definitely do not need to go and waste your own time commenting stuff that doesn't break POLA if you're working solo
Also, cache the Rigidbody to avoid multiple GetComponent calls . . .
yeaa let me add it again
I accidentally used something very expensive when trying to make it more optimized lmao
there is nothing 'optimized' about that code, less code does not mean optimised
yeah man your right but you don't know me I am sick
will try to break this habit soon
Hello guys, I'm trying to make a proximity spawner and it doesn't seems to work. Now it not spawning enemies, but before it was spawning endlessly or a bunch in a few seconds intervals. I tried many ways and it doesn't work
Even so, you should follow code conventions and guidelines. The format is not even correct. You can't tell when a scope ends, which is error-prone . . .
Hello guys, i have problem with my script, can you help me? I'm writing a script on macbook and my Arrow dosen`t work
Maybe on mac we have other keys?
Try GetKeyDown
did you attach this script to an object with a rigidbody?
and you should try to Debug.Log to see if it actually runs your code. https://unity.huh.how/debugging
Your coroutine assigns canSpawn to false; the following if statement will never be true, so nothing will instantiate . . .
yep
But how should I put the canSpawn false again? Because the thing is I need the enemy to spawn every X seconds
@fresh parrot the coroutine does not run until completion before the following line. Execution starts the coroutine and immediately moves to the following line . . .
Unfortunately, does not work
Place the spawning inside the coroutine . . .
Once the wait period is over, spawn an enemy . . .
I already tried that and it spawns endlessly
hey does anyone know a good youtube tutorial or course or website where i can learn coding languages?
See here, the enemies spawn like 34343 in intervals of a few seconds
Please configure your !ide before asking questions here
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
I mixed up right and left and debug.log helps me 
See above message
Is this code supposed to spawn enemies every 10 seconds?
!code
Posting 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.
An update method will call the coroutine every single frame, and the delay is not changing that
Yep
how do I use !code
Posting 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.
Right, so instead of having an update loop, have a Coroutine that checks distance every frame (you can do yield return null to skip a frame). If the target is met, spawn and then wait 10 seconds. Repeat coroutine
You can make the coroutine have a while loop so it repeats
thanks, second please
I checked it out, and it's amazing. Did you send me this because I have a weird looking line of code?
wat.
this says error
to do with the game obj
error CS1955: Non-invocable member 'GameObject' cannot be used like a method.
Anyone know why? sorry i am real new if its rly simple fix
But on the Inspector I have like a tomb, and when the player is inside the radius only then it should start spawning enemies
Inside the spawnradius
I have already done what you wrote
Gameobject is not a method. You are using it like one.
Destroy is a method, yes
Please do a c# and/or Unity tutorial as these are basic questions.
also please do not crosspost the same question on multiple channels
self error nothing to do with overall knowledge my own fault and self error that I should of found myself tbh
this entire website is auto-generated spam
hi
Thank you very much, I just installed visual studio and now my code looks fine
that is certainly bs
the compiler figures out wtf it’s doing. it should not impact anything at runtime at all
it will not impact anything at runtime indeed
you should avoid var for style reasons, but that is my hot take, and totally separate from any performance issues (of which there are none)
Booooo . . .
yeah. I know. var really is that bad, but a lot of people spam it
like var x = 5; You’re not even saving on typing characters at that point
If I want to do weighted pool where there are a bunch of stuff with different chances of appearing, I should be using a Dictionary with the object in question and an int as the chance of that object or...? I don't really know how to handle this to be as modular as possible...
make a custom data structure
a simple class with a different collection inside
Your custom data structure should have the following things:
- A field for current total weight. (private setter)
- A collection that holds entry and its weight.
- Be generic, so the entry you store could be of any specific type
- Have a method to perform a random selection.
- Methods to add/remove entries with a given weight
- methods to read and modify the weight of an existing entry
this should be relatively simple. But you should make a custom data structure so you can abstract and do whatever implementation underneath, and/or change it in the future. It also separates the responsibility of managing weights
the whole shebang should be fewer than 100 lines of code tbh
but you might want to add features later, like implementing IEnumerable<TEntry>
there's Sharping's which you could reference https://github.com/cdanek/KaimiraWeightedList
yeah, this is a good one. I’d try this
The code screenshot you send shows your editor doesn't know most methods so it's not configured
What does the error mean?
If you keep a dictionary of entries and weight, you have O(1) CRUD time, and O(n) random selection time.
The one prakus linked has O(n) CRUD, and O(1) random select
I want this to change the weight of stuff pretty often, since is the kind of things where there are lot of different instances of the same pool with different chances. Like maybe in some point in the game some enemy is way more common that another or this a rare rewards and uncommon items are way more likely to shown... stuff like that.
does this work the way i think it works?
private void Gravity()
{
if (!grounded)
{
rb.velocity = new Vector3(rb.velocity.x, -1f, rb.velocity.z);
}
}
Also, the collection, should definetly be a Dictionary right?
is bro coding unity on a smartphone?
what is the ratio of number of times you modify the weighted list vs number of times you randomly pick from it?
My humble opinion is that you can make this in 10 different ways, and more likely than not they'll all be fine 🤷♂️ 🙂
Lol I used Windows Shift S
do you modify the list more than you draw from it? If so, i would do this with a dictionary<TEntry, int>
if you randomly draw from the list more frequently than you modify the weights, then you should do this
ok, forget my question earlier, i want to know a thing, how do i stop my player from sticking to the walls while i input the movement to there?
like, i want it to slide down even when inputing to go there
but since the one prakkus linked is already made, I would say that I would expect a ratio of 10:1 modification:pick, before I even consider coding it myself
Put an Physics Material on the floors an walls
@frigid sequoia understand?
is your character a dynamic rigidbody with discrete collision detection mode?
if so, set it to continuous
hi my visual studio isnt autocmpleting unity code
Yeah, I would say that one will work fine; I can just create a new instance of it from specific spawners and modify the values manually. And if I want the pick to be more weighted towards rare stuff, I can just... increase the weight of every object by a flat amount, that should make rare stuff significantly more common, without the need of adding a rarity tag or anything like that
you can just use bigger ints
!ide
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
bigger ints = more resolution
just start by giving everything the weight you want, but add 2 zeros. Like instead of 1, 2, 5. Make weights 100,200, 500. So you can potentially change your mind and mess with things later
I wrote a little extenison method for this
not a huge fan of that return default at the end
Random.Range with floats is inclusive, not exclusive
of course, floating-point errors will also probably cause slight errors anyway
i should just return the last item in the sequence in that case
this is O(n) draw, so it’s more of a correction method
oh yeah, this is less efficient than if you have a few rarity buckets
in that case you can do the draw in constant time
hey all. im dealing with a simple calculation problem. I want my sunTimeSec to progress acording to the orbit/position of the sun, but the suns needs to orbit twice to complete a full day, and i want sunTimSec to progress according to that 2 cycle. Its supposed to be updated in method UpdateSunTime() but im not sure how to do it so i have as 'sunTimeSec += Time.deltaTime;'.
but if you are using a data structure, you should probably have a method in it to use a different weighting function, or to modify all weights in the table with a given re-weighting function
Why does this code sometimes teleport the player a lot farther away from the respawn?
RSPN sounds way worse than...respawnPoint
why are you moving your player’s transform when it has a collider, and moving it in a collision callback
that is asking for trouble
If the player has a CharacterController or Rigidbody, then moving the transform directly can break, yes
i’m not saying that is your issue, but it could be a part of your issue
at which point you probably want to move the player’s rigidbody.position
You should reference the player's rigidbody
because that moves the transform and colliders
[SerializeField] Rigidbody playerRigidbody;
okay
If you move the transform, the physics system is "left in the dark"
it only learns about the movement later
if you move the transform, the colliders stay where they are
and if you have Interpolate enabled, the physics system just ignores your new position entirely
should i make it make the rigidbody kinematic when it teleports?
not really
no, you should just set the .position property of the rigidbody
okay
setting rigidbody.position teleports the object, transform, and all the colliders
without respecting physics collisions!
any idea why this is happenning? it is not supposed to go like that. i can post the 2 scripts if needed
don’t move the transform
also, you don’t need to reference GP when you have rigidGP
"RigidBody" doesn't exist
-.-
it's Rigidbody
ohh
your IDE is clearly not configured. !ide
rigidbody.gameobject directly links you to the gameobject
i'm not actually sure what you're using here
okay
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
so like "Rigidbody"
you are modifying your code without understanding what is going on. stop it
stop and think before you write code
right now you have references to rigidbody, and GP, and rigidGP, and rigidGP.RigidBody
i know im fixing it
no, you're just making random changes
i noticed the problem
slow down (and name your variables more cohrently)
and then asking us if it is right
anyway, first order of busjness is to configure ur IDE, otherwise we can’t help you
because #854851968446365696
!code
that just makes the bot give you links to pastebin services
oh
you need to follow !ide
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
i made the code a little bit more understanding and did the rigidbody teleport
like instead of "GP" its "player"
and instead of RSPN its "respawnpoint"
does your IDE tell you where your code doesn’t work yet?
Hello, is there a way to invert transform.LookAt(), right now it looks at the object in the Z axis of the object, try I want it to look at it in the -Z axis
that should be giving you a case of the red squiggles
im not really good at coding
can someone help me with some code? im making a top down game and trying to get the enemy to shoot in the direciton of the player, but the bullets spawn in and they only move on the Z axis so theyre basically stationary
i dont really know what ide means
your IDE is the software that you use to code
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
follow the link for your ide, and then follow the directions. This is the 4th time we ask. you will not receive help here until you do
it's your integrated development environment
the "integrated" part means that you have things like compiler errors built into the editor
currently, that is not working
and having it work should be your top priority. not fixing your code
i have this unity 2d code that makes a ball bounce perfectly,
void OnCollisionEnter2D(Collision2D collision)
{
float speed = lastVel.magnitude;
Vector3 direction = Vector3.Reflect(lastVel.normalized, collision.contacts[0].normal);
rb.velocity = direction * speed;
}
how do i make it so that the bounce direction is changed within a range?
Hi, so I have a problem with the spawning my menu, I want my menu to spawn at my cameras location plus an offset when I press escape, here is the code:
"escMenu" is my menu, and teh script is part of the main camera. My menu ends up spawning at teh coordinates the prefab is located. Why is this, and how can I change this, thank you for any help in advance!
i want to connect these in order to make the air movement play when the character is in the air, but make the slide play when the character is in the air and touching a wall (for wall jump), I've tried several configurations but it hasn't worked. how do i?
Can you send that whole code?
Is that in GameManagerX?
I feel like that naming is gonna cause issues
This should be a syntax error
private void Update()
{
timeLeft -= Time.deltaTime;
timeLeft = "timer:" - Time.deltaTime;
if (timeLeft <= 0)
GameOver();
}
You are assigning a string to the float
the syntax is good; the types are bad 😉
The - operator is not defined for string and float, so you get an error
The timeLeft variable is a float.
Now, if we were in JS-land... 😂
So did you remove that underlined part? A compiler error will stop the code from running
can someone help me with this? I don't know how to animate this...
yeaaah I removet
been researching
kinda sucks I have to have 2 different scripts for this
Im stuck here
i did everything in !ide and my text autocompletion in unity still dosent work
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
for examplei type in Rigid... i expect vs to show autocompletion to RigidBody 2d
it dosen work tho
You don't need two different scripts, but that IS a good idea to split things up whenever possible.
More scripts doing less is better than less scripts doing a lot
Im working on a pickup/drop system for my items and ive been trying to fix this "Object reference not set to an instance of an object" error but to no avail.
how am supposed to draw the seconds on screen If I cant use string
What do you mean you can't use string?
seconds.ToString()
IT still wont draw seconds
I have timeleft but never used it in method 😕
In this short video I am gonna show you how to quickly make a countdown timer in Unity in a few simple steps. That's it :D
Make sure to pause the video to copy the code. Or better yet just download the script from here : https://drive.google.com/file/d/1YS0y89zqQgAtUNWbsRk0XBi20_wRkBGT/view?usp=sharing
#shorts #youtubeshorts
I am following this guy
this guy doesnt use it too
never mind im a smooth brain
Show the inspector for the object that has Timer
Timer is not on this
Ah ok
Can you show it without cropping. I want to see the whole editor
This is still cropped
Oh, you assigned the text to the number, it overwrites the entire thing
I don't care about that
I wanted to see the stuff to the left, not the inspectors. Specifically the hierarchy
But that doesn't matter now. I thought you were saying the text didn't update at ALL. To be clear, the issue is that the words "Time Left" get erased?
You have to update the text to EXACTLY what you want it to say:
timer.text = $"Time Left: {seconds}";
What you put in the inspector is lost the second you assign to .text in code
when game starts timer decreases by 1
it stays there
the last thing to fix now
Can someone please help me with this, ive tried so many different things now and i cant figure it out
Where do you call UpdateTimer?
in gamemanagers start game method
Where is StartGame called?
I assume it only happens once?
No, I meant what method
it is only called once
Then updateTimer only runs once 🤷♂️
I would just make UpdateTimer be Update
Update is called once per frame
But subtract Time.deltaTime, not 1
What's not working? The code says that they'll move in the x and y axis (not z) - relative to their position and the player object.
With physics 3d
theyre not moving on the x and y axis at all, ill send a video to better explain
Log the velocity after assigning it.
That would verify if they're moving as expected with the code shown.
A video of it not doing what you're wanting won't tell me if the code is working or not.
what do you mean by this sorry
Also embedded mkv files aren't playable in my discord app
Log the velocity of rigid body
Print the value
You know.. Debug.Log
yeah okay thanks
If the x and y components are not zero then it's working as intended
The code shown, that is.
Is there any built-in enum for deltaTime type? Like this:
public enum FrameType
{
DeltaTime,
DeltaTimeUnscaled,
FixedDeltaTime,
FixedDeltaTimeUnscaled
}
I searched it but getting different results...
Why does it need to be built-in and enums?
I don't know. It just was a thought.
hey, i'm trying to make a spawning code for a player object for multiplayer purposes, but i cant spawn the camera with the prefab (it just doesnt happen idk why) so does anyone have tips?
Probably not
What happens instead?
velocity stays at 0 the whole time
well i have a prefab with a camera and i use instantiate but it just says 'no camera' but if i drag it out manually the camera spawns
What did it print?
What you see is not what had happened in those lines of code
well i put debug.log(rb.velocity) in it and the only thing in the console was this
Maybe provide more context like the actual code
Show how you did it
public void OnSpawnAPrefab() { if(random) { float x = -40.0f; float y = 0.0f; Instantiate(prefab, new Vector3(x, y), Quaternion.identity); } else { Instantiate(prefab, spawnPoint, Quaternion.identity); } }
You cropped out the important stuff - line numbers
Place a log and see if the function is ever called
okay
I'm assuming the player was null and that line 15 is referring to usage of the player variable else rb was null
oops
So it isn't related to the log. You've got an nre with the original code
Where rb was null
You need to assign rb something before you can use it
fixed it thank you i completely forgot to fuckign assign rb to rigidbody
braindead
sorry about that
it calls it just sayd 'display 1 no cameras rendering' when i click play to switch scenes and spawn the prefab
then you have no camera in the scene you switch to ?
it spawns with the prefab (or should)
So does it spawn the camera?
the prefab contains a camera and the code spawns the prefab but it says there are no cameras
i have a play button in the main menu that changes scene and spawns the prefab
So, I'm just trying to verify. The camera object spawns in the scene hierarchy?
no
Check the spawned camera in the hierarchy and see if it's correctly configured
So it doesn't spawn?
Are you perhaps spawning a camera and then loading a scene?
it might be that it spawns before the scene changes but thats just a guess and i don't know how to fix it if it is the problem
Spawn after the new scene is loaded
Most straightforward way would be to have a script in the scene to spawn the camera
how? would i make another spawn script that plays when i load into the 2nd scene?
Is there a reason why the camera needs to be spawned by code? Why not just have a camera in the next scene?
well i'm trying to make a multiplayer arcade tank game and i want the player character to spawn in by code so i can have other players spawn in aswell
Hmmm, there ought to be one camera only though right?
well one camera per player
Just have the player spawn the camera after they've been spawned
wym
You're going to need to spawn the players in the next scene and every one of them are going to have a camera so just spawn the camera when you spawn the players
thats what im trying but i dont know how to detect after the scene changes
Why would you need to? Just have the code in the next scene that does it
no but when does the code run? it would need to call the function?
It shouldn't be this scene's responsibility for what's in the next scene - unless you absolutely must have to have the next scene configured from this scene.
i mean when does the next scene know to call the function
Hello, what is the best way to move a RigidBody ? I had a Character Controller, and I was just using .Move(), but I don't find a equivalent for RigidBody. For now, I'm changing directly transform.position (also, Use Gravity is unchecked), but I don't think it's the most efficient method.
An object in the scene with the start function?
Awake and Start run when an object is instantiated
so make an empty object that calls the function at the start of the scene, right?
You'd share data between scenes with a Singleton ddol object or some static manager class
Assuming you've got some sort of persistent manager for managing player count etc for your multiplayer game already setup
Modifying transform position would be teleporting and ignores physics
well right now its a singleplayer setup with a single map and stuff but im trying to setup prefab spawning so then i can call that when a new person joins the game
when i make it multiplayer
Is this a local multiplayer?
well i haven't started making it multiplayer i am starting with making player spawning a function so when i get to making multiplayer i already have a playerspawn function so when someone new joins they simply call the playerspawn function in the map
Will it BE local multiplayer?
i was thinking of using netcode or something to make it online multiplayer (i just googled how to add multiplayer to unity and that is what everyone said)
make sure not to do too much before getting into the multiplayer aspect.. u might be regretting that u did
wym
Then the entire way you're trying to do it doesn't make any sense
multiplayer features are tightly integrated into core mechanics most time
And do you have an idea of method I could use plz ?
its good to develop the multiplayer parts alongside everything else
yeah converting a non multiplayer game to multiplayer can be very hard
its not just something u can throw in at the end
Build from multiplayer from the ground up, otherwise you're gonna rewrite almost everything
(most times)
Local multiplayer you can get away with adding on top, a little.
But not networked
Which is one reason I was asking
networked is another type of beast..
local multiplayer ur just ususally changing player inputs and thats all
network multiplayer basically has to do with everything, movement, spawning, scorekeeping, etc
is it good to use serializefield this much?
all i have right now is a basic map a player prefab and a main menu so im not adding it in at the end, i'm trying to figure out how to build it in the first place
much better than trying to Find components all the time @ runtime
Its neither good nor bad
Well, the route you're taking is incorrect.
Have each client add their own camera, and don't worry about other players at all
Just have the camera in the scene
why then?
well the prefab contains the camera so if the client calls the func it spawns a new camera for the client
Why what? You use serialize field when you want a private field to show up in the inspector
If the prefab contains the camera, then just use that?
Server initializes the client, done. Client already has the camera
I just don't know if it is correct to use that or is there different way
A different way for what? Having things show up in the inspector ?
If you're wanting rigid body physics, you're going to have to use forces or modify velocity. Else if you're using a kinematic rigid body, you can use the rigid body move position (you'd implement some physics yourself).
thats what im trying my question in the first place was how to call the spawn function after the scene changes from main menu --> play button pressed --> switch scenes + spawn prefab
Why call a spawn function, is what I'm saying
The client scene would just have the player in it
ya, multiplayer ur not actually spawning in every player.. each persons game is just spawning in 1 player..
or is just there.. like aethensoity mentioned
but how does each new client spawn is what im saying... im trying to figure that out
can u share what code u already have?
The same way it would in a singleplayer game
a Start() method or something
Either the player is IN the scene. Or you have a gamemanager in the scene that spawns it itself
thats what im trying to make
GameManager or something would take care of htat. if u want them spawned in at runtime
Change OnSpawnPrefab to Start
And boom, put it in the scene, you're done
^ when the game starts the scripts start method is run..
then it spawns the player/camera/ew
so i attach it to an empty object then it spawns on scene start?
!vscode
Yep
That empty is typically a GameManager. But that is just meaningless convention
The player doesn't usually spawn itself. You'd have a manager that the next scene would interact with to acquire the necessary data for doing whatever it needs to do like spawning.
public class GameManager : MonoBehaviour
{
public GameObject playerPrefab;
void Start()
{
SpawnPlayer();
}
void SpawnPlayer()
{
//do your thing
}
}```
Consider just loading the next scene and having something in the next scene spawn the players for the next scene.
Where you'd pass persistent data with some manager
so far i got this:
Save your scene ASAP
hey! it worked!
if ur game crashes ur gonna lose everything
its saved
as of screenshot not saved
ahh k
as of now saved
just lookin out for ya 😄
🫡
The fear would be accidentally placing that code on the player 
bRrrrrrrrrrrrrr
does anyone know any 3d game tutorial video ?(send dm)
nah i made an empty game object and connected it to that and start of scene 
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ty
now what happens in the next scene.. u gonna have the script in there too? so it spawns in the player (again)?
no the first scene is the main menu which you press the play button then it switches to the second scene and spawns the player
now time to suffer through a youtube tutorial on multiplayer thisisfine
im following a tutorial and i get and error "you are trying to save a prefab that contains the script which does not derive from monobehaviour" while everythinh matches !!!! pls help
Are you sure everything matches ?
script name - PMS class name - PMS
Can you show a screenshot of the prefab ?
What does the error mean?
Exactly what it says
Have you tried reading the do documentation about Rotate ?
It wants a vector 3 but you're calling it with a single float.
can I ask if dots and ecs are easy to use now?
Oh
#1062393052863414313 You could probably try asking there.
its exciting af but hard
Log stuff
This?
Or read what you coded
Keycode.W, not "W"
Rotate(0,0,0)
wait why does the error say Up but code says W
Probably a new issue
try Keycode.W
Sure it did, to this #💻┃code-beginner message
I suggest you go do some !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
wont make any difference it will always be a 0,0,0 rotate
Quick question, how can I apply constant force to a RigidBody ? Like, I have a custom gravity force, and I was using .AddForce, but my object falls and jumps incrediblly slowly. I guess it's because the force it applied each frame, maybe ? Anf thus, how could I fix that ?
add MORE gravity
You don't need that with AddForce
(because AddForce with the proper (and default) params does it internally)
Yeah you don't use time.deltatime with physics
Oh
and u gotta use FixedUpdate
But How does KeyCode WORK?
It is an enum
Or physics force mode impulse
It has values
That's about it
just type GetKey(Keycode.W) instead of a string in there like you have atm
because Keycode. is just using straight up Hardcoded keys
when u use "W" thats using the presets in the Input Manager
"Horizontal" "Vertical" type stuff
im pretty sure.. yea you need the UnityEngine using statement
the default using statements you have in the script when u create one in the first place are enough, u dont need to add anything
Am i doing it Wrong then?
u removed the Input. from before GetKey. u need that too
also it needs to be an if statement
Then i guess i need to make if not?
Because now it just spins out of control and does not stop
nvm
I just had to remove ";"
yeah if-statements dont have a ; after them
But if i can not make it 0.1 how can i make it slower?
try 0.1f? cuz floats need an f at the end
the canvas is the highest layer
without it, it considers it a double and those are rarely used in unity
YES!
reposition it in the heirarchy.
and also get rid of one of ur event system components
u only need 1
Why does an ball clipp thru the floor when i Rotate it on the Z axis Fourth an back
I have rigid body on both
Physics matireal?
transform.rotate doesnt respect physics so u gotta use this method instead https://docs.unity3d.com/ScriptReference/Rigidbody.MoveRotation.html
how do i rotate unparented object like its parented?
with code
u do that with code ;D
i need that in code for floppy arm
or you just rotate it in the same place you rotate the other object, with the same values (and change its pivot to the other object i guess)
hey so i'm in a 2D platforming project (from scratch), and i've been following a tutorial on the rest of this jump script https://hatebin.com/drdiuraqzm, but when i play the controller is letting me jump more than once, no matter what i set the maxairjumps, is this a problem with the jumphase? (i set it as a serializefield in the code to see what it is during gameplay, and i know i should just use logs but this felt easier)
bro i have an error saying that my method must have a return type but im following a tutorial and it has the exact same thing unless i mispelled something that i cant notice
that isnt my problem, i need to rotate it in single spot where it is while its automaticly turning to face camera
you last method siganture is incorret you have not specified a return type
sounds like billboarding? you can google that
which line is that
also configure your !ide before continuing
💡 IDE Configuration
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
u still could use this function to rotate it around the Pivot u want (and then as a child object or something).. u rotate the child to face the camera
it has the exact same thing
Definitely not. You made an error. Configure your IDE and make sure you copy the tutorial exactly.
The error message has the line number of the error in it
