#💻┃code-beginner
1 messages · Page 57 of 1
so transform.up gives up. (-y,x) gives that vector rotated by 90 degrees
(-x, -y) gives it backwards, and (y,-x) gives it rotated by 270 degrees
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Obstacle")
{
Destroy(rb);
Vector3 jumpPosition = new Vector3(transform.localPosition.x + 8f, transform.localPosition.y - 12, transform.localPosition.z);
transform.DOLocalJump(jumpPosition, 13, 1, .8f).SetEase(Ease.InSine);
transform.DORotate(new Vector3(0f, 0f, -90f), 1f, RotateMode.LocalAxisAdd);
}
}
Rotate works just fine. But I cannot seem to get the jumping correct. It somehow uses the world transform.
It should jump towards its right but instead it jumps backwards and through the platform.
I appreciate all of this. I do not fully understand, but you've given me some pieces to work with and I'll see what I can do from there. I'm utter garbage at math so that rotation matrix stuff is way over my head, but I think I can figure something out with what you've given
you should learn
Yup, probably.
2 things you should really learn well if you do this sort of physics: 1) law of sines/cosines, 2) basic vector math (like dot products and angles)
rotation matrices are extremely simple. you know how to multiply matrices, right?
I remember vaguely that it was something they tried to teach me in school several decades ago, but not how to actually do it anymore. Lmao
learn again. matrix multiplication is not complicated
this is a 2D rotation matrix. You can calculate the value of each of the 4 cells by plugging in the angle you want to rotate by
when you have that answer, you multiply it by the vector, and that outputs a vector that has been rotated by the angle you plugged in
I appreciate the effort, but this isn't going to click for me right now. I was just doing some unity stuff on my lunch break today, and I've got to get back to real work at this point
for theta = 90 degrees, sin theta = 1, cos theta = 0. So the whole matrix is just
[0 -1, 1 0]
I don't want you to waste too much time or effort putting all this out right now if I don't have time to consume it, but thank you regardless
when i have 2D character andi use transform position to move him should i use rigidbody and box colision to not allow him to move throught walls
or is there better option because when i do it the character i lagging in wall
when you randomly generate obstacles for an endless runner, do you just take random X and Z Values and place it down or what is the strategy with this kind of generation?
hi, im a beginner, and been worrying about trying to find the best way to do thing. does it matter?
like just trying to make a character move i think there are some like very hidden medthod that i should learn instead of just translate the spite 1 pixel every frame
i'm new myself but probably you initiate prefab
Instantiate(somename, position(Vector), Rotation(Quaternion.Euler))
and use random number in y position
yeah im doing that but i feel dumb generating hundreds of random numbers
what
ok hundreds is too much but 4 or 5 every spawn wave
depends if you have lanes too
its getting pretty long because the reference of these objects need to get saved to destroy them if theyre out of reach
no not like subway surfers no lanes
You shouldn't need a reference to the objects you want to destroy, let the object clean itself up when it's out of range
do you reference spawned object and destroy them from somewhere else when they leave screen?
how can i do this?
do you reference spawned object and destroy them from somewhere else when they leave screen?
I was playing around with an "Idle slayer" clone not too long ago, off screen I had a trigger zone that if/when objects reached this zone, they would destroy themselves
after 3 spawn waves the first one gets deleted right now
ok so the trigger zone should move with the character
and the script deleting the obstacles is in the obstacle
no i have a generation object that deals with everything
Yea, if that's how you have your world set up.
when i generate trees and stones how do i know if in the spot i want to generate the tree in is no stone
Clean up zone is just off camera, a set distance
Is it fine to ask hlsl questions in here?
i think so
yes
Gotcha, thanks
So.. i'm confused
SV_ in front of a semantic indicates System Value, which is basically what the system will use to draw the final image,
SV_POSITION grabs the vertex position from the mesh, but why does color get routed with the semantic "COLOR" instead of "SV_COLOR" ??
is there a way to make it so every time a builtin component of type X is added to the scene, i call a certain method?
How can i find multiple scripts with findgameobjectswithtag
Hey guys, in my mini game, I need enemies to be spawning all the time non stop. I am using this method and so far working good. cs InvokeRepeating("SpawnEnemy", _spawnAfterXSeconds, _spawnEveryXSeconds); But I need to have more control over it as I need that some enemies spawn only at first 2m and after that other type of enemies will spawn, and even tho in the min 5 i want again the same mobs from the begining to start spawning too, and so on. So i need to have control always when they are going to spawn. and when I determine they will spawn they need to keep spawning until I say stop, they dont just spawn 1 time. Coroutines might not work as they spawn just 1 time right? any tips on that?
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public class EScript
{
static EScript()
{
CleanupSub();
ObjectFactory.componentWasAdded += ComponentWasAdded;
EditorApplication.quitting += OnEditorQuiting;
}
private static void ComponentWasAdded(Component component)
{
Debug.Log($"{component.name} added {component}");
if(component is TestScript)
{
Debug.Log($"My Component {component} is what I wanted");
}
}
private static void CleanupSub()
{
ObjectFactory.componentWasAdded -= ComponentWasAdded;// cleanup
EditorApplication.quitting -= OnEditorQuiting;// cleanup
}
private static void OnEditorQuiting()
{
CleanupSub();
}
}
My ground detection detects walls
the same way you said it
var myObjects = GameObject.FindGameObjectsWithTag(c_myTag);
Hi. Does anyone know the reason why in the editor the game works okay but in the build I get a bunch of errors please?
falling = GameObject.FindGameObjectsWithTag("FallingThing");
says Assets\Scripts\HealthScript.cs(17,19): error CS0029: Cannot implicitly convert type 'UnityEngine.GameObject[]' to 'FallingThingScript'
because falling is not an array
what will happen if i use normalized twice
new Vector2(1f, 1f).normalized.normalized
will the 0.71 chaange to something like 0.6 to normalize
FallingThingScript falling; like this
thats not an array
depends what the errors are? how can we help with no context
also this isn't "assigning" this is simply declaring
I'm trying to drag and drop a Text GameObject in UI canvas onto DialogueManager at the top of my hierarchy as a variable. And for some reason, it doesn't allow it. There's probably a really simple reason why but.. xd
the types dont match or ur trying to add a scene object to a prefab
string myTag = ("FallingThing"); still declares it as invalid
I have frequently seen just doing prefab chunks. You "append" a section that you randomly grab. So a section would have hand placed trees rocks etc, and then you just randomly grab a SEQUENCE of those sections.
sorry. For example, in the editor I don't get any errors, but in the build I get a bunch of errors saying that an element from a dictionary doesn't exist. I am trying to change some stuff in the scripts because I'm afraid it could be just that in the editor one thing is being called before the other (and so it works fine), but in the build the order is different idk why
why and where the hell did you do that
() is not valid string sytntax
hmm. okay. I think it's probably type mismatch then. how would I problemshoot it... I have it declared as follows: "public Text dialogueText;" and that doesn't really leave much to confusion.. and the object is simply created from Create->ui->text.
you should know why, is your own scripts lol
start by sharing the exact errors messages, use the OnScreen Console asset if you can
in the place where you put floats and ints
is your component textMeshpro ?
or just Text
let me see
what..?
ahh, it's textmeshpro by automation. that's different to text, then?
indeed
What does that mean?
Just do this
string myTag = "FallingThing";
you would need TMP_Text
but also import the namespace its in
where i put these
public float Health = 100f; public GameObject Player; FallingThingScript falling; public float DamageFromFalling = 25f;
I was using the default unity development build😅 , I didn't know that thing existed
okayyy! nice nice! ty ty
Variables
well you seem to be trying to use 1 as a key in a dictionary that doesn't contain it
still error
Show code show error
yeah I can see that. The thing I don't understand is why in the editor works haha. But anyway I'll start debugging
Assets\Scripts\HealthScript.cs(18,19): error CS0029: Cannot implicitly convert type 'UnityEngine.GameObject[]' to 'FallingThingScript'
FallingThingScript is not an array and its not GameObject
yes
https://assetstore.unity.com/packages/tools/gui/in-game-debug-console-68068
might offer you more insight
okay thank you so much
yes what?
it's not a gameobject neither an array
right thats what the error is telling you
but i do not know the syntax to when reffering to a script
You have a list of objects. You need to get components from them
@solid verge if you want list certain component only skip tags/getcomponent altogether
https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
ngh. I changed it to textmeshpro+ importing tmpro... but it remains destitute in not allowing the drag and drop :C
textmeshpro+ ?
can you show ur exact code
What I wrote would certainly not give an error. So it's either something else or you changed it. You gotta show code for use to help more
Edit: dang lag. Ok, they are handling it with you! Looks good.
does GetComponentsInChildren<RigidBody2D>() give me an array for rhe rigidbody component of all the GameObjects Children or just one of the children?
all
including parent
Including Parent??
yes if parent has Rigidbody2D it will add it
parent as in the object that you called this on. not this object's parent
okay. Thanks!
wish there was an overload for skipping parent but hey can't have everything
yeah, sure. https://hastebin.com/share/efayujarol.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
nooo
thats the baseclass that covers all possibilities
yup
Tip: you can do full code blocks with 3 ` symbols so for example:
```cs
(code)
```
sholdn't for an entire long class tho
did you read this part
#💻┃code-beginner message
i did but i did not understand
which part
i guess everything
ok its very simple
FallingThingScript[] fallingThingScripts = FindObjectsOfType<FallingThingScript>();```
what doe the [] do
array?
yup
but how could it.
It defines it is an array of what is before. so int[] is an int array. someClass[] is an array of the class
no..
nope
array is a type
an array is a list
oh
can array contain just one thing?
sent that already
Microsoft is more correct. But w3Schools is easier to understand 🙂
they're both correct, microsoft one just has more examples (more array types)
man i'll just try and solve this tommorow
but yes its easier to understand
it can contain multiple things. but all the things has to be ofthe same type
thats because you're jumping straight into arrays without doing the basics of c# (this is one of them) but you build up to it
exactly..
i will come back here
you're trying to do a health thing without knowing the basic c# you're gonna have a harder time
i mean't that it started by just a simple thing
knowing the basic syntax/types is invaluable to doing anything
and another function that if health is less or equal to zero it is done for
with a loop that minuses the health until the health float is less or equal to zero
wait reverse the words cause my internet sent the second one first than the first one
Is IEnumerator with yield return new WaitForSeconds(3); a good solution for time based powerups or is there something better?
is there a function that is called right before switching scene or before the Gameobject is destroyed?
what type is Time.deltatime
Float
it works if you don't plan on adding pausing or saving
OnDestroy()
Oh, pausing is a good point. So the Coroutine would still run if i pause the scence?
ye, to work with pausing you would need a while loop that checks every frame if the game is paused
@solid verge One big issue I see is here
FallingThing = FallingThing.GetComponent<FallingThingScript>();
You apparantly have a FallingThing Gameobject reference, and you want to use that to get a reference to the FallingThingScript.
You could just change that variable to FallingThingScript and drag the object into there, then delete the line I copied above
Thank you! I will have a look on this
Me too. Dang
ah yeah discord just died there for a bit lol
Is there a way to have control over spawning with coroutine or InvokeRepeating. Like i say start spawning now until i say keep spawning and stop when i want and come back spawning again.. ? Or should i use a mix or other ways?
store Coroutine in a variable
you need a while loop inside coroutine for Repeating behavior
hmm ok
like that? cs myCoroutine = StartCoroutine(MyCoroutineMethod());
and stop like that cs StopCoroutine(myCoroutine); ??
yup
eg
while(true){
//Spawn
yield return new WaitForSeconds(seconds);
}```
Got it, thank you
having a dumbo moment. what is the proper way to see if a button is being held in new input system. Cant find it online somehow. is it context.started?
Also another question, is there a feature in unity to put a watch in the screen couting down the time? like 15minutes counting down to zero? Or it need to be done 100% hardcoded?
You can stop a coroutine yes. you can just have some bool keep track if you should be spawning at this moment and change the bool based on your logic. Then you can do your work in update instead of starting and stopping coroutines if you wanted
Is the "Invoke" timer running while a scence is paused?
like theres this but I don't understand how those are related to hold inputs.
check out .started and .canceled
okay, this works again. xd so I was trying to search data on that tmp_text workings, but all indicators tell me to use something else, like something specific to canvasUI texts. But then referring to those I get a type mismatch. I also tried the TMP somewhere, but it didn't work.
(alhtough I maybe did it poorly. google nor gpt was helpful finding that. the unity forums are down/infinitely refresh too)
so... trying to make a simple double jump... (I was using add force, but I guess I need to do something else first...)
I'm trying to make the midair jump ignore the character's current Y velocity and always make the midair jump uses the same up speed
On the new input system "holding" is not the same thing as in the legacy input manager. Basically in the new input system holding would refer to a button with a Hold processor on it. That's what performed is talking about here
reset Y velocity to 0 immediately before applying force for a jump
do I just type reset Y and done?
You'd start holding, started gets invoked. Keep holding until the specified duration, and performed is invoked. Release the button anytime, and canceled is invoked.
can you show which component you're trying to drag in the field ? and the screenshot for entire object inspector @nimble inlet
So if your hold is about "tell me when I start pressing down, and stop pressing down", then you want the started and canceled events
how do you reset only the y velocity? it wont let me do rigidbody.velocity.y = 0 (I also was trying to do jumps)
okay, a second.
what the f- is an object inspector. that's an object. it's the inspector. XD
you not know what inspector is in unity I suggest you start from the basics 😛
the inspector window. thats the hierarchy that you posted
there's also inspefctor window. multi image.
It's not the inspector
hu?
idk discord is lagging i only see 1 image
is there an attribute to hide a public field in the editor/inspector?
HideInInspector
it will still be serialized though
Oh..there's no thumbnails but you can click through it
Sure [NonSerialized] or [HideInInspector] depending on what you actually want to do
But - probably best not to use a public field in the first place if that's what you want
Huh, weird. Discord not doing too great today it seems
probably due to discord currently exploding. about 50% of my messages are even getting through right now because of it
what about the object you're trying it into
let's see..
yeah discord is dying rn
Its just for aestetic purposes. Variables that should not be set by human but still need to be accesed by other classes
That's looking for Text, your object is a TMP_Text
its still Text
okay how is that possible. :C it's literally defined as "TextMeshProUGUI" atm...
Did you save
did you save
TMP_Text is TextMeshProUGUI right?
100%
its the baseclass so yes
Do you have any compile errors?
there's some new ones...
If you have any compile errors, fix them
the compile errors make no sense. But these weren't here before I think, when things still didn't work.
I think it's saying I have a duplicate script of the same name...
Then you should probably listen to it
yep. I don't know when that got created. xd I deleted one and there's tons of errors now from that. good stuff :C
so I should add a holding interaction on my jump action. How do I access that in code (does the processor turn that into a held action automatically?). For example I want my character to rise with addforce while its being held then when let go the addforce stops.
alright... got it
Then you don't want the processor. See #💻┃code-beginner message
The Hold processor converts the button into a "raise no performed event until the button has been held down for X seconds"
so why would I need to add cancelled
To know when to stop adding force
can u make a parent inside a parent?
but how does that work with the if statement?
okay. there's only one error left and that's the type or namespace "image" is not found. code being " public Image textboxImage; in the previously sent code.
Is it image or Image
Image
bruh like a parent, in the hierarchy section
if context.started (addforce)
then what triggers the context.cancel (is it just if context.cancelled) empty block
Do you have the UI namespace?
no. added it. good thinking.
Any object can be a parent object of another, even if it already has parents
wow unity is so friendly. xd new errors only hiding behind old errors.
It doesn't. Here it'll only add force once, when you start pressing the button. Take what's in the if statement out and store it for later. Set a bool to true in that if statement. Add another if statement for canceled in which you set the bool to false.
Then paste your code in FixedUpdate, and only apply force if the bool is true
ty
I have managed to remove all the errors in compiler+vscode... I cannot still drag and drop the object onto that script.
Select (do NOT double-click) the script in Unity, in your project files. It should show its contents in the Inspector. Make sure it's identical to what you can see in your code editor
alr show new inspector of the Entire object, not just that component
should be identical
Is it
Ensure that it's the case
How about send a screenshot of your full unity window with:
- This object visible
- The console tab open and visible
something like this?
which object do you prefer to see in the inspector for this?
The one with the script that you can't drag anything into
behold my beautiful game
they don't matter no?
The one in the Inspector does
There is no script here
This is an empty script
🫠
oh snap, it got removed when I removed the duplicat.e
Yep, if you also want it to stop when you hold for more than 1 second
yeah
hey guys doing some coroutine tests, but it seems I cant do like that. any ideas?
||switch IEnumerator to Coroutine|| 🥣
What are the errors
that fixed first
but on stopcoroutine still got the error
The first error says you cannot assign a Coroutine to a variable of type IEnumerator.
The second says you can't call StopCoroutine on an IEnumerator.
StopCorotuine(coroutineVar)
the errors tell you exactly whats wrong usually xD
I did a reserach and said I had to use private Ienumerator myCoroutine;
for me as NB not always is that obvious 😛
true, when in doubt always look at the API/return type of the function
Thank you
StopCoroutine has 3 types as params btw
Coroutine is the return here
for stop you can pass IEnum but you already stored as Coroutine
oh wow
interesting..
For now I will stick to the simple method as I am starting, but already took not of those to check it out later. thank you a lot
Another question, to create a count down timer like 15m showing on the screen 15:00 until it gets 00:00. need to be hardcoded or there is a feature on unity for that?
you need to make that timer yourself
ok thank you
update the UI text
with time.time or something like that?
ok hear me out
i have 2 scripts
A: For the boulder, which tells it how it can move n whatnot, boulder is now a prefab as well
B: boulder spawner, if u press space it will run a method in script B that spawns a boulder
however i am having a bit of trouble with this, im not quit sure how to build the spawner method
Currently, i just have
no Update or another Coroutine just for timer
what you can do is put it in the same while loop if you want if its related to that previous coroutine
you should not be calling the constructor for a MonoBehaviour
hmm ok, will check it out doing a research on it. thank you
https://unity.huh.how/runtime-errors/monobehaviournew
or use Instantiate to spawn an instance of the prefab that is referenced by your component
oh ye Instantiate
used to working with monogame
For a timer, I often use a variable of seconds representing the total time I want (for example 60 * 5 would give 300 seconds), then you can tick those seconds down with navarone's suggestions, and display those seconds as detailed as youd like to some text object (days, hours, minutes, seconds, milliseconds, etc) - though for this approach, you may need to do some math on the seconds and possibly ToString formatting, as the math will result in decimals more often than not
Got it, thank you very much !
What is Catapult_boulder
It takes a variable, not the string name of a prefab
You have no variable named Catapult_boulder
Im using object pooling of two different objects, when the game starts the its objects pools 8 of the first object and when i press a button it then switches to objects pooling the second item, but the transition of making the 2nd active and 1st inactive causes lag spikes on android. There are some scripts on the objects but when i check the profiler there is no certain script thats causing the lag drop, what can i do here?
i think you need to check profiler to see what the program IS doing during the lag spike
if the cost is being distributed very evenly, check for things that shoukd only be called once to see if they are called multiple times
how many objects are you pooling in the 2nd pool? this sounds weird to me, that you are making a pool inactive and making another active. An object pool is just a place for inactive objects to live
its one objects pool but at the start i only make active the first one, then when a button is pressed, hide the 1st and show the second. its all the scripts on the second object starting all at once, what can i do to make this transition smoother?
what you are describing (and the screenshot) makes me think this isnt actually an object pool. Is this Tile_Forest and Magic Forest thing your scene objects? What are they
they are both objects for my background in the second screen shot, when i press a ui button they switch. I can link the code where i object pool them
Yes show your code, i am very convinced right now that this isnt actually an object pool
This sounds more like additive scene loading, but with prefabs
hold on discord limit
!code
let me pastebin it
📃 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 do i reference the perfab
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Make a variable and drag in the prefab
public GameObject boulder;
sorry its a lot of code but its really just the first 3 mehtods
honestly i got no idea what part im supposed to be looking at, but u can profile certain sections with this
https://docs.unity3d.com/ScriptReference/Profiling.Profiler.BeginSample.html
can you elaborate on
Make a variable and drag in the prefab
Drag in... where?
The inspector
If you have a public variable. There will be a box in the inspector. Drag it into there
See the boxes in the left image here
#💻┃code-beginner message
It will be like that (but yours won't be an array or list or whatever they have)
yeah i get it but this is the object pool
private void Awake()
{
coinSpawner = FindObjectOfType<CoinSpawner>();
objectPool = new List<GameObject>();
// Fill the object pool with all objects from the prefabs list
foreach (var prefab in prefabs)
{
for (int i = 0; i < maxObjects; i++)
{
obj = Instantiate(prefab, new Vector3(currentX, 57.41f, 25.19f), Quaternion.Euler(0f, 180f, 0f));
objectPool.Add(obj);
obj.SetActive(true);
// Activate only the object at index 0
if (prefab == prefabs[0])
{
activeObject = obj;
currentX += spawnOffset;
obj.SetActive(true);
}
}
}
// Find all SpawnerScript instances and add them to the list
SpawnerScript[] foundSpawners = FindObjectsOfType<SpawnerScript>();
spawners.AddRange(foundSpawners);
}
this still looks more like additive scene loading but using prefabs, instead of an actual object pool.
Also for some reason you've now changed it to set every object to true on awake, while in the hastebin it was obj.SetActive(false);
yeah im testing different ideas
If these prefabs are massive, then yea its gonna take time to set them active/inactive. Your solution in that case is to make them smaller
can you show the hierarchy of this prefab
i sec, yeah its pretty busy but idn what to reduce
You can either go through the giant prefab and load objects over time instead of trying to do it all at once
break them up into smaller prefabs then load them slowly
use additive scenes instead with the same concepts above
Quaternions represent a rotation. You really don't need to know what W means. But if you want you can look up the incredibly complex math of quaternions.
In game dev you should just work with euler angles though. The x y and z will NOT be what you see in the inspector
Hey, guys! I have a question. Can I pause and unpause my game on IEnumerator? On my game, I have made pause menu screen to be enabled and disabled with a time delay. That's why I made everything on IEnumerator. So, I want to freeze the game and unfreeze after unpausing. Can I do something like that insdie IEnumerator?
Check my code
{
if (Input.GetKeyDown(KeyCode.Escape) && pauseIsActive == false)
{
yield return new WaitForSeconds(pauseDelay);
pauseIsActive = true;
pauseMenuScreen.SetActive(true);
Time.timeScale = 0;
Debug.Log("Pause menu screen is active!");
}
else if (Input.GetKeyDown(KeyCode.Escape) && pauseIsActive == true)
{
yield return new WaitForSeconds(pauseDelay);
pauseIsActive = false;
pauseMenuScreen.SetActive(false);
Time.timeScale = 1;
Debug.Log("Pause menu screen is not active!");
}
}```
its seems like alot but i only have 2 scripts and everything is low poly, every material is using shared instanced
bad
I have a problem with Time.timescale
https://docs.unity3d.com/ScriptReference/WaitForSeconds-ctor.html
Suspends the coroutine execution for the given amount of seconds using scaled time.
why do you have Inputs/keycode inside this function
yeah also shouldn't be getting input in there
you would use WaitForSecondsRealtime if you want to wait for realtime to pass while the time scale is 0
🤷♂️ then start profiling which section of your code is specifically bad. If you're convinced its not the prefab loading, then what
I thought, I could use input inside it and write StartCorountine on Update() that's what I did
Anyway, I will fix it
you're like starting a coroutine each frame,
Oh, true!
how come?
As it says GameObject doesn't have a FireProjectile function on it
so you can't call FireProjectile on a GameObject reference
you're also trying to call it on a prefab which is sus
So what? GameObject still doesn't have such a function
bool isGamePaused = false;
Coroutine pauseRoutine = null;
void Update()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
if (pauseRoutine != null) return;
pauseRoutine = StartCoroutine(PauseGame());
}
}
IEnumerator PauseGame()
{
isGamePaused = !isGamePaused;
if (isGamePaused)
{
//dostuff paused
}
else
{
//dostuff not paused
}
yield return new WaitForSecondsRealtime(wahetevr);
pauseRoutine = null;
}```
the prefab had a script which had it
you should do some basic c# courses to learn how types work
Well, you're referring to it as a Game Object only
you can never call FireProjectile on a GameObject reference. If it's from some script of yours you should be using that script type, not GameObject
Refer to it as the specific script, if needed.
i tried typing out the name of the script
but it makes it green, so it refers to the class
That's what you want...
GameObject is a class too you know
public SpecificScript ss;```
or no it says this
yea thats what i did but then i got confused
you're using the class name there when you should be using the field name
notice how you did myBoulder.FireProjectile()
not GameObject.FireProjectile()
Maybe lookup some basic C# tutorials 
you're confusing the type of a field with the field itself.
another good reason class name should be Capitalized so you know its a class and not the field/reference
bruh i was afraid to change class name cuz the class name has ot match the script name n i didnt wanna change naything
otherwsie id have capitalized class names
if you rename the class in VS iirc it also renames the file
ctrl + r twice tho
i see
So change both
see it says Rename symbol's file
not sure why its called symbol but wahetv lol
how did u get this little menu
A Symbol is what the name of a thing is called. int x = 3, x is the symbol that represents the variable
oh damm I feel silly not knowing thats the name
xD
Variables, properties, classes, methods, and structs all have "Symbols", so you can use that when you don't know or care which one you're talking about
click on the thing and do ctrl + R twice
ir right click + rename
ohhh nice TIL
box was already ticked
So then when you rename the class it'll rename the class's file
yup that means it should rename the file too
When you hit enter
It is immediate
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
thats weird isn't raycast hit a struct
just use else for that second block instead of checking if hit.collider is null
Im getting the following error, I know it is probably simple to fix but for the life of me I cant seem to fix this
When you are done typing
You use hit in another method (WallDestroy)
Hit is declared locally though
structs are only assigned their default values automatically when declared as fields. local variables can still be unassigned
if (hit.collider == null)
What is this checking if the raycast hits nothing
and uhmm is there a chance or something that could contribute to it not working?
hit doesn't exist
Ahh I see
What doesn't work
if it DOESNT change the symbols name
after enter
also i clicked on something n it looks like this now
Rename it back to the same thing it was before. Then rename it again
the boxes r gone 😔
worked 👍 '
you can also do new() I think
that would still make no sense though cause nothing is assigned to it
not even necessary though. they can just use else instead of that second if statement. since checking if hit.collider == null is the same as checking that the raycast didn't hit anything
yea makes sense
but yeah assigning either default or new() would technically solve their error
The issue is using it in WallDestroy without it being a class variable. That's where line 34 is
But yeah, else would make more sense there
is this rayhit even supposed to be local?
No, definitely not
yall am i a game dev? 🙏
technically
im making it out the hood
not if you forget to save when its * on filename
after that transformation is complete
ah yeah, my bad got the lines mixed up (though the issue i was pointed out is basically the same). they should just be calling Walldestroy from their objectfind method instead of from update. then they can pass the raycast hit when the raycast is successful
Why do you have boulder and myBoulder? Wouldn't it make more sense to just spawn boulder?
yeah that GameObject is useless here
Yeah this makes sense now idk why I didn't think of that, also changed the null to else instead
hmm true
or wait
also you would change GameObject to Boulder in the instantiate
dont i need it to be GameObject to Instantiate
ohhgh yee yee
what happens if i replace Boulder spawnedObject with boulder
You'd store the result of Instantiate in your variable boulder
yeah ideally you'd have a second variable of that type (probably one that is not public) that holds the reference to the instantiated object. assuming you'd want to be able to instantiate a boulder more than once with this class
hmm i think i get it
its like taking the balue print and making an object out of it and assigning it to a variable, if i assign it to the blue print then the blue print is gone and i just have one instance?
I thought I got what you meant but apparently not, would you be able to show me what you mean by this?
do you know how to pass an object as a parameter to a method?
I think so yea
so then what part of what i suggested are you not understanding?
soo.. i dont really get this
i want rockSpawner to be a part of the catapult_1 parent
can I not access this value onEnable? its giving object ref error
Double click the prefab to unpack it
Modify it there
SMM.instance is probably being assigned to in Awake. don't access its value until Start
Most likely this is running before instance is assigned.
Okay actually I misread your message how would I do this?
ah i see TY
hmm i think its best if i just delete the boulder, then in the script have a way to spawn in the first boulder
if you do not know how to pass objects as parameters there are beginner c# courses pinned in this channel to help you start learning how to use the language
however, evenm if i wanna move rockSpawner to that parent it still gives same error, even tho it is not a prefab
right click the prefab and click Unpack
then you can modify it
Catpult_1 is a prefab..
hmm hmm
Catpult_1 is a model/fbx
Catpult_Stone_1 is prefab
unity treats model files as prefabs its weird
Oh yeah, you right. Just saw a big of blue and ran with it haha
yeah lol they should've really made it a diff color
Thanks, I did this stuff years ago but I've almost entirely forgot alot of important stuff so I'll definitely need a recap of basics
ok so i unpacked the prefab, added the rock spawner, then made it a prefab again, but the movement script doesnt make the rockSpawner follow
wdym the movement script?
btw always keep ur console window docked somewhere where its fully shown
the parent has this script
Don't use new Rigidbody
Don't create any unity components with new
is Moving Forward printing
stop newing components
what you really want there is just a reference to the Rigidbody by dragging it in the inspector
^this also swap from translate to rigidbody based movement
cleaned up the script i didnt need the rest
just so you know, your movement does not respect colliders
so the object will not collide with anything
wait nvm i do need hte rigbibody so i can use rigidbody based movement
quick question how can I spawn the same object at 2 points
duplicate the line & change pos on second?
call Instantiate twice where you provide one of the relevant points each time
Spawn it in one place, then spawn it again at a different one
my bad i also want the two points to be used randomly if that makes sense?
you're gonna need to elaborate because that can be interpreted in a number of ways
Spawn it in one random place, then spawn it again at a different random one
for example if I had point 1 and point 2 I would want them to be used randomly
aight less go gang
public Transform[] spawns;
private int spawnAmount = 2;
void Spawn()
{
for (int i = 0; i < spawnAmount ; i++)
{
var instantiate = Instantiate(obj, spawns[Random.Range(0, spawns.Length)], Quaternion.identity);
}
}```
whats the best way to learn?
practice / lots of repetition
you should also not be applying physics like AddForce inside of update, do that in FixedUpdate. also when you make that change remove the deltaTime multiplication. and you'll likely want to use ForceMode.Impulse rather than the default forcemode
there are beginner courses pinned in this channel
and the pathways on the unity !learn site are good
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
do i keep the rotation in fixedUpdate too?
nope, rotation is too slow then
but then.. should i just buff the speed or put it in Update? 🤔
i have a feeling that Update has to be blue
rotation you want rb.MoveRotation
also nesting Update inside FixedUpdate is wrong
Update never gets called there
Vector3.forward should be transform.forward
dam i didnt even notcie i did that
makes sense
i did think about it
that it had to be based on rb
you technically can still use transform.rotate but the inaccuracy might be significant enough
well when it stopped working after a few changes so
📃 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.
what does the last arguemtn for Quaternion do tho, i understand the first 3 are the rotation around the 3 axis
ye but the code isnt long enough for it yet, i think so at least
wdym Quaternion has 4 values (x,y,z,w)
like myRigidody.MoveRotation(new Quaternion(rotationSpeed,0 ,0 ,0));
it is asking for Quaternion
The first param is the x value, so it would make no sense to put rotation speed there
yup that one
well i mean it did work before
?? Doubtful
its not rly rotaiton speed, but how much it should rotate with
maybe my naming is bad
quaternion value don't go above 1
so it would never work
Each value of a quaternion is the TWIST around an axis. I guarantee it is not what you think it is
oh i had 0.05 - 0.4
i... did think right 😢
The reason it worked before is because transform.Rotate can take in a Vector3 as arguement, if you want to use eulers
it has different signatures
moverotation doesn't have Euler (only accepts Quaternion)
Did you think it would match what is in the inspector for rotation?
uhhh wdym by inspector for rotation
Do you know what the inspector is?
Which part is throwing you?
not exactly
It's the window on the right be default, with the word inspector above it. It has all the values of a game object. Like position and rotation right at the top.
I recommend taking the Unity Essentials path at learn.unity.com before proceding further
this would be example of euler
same rotation in quaterion
but you can move it to the left side!
Or you can turn it into oblivion and not have any inspector tab at all
Who needs it anyways
make custom inspector, win
Or just make your own game engine
I want my fields to have analog guages
you still aint share the new modified script
cuz it had an error
which i was trying to look up
but the explanation to it dont really sit with me
why are you using new
Quaternion.Euler returns a Quaternion
and are u sure X is what you want to rotate instead of Y
It's not a constructor, it's a static method, no need for new
uh... yea..
..?
always. because it rotates around that axis
yaw?
Y rotation in unity is yaw
this should also be helpful where head is the yaw in this image
i dig it
yes. though you won't be correctly accumulating your rotation there if you're using MoveRotation
unless this is in FixedUpdate where it won't really matter if you accumulate it or not
it should be * Time.fixedDeltaTime if in FixedUpdate to be degrees per second, and is just incorrect if in Update
maaaann..
cant even say bro
anyways, it no longer knows where forward is
its movement is no longer based on the rotation
and its 12:14
i have yet to do things
that i needa do
😔
this has been a lil humbling and wee bit disapointing
bro speaking in riddles
Because you should probably try to say something actually useful
Think I have got it, tried to remember on my own took a bit but think I got it its not throwing any errors although correct me if I am wrong here
did someone give you the impression gamedev is easy ?
teacher said that we technically should only need 15 minutes... i spent like 6h+ now... and didnt even complete 50%
how is this is even possible 😭
15 minutes to what exactly ? whats the assignment..
its just an exercise, we just gotta make a catapult shoots balls
and add more stuff if we have time
no sane teacher would say any gamedev would neeed only 15 min
its possible but why, would you
this is a stupid question but is there an opposite of the random class
Sounds more like a 15 minute assignment after a whole class/classes and someone slacked off.
now the next thing i recommend changing is perhaps to not rely on the object's name but rather a tag or even a specific component. Then if you instantiate a clone of the Wall object that clone will also be affected without you needing to make sure you rename it
🤨
quite possible xD
idk teach lowkey chill
Ah yea true
wtf would be the opposite of that?
yea ngl i cannot focus to save my life
opposite of random class? whats that even mean
i did learn... some things..
Well then, to answer your question: it is possible.
i dont think anyone managed in 15min
Using AddForce to launch a rigidbody is only a few lines of code. It really is the basics of Unity.
but most of em were almost finished after like 2 - 2.5h
yeah but they're doing like rotating a catapult and all that
not sure if thats part of the assigment or what
what are you trying to do here
Random is not a function
Just realised I get this upon play
i think u need random,randint
i dont what random data
but what class would i use
then why are you doing anything with a class called Random?
pass specific values?
what do you want?
oh right, you should only be calling your Walldestroy method if you actually hit something with the raycast and pass in its raycasthit, not just a new one
for what?
Then don't use random...?
Ahh got you
thats like saying I want to cross the street but not blindfolded
alright what function or class could I use to use fixed data
here is what i meant earlier by it no longer knowing hwere forward is
the... the data you want
what do you mean? just use the data
use that
maybe static data like ScriptableObject
please share your !code correctly. nobody wants to scrub through a video to try to decipher what you are doing
📃 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.
i told you earlier how to fix this
i see
just use AddRelativeForce or that fix
So that should be inside the if statement here like this yeah?
wait i already did this
you read the wrong thing
why are you calling it with a new RaycastHit()?
now use the already populated hit variable rather than constructing a new RaycastHit
Meant to change that oops
The number 1. It is known and doesn't change. So kinda the opposite of random?
alright guys sorry for the difficulties i figured it out
Alrighty thanks
the vector3.forward is World dir
transform.forward is local dir
or what Boxfriend said instead
👍
Thanks man thats it working, appreciate the help!
dam why it slides so much
dam there is so much wrong still
makes sense now how game devs be staying up til 3
what did i get myself into...
anyways ill have to hit the hay now, thanks everyone for your pateince today
ah was the AddForce supposed to move the catapult rather than launch the boulder? because if so you should remove the ForceMode.Impulse parameter from that call
oh and you'll want to make sure that your rigidbody has drag and friction otherwise it will just slide forever
private void OnCollisionEnter(Collision collision)
{
if (other.TryGetComponent<Walls>(out Walls walls))
{
Debug.Log("Hit wall")
}
}
this is my code, I have an empty object called 'Walls' with the children as all of the walls of my map, why am i getting this error?
The type or namespace name 'Walls' could not be found (are you missing a using directive or an assembly reference?)
Do you have a class called Walls ?
Object name is irrelevant here
I dont have any code for my walls, they are kinda just there
What is Walls
Ok, then that is why
You have no component called Walls
you cannot use a type that does not exist
If you want, sure
We often call that a "tag script"
Are there better ways?
Tags
Having the Walls class actually DO something...
But you only get one of those
like maybe use the OnCollisionEnter on Walls
How would i access the Unity Transport Bool Allow Remote Conneciton through a script cant seem to find it anywhere
what ?
Can someone explains to me what is Wwwform class? I still dont get it, is it creating an temporary form or generate form data to a server
it's an object that will wrap the data up and send it to the server (via UnityWebRequest) in the same format as an HTML form i.e. application/x-www-form-urlencoded
Gotcha, thanks! 
hello, I'm trying to bind an Event for this PlayerInput (from Input System: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.3/manual/Installation.html), but I'm not seeing the public methods of another script that's attached to the same object that PlayerInput is attached to. is this a bug?
you dragged and dropped the script (from your project files) instead of the object that has the script attached to it (from your scene/prefab)
😌 Oooooh thank you so much! @wintry quarry
I have a basic player movement script going so far and I aim to incorporate a double jump. I believe i've set up my logic correctly yet I can still jump infinitely. Can someone help me and point out where I went wrong?
you should really avoid variable names like dJ. it makes it like impossible to understand
Sorry, kinda forgot other people might be seeing this so I just used variable names that made sense to me
you should also use better variable names for yourself
the most likely person to read your code is yourself several months/years in future, when you no longer remember wtf you were doing
You're probably right, i'll work on it.
i recommend splitting jump check from executing jump
jump function should just be in charge of executing a jump. not checking logic to see if a jump should be possible
single responsibility principle, especially since those responsibilities might become more involved
Good point, should I just keep them in the update function instead?
your isJ bool isn’t being changed when you call jump
I would. Or make a separate function to check, so Update can be slim
Update in movement scripts tend to get really busy, so you want to be super organized
Why isn't my variable being changed? My single jumping was working, but then I attempted to add a double jump and thats when this started
because bool is a struct
it is copied
you send a copy of it into the ground check method
you change that copy
original stays unchanged
*value type to be precise
i cannot stress enough how much 1-2 letter variable names are cancer
public struct Boolean
Is there any way I can pass the isJ variable into the function and have the actual variable be updated and not just the copy?
don’t use ref
GroundCheck should return a bool.
isJumping = GroundCheck();
which also makes it obvious why that line is wrong
because you should not be setting isJumping to a value depending on ground when you know you just jumped
player state should also be an enum
i think he’s gone now
Can you elaborate?
I can always send some guy's BulletLogic function which contains all the functionality, and hit reg all in one massive function, multiple nested loops, string comparison, and two letter names. 
That sounds like aids
It's a code from a flash game when he was pretty new to it.
Im actually curious now. Do you have it? I'd love to see it
Sorry for the late ping, just saw something in your code, instead of using GetComponent(typeof x) as x you can just do GetComponent<x>()
ActionScript, TypeScript but the safety isn't imaginary guardrails, it actually exists. 
ahh that's much better. thank you vm @silk night
I need a longer screen.. that nesting..

Please tell me that is autogenerated and somebody didnt lock their dev into their basement until that was written
It's also decompiled code.
But I'm not sure why the loops turned into a while loop with the index outside.
I'm not perfectly sure if it's actually built like that to begin with.
in grad school, i inherited code for a tribometer that was like that. one letter variable names. highly technical math from an obscure paper on highly specialized machinery. Over 2000 lines of code, with the only comment being one random comment with a paper citation
We gave up and just told our PI “yeah, the machine isn’t going to work.”
Yeah thats why i understand the variable names, but the nesting doesnt suddenly pop into existence when decompiling something 😄
PlayerState enum with values for Jumping, Grounded, DoubleJumping…
this way you don’t handle a bunch of bools that should be mutually exclusive
I'm sure with the nested ifs though.
He definitely didn't want to use AND since he used both AND and OR sparsely around so it's not just the decompiler.
Oh, okay, thank you!
my issue was that we didn’t understand the math since we didn’t understand wtf the variables represented, nor their units
if we knew the units, we could try to infer what they meant, but no dice
Sounds like he converted the research paper into code. 
Also they bought that reason?
it was true
i was the most computer saavy guy in the lab. if I say “it’s not happenning”, then it is simply not happenning
in the land of the blind, the cyclops is king
the enjoyment of the biggest fish in the pond
Sorry to be back here, but how would I check to see if I can double jump or not? I've tried almost everything I can think of, and I cant seem to get it.
Updated Code: https://gdl.space/eluzexegel.cpp
Do you know that you can modify class properties in method?
Yeah, is the answer simple and im just on the spectrum?
Have an int. When you jump, add one. If it's less than 2, you can jump again. When you are grounded, set it to 0
I thought of that, but thought it would just add more variables to my code when what I had would suffice.
Ah, you have a doublejump bool
So use that?
You have a doublejump method too?
I feel like this is way more convoluted than an int
Thats the goal, i've tried using that almost every way I know how.
I would get rid of that and the doublejump method and just make the jump method add one to an int.
Make it much more simple and clean
Yeah, im not the most experienced
Wait, also do you have compile erros? Your Jump method has an isJump bool (why?) but checks isJ
Why does the GroundCheck method have a bool passed IN?
No, I changed that before posting to try and make variables more clear and guess I missed one
Ah ok
It was mainly used for when I had my double jump boolean as well as my normal jumping boolean so I could set each one with only one function
very inefficient though
how do you check if callbackcontext is null basically? I cant do context.cancelled for reasons.
(couldnt find anything online that worked)
why would it ever be null?
What are you trying to do
btw it's a struct so no it can never be null
so im jumping and when I let go of jump, I was trying to check for when it was let go (or no input). but I cant use context.cancelled because they are on different scripts. the jump is actually started from onenable but what enables the jump state is the jump input on another script
but I cant use context.cancelled because they are on different scripts
This doesn't make any sense at all
lol im sorry
do your input handling as needed, using canceled to detect when the button is released
communicating that with another script is a separate concern
I feel like you just... want ctx.canceled.
When the one script gets that callback, send that information to the other script
Subscribe the other script to the event when it is enabled
And a disabled script can still accept and run code. Just not run Update and (unfortunately to this situation) receive input callbacks
what does scripts being enabled have to do with anything?
apparently nothing
enabled only determines when Unity callbacks are run on your script. You can call functions as you please regardless of the enabled status
unity events for input wont run from a disabled object though right?
hopefully that made sense
If you're using the PlayerInput component I don't see why the object it's attached to should/would ever be disabled
PlayerInput is 1:1 with a human player
yeah i mean the object you plug into the events
that's not relevant at all then no
It will still run functions on a disabled object
that ruins my state machine then? (not asking like you know)
Is that a question or a statement?
all these objects have scipts that do stuff on the playerinput component. youre saying they are always running the callback context in their functions?
wdym by "running the callback context"?
they each have functions that accept callback context
and theyre running while the opbject is disabled according to you?
If you mean that you've assigned functions on them from the PlayerInput component inspector unity events, then yes
they will run
assuming the PlayerInput itself is enabled / active
Are you sure? I thought that they would no longer receive the callback event if the script was disabled. Someone said they tested it, but I did not yet
Well now you're all making me question it haha
But C# events definitely don't care
I guess its possible UnityEvent checks but I'd be surprised
naturally the docs are silent on the matter
trying to test rn lol
considering objects can be enabled from unity events, i don't think them being disabled is going to prevent anything from happening when the unity events are invoked
and you can still call methods on disabled objects, it's just certain unity messages are prevented like Start, Update, and FixedUpdate
yeah looks like it runs while disabled fml
you can just check if its enabled
u right that will prob be easiest ty
ty for the help Im still not sure on the context for my first question but I need to fix this right now
so for this why cant I use gameObject.isActiveandEnabled. it only lets me do this.
in the docs they say it checks a GameObject
gameObject doesn't have that property naturally because it doesn't make sense
not sure why you would want to use gameObject
oh good point im not supposed to be using the current object (wait yeah I am lol)
whoops
I didnt know anything about new input system, but why the fsm is in forms of gameobject
my medicines worn off dont flame me😭
its fine, convenient way to represent and work with fsm
only problem is that if the hierarchy with it is moving you are adding pressure to the scene graph
adding a debug panel is easier for me…..less gameobject needed but your scene will be mess
how do i reference classes defined in separate scripts?
do i have to have a reference to it or something>?
yes, you must get a reference to an instance of a class in order to interact with it
Text is a legacy type of component you
tyty
How would I grab a refrence to an asset from its path?
tyty
when using CreateInstance for a scriptable object, does unity actually create an asset?
or will it get GC'd after runtime?
ok cool, so I can use createInstance and createasset separately without issue
it can be a way to leak, because any unity object represents native resource which may not be cleaned up until you call Destroy on it
would calling destroy on the reference to the SO after its been created as an asset destroy the asset?
all my code uses AssetDatabase.DeleteAsset for that i guess it will just throw if you try
i imagine i would be like - destroy instance in memory, see it still serialized on disk, reimport, instance created again but ref invalidated, invalid state
gotcha, I was only asking since you said that it could cause a memory leak, that if it was because there was a version of the SO in memory and in storage that I would possibly need to clear the one in memory to prevent any problems
any SO that has backing asset is in essence bound to that asset, unbound instances are "unmanaged" by unity, so their lifetime control is on you
ok, so would this be considered bound or unbound?
AssetDatabase.CreateAsset(attackSO, "Assets/Custom/Player/Combat/" + item.name + ".asset");```
bound
wonderful
unity will associate now this instance with the .asset
people use SOs for runtime representation as well, cloning or creating in place for various use, so i mentioned the general leak possibility
I was able to get it working, thanks so much for all the help you are a life saver
actually one more thing, I tried to use CC's like you suggested and wanted to make sure I'm using them correctly, does this look good?
||I know "no screenshots"||
if thats inside Editor folder you dont need the guard
DEV_Build is actually super nice to know tyty
oh I didnt know that you needed to make the folder lmao
you dont need but you can and should
it will automatically compile everything in it into editor assembly
I definity will add that rn
folder can be anywhere and you can have any number of them
same as Resources and Plugins
How do you usually handle NRE's that happens when you stop playmode, is it good to be ignored?
does that NRE's even happen in the actual game?
With defensive programming
Generally you shouldn't have any NREs in any circumstances
are those NRE's or "destroyed but still trying to access it"?
yea that thing
check for null before accessing references which may be null (or destroyed in this case)
that means if (thing != null) checks in your OnDestroy and OnDisable code
public static bool IsNullOrDestroyedSilent(this object uobject)
{
try
{
return !(uobject as UnityEngine.Object);
}
catch
{
// swallow the exception
}
return true;
}
``` hacky way to get around that
it's just annoying to have to check them when they are meant to be like always active :<
all objects in the scene are destroyed when the scene is unloaded
disabled first, then destroyed
they're like permanent thing, but closing the game breaks the rule
isnt try-catch system more expensive than the normal null check?
yeah, if it throws
!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.
Mornin' all. More adventures in gravity.
Would someone be willing to take a quick look at this and give me any pointers please?
I'm basically changing the gravity vector on the fly to simulate planetary gravity (spherical world etc)
I'm using a rover as an experiment, I have the driving around the planet etc. all sorted and working.
The part i'm interested in is.....
roverMass = roverRigidBody.mass;
float gravityForceOnObject = roverMass * gravityForce;
roverRigidBody.AddForce(-gravityVector * gravityForceOnObject);
what I'm now trying to do (that will be applied to a ship object later when it's working), is to counteract the gravity, so that my eventual ship will 'hover' automagically. I think I have my gravityForceOnObject calculation wrong because currently instead of hovering, the rover just flies straight up (although in the correct direction).
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You're multiplying gravityForce into the force twice
Once in the first gravityVector calculation and again in the gravityForceOnObject calculation
Oh....of course I am. So the gravityForceOnObject is completely redundant? lol.
The canonical way to counteract gravity would be:
rb.AddForce(-Physics.gravity, ForceMode.Acceleration);```
Note that in a game with custom gravity directions using Physics.gravity is probably not going to work out for you since it's global
Aaaah, okay. Yeah that makes sense. Sorry, tend to glass over a bit when it comes to physics stuff. lol.
Usually custom gravity through AddForce is in the cards
Can you add a seperate artifical gravity to your objects to countteract?
How do I pass stuff like GameObjects into FSM scripts?
I haven't implemented it on this specific script yet, but the gravity 'range' is limited for each planet (ie, big ass trigger that turns it on and off for each planet with their own vectors and strengths.
As parameters to functions or constructors
cool
Hmm. Okay, so doing this had the same effect, the rover just goes straight up. I'll keep plugging away at it. lol.
Show code
void Update()
{
gravityDirection = currentPlanet.position - transform.position;
gravityVector = gravityDirection.normalized * gravityForce;
Physics.gravity = gravityVector;
roverRigidBody.AddForce(-Physics.gravity, ForceMode.Acceleration);
}
You're calling AddForce in Update
AddForce should only be called in FixedUpdate