#💻┃code-beginner
1 messages · Page 214 of 1
yes,cause by default unity also if there is not a script behind calculates the collision between the 2 objects
2D or 3D
3d
so collision has an impulse property, apply the inverse of that
the problem is another
when player1 collides with player2,it is like player2 moves also if there is not a script behind that apply a force
of course, physics is physics, scripts are irrelevant to that
ok,is there a way to deactivate the deafult physics and move player2 just with a script that apply the force during the collision?
you want to alter the standard behaviour of physics you need a script
Make it kinematic
then no collisions
After the collision you could no?
can you explain better? (i know what kinematic is)
physics has already happend at that point
Collision > make it kinematic > handle the logic however you want > change it back?
when you make it kinematic you can no longer use force
the problem is that when an object is kinematic if i try to add a foce via script it doesn't work
oooooh i see
how can i do without collisions?
But you don't want the physics engine to actually do things to the object right?
yes
you cannot, that was a reply to the kinematic suggestion
Why not just set the velocity and anything you want to ignore to 0 then do your logic?
i don't really understand you idea
Well from what I understand, you basically have object A colliding with object B, but you don't want object A to do what it would normally do. Kinda like stopping a rubber ball from bouncing when it hits the ground. Naturally it would bounce, but you dont want it to right? So why not just set the velocity to 0 (or basically "reset" the consequence of the collision), then do your logic to do whatever you want to do to Object A?
Or skip the "reset" thing and just do whatever you need to do with with object A on collision
hi, i'm working for a game and i build it but when he can't open it i think is because he don't have open it
what can i do??
because for famous game we don't have to install unity
I understand your idea but it would not work in my case
anyway maybe i found a solution
This isn't a coding question. If you make a build, make sure you send everything it puts into the folder. No you don't have to install Unity to run a build.
var newCard = Instantiate(_handCardPrefab, transform);
If transform has the HorizontalLayoutGroup component, does the game object know its "real" position? Because the inspector says it's 691 -156, but if I print the position, it always yields (652.93, 0.00)
k thks
what are you printing
thing its displaying anchored position in there
transform.position
yeah since this is UI, you might want to get the rect transform
can use GetComponent for that or cast transform
_rectTransform = (RectTransform) transform;
Doesn't transform get a RectTransform for UI game objects?
its the same object, but because you are viewing at the type Transform
you can not see all of its properties and fields
such as the anchored position value
private Rigidbody2D[] childRigidbodies;
// Toggle the Rigidbody2D components of all children
foreach (var childRigidbody in childRigidbodies)
{
if (childRigidbody != null)
{
if (animatorEnabled)
{
// Set to static if Animator is enabled
childRigidbody.bodyType = RigidbodyType2D.Static;
}
else
{
// Set to dynamic if Animator is disabled
childRigidbody.bodyType = RigidbodyType2D.Dynamic;
}
}
}
}
}
}```
im trying to write a script that toggles all the Rigidbody2D body types of the children of the parent object between static and dynamic but it's also toggling the parent objects Rigidbody2D, any ideas on how to avoid that?
You're toggling every rigidbody in childRigidbodies. If that array contains the parent then it will change the parent
any way i can exclude the parent object from that?
Don't put it in the array
Okay, so it seems I found the issue:
The first image is the instantiated object that has its position at 158, -531. The second, which is almost the same position as the other object, however, is at 633, -156. it seems they use a different position system. How do I convert one into the other?
The hierarchy is like this: "Drawn Card Prefab (Clone)" is instantiated and a direct child of the Canvas. It's anchor is in the middle of the screen. "PlayerCardContainer(Clone)" is the child of a horizontal layout group
how?
Instead of putting it in the array, don't
how do i chose what to include in the array?
How are you adding things to the array
im not really sure how it works actually im just following a tutorial its not very clear
Then you're going to have to find out
thats why im here
When you add something to the array, don't
If it is an array returned from a method, loop over it and remove the thing you don't want
We can't help without knowing though
You have to figure out how it works on your own, or at least walk us through it as you understand it.
You could mark the parent with a tag and compare the tag of each gameobject when looping the array
You could also just make a child object that contains the Rigidbodies you do want in the array and put that script on the Child Holder Gameobject that way when it loops it will only get those children and not the parent
I've got this script to make the enemy detect the player when they can see the player, but the enemies are able to see the player through walls (Ground Layer). Does anyone know what I'm doing wrong?
instead of doing LayerMask.GetMask
[SerializeField] LayerMask layermask and pass the layermask field into the function instead
Also if detection is touching ANYTHING detect the player?
Ur if statement should check for the player specifically
Did i say something wrong?
What is the LayerMask? I'm struggling to understand what it does in this situation
A layermask tells wether or not the raycast should collide with a collider
A layermask is like a list of layers you want to apply
So in this case the Raycast will collide with whatever gameobject is on the Player Layer and The Ground Layer
If it is in the layermask, it will return a hit. If not, it will be ignored
So, if I had an object that wasn't in the layermask, could the enemy see me through that object?
Yes
this worked thanks
Ofc
The raycast will ignore whatever Layers WERENT included in the layermask parameter
So the raycast will phase thru the collider
You could use RaycastAll and it will return EVERY collider it passes though. Check if the things blocking should block vision
Ur if statement is ur problem
Ur saying if the Raycast hits anything including the ground
That the enemy can see the player
I'm getting a NullReferenceException error on line 27. Why?
Ur raycast isnt hitting anything
Either detection is null or it has no collider
So the Collider on it is null
Check if the collider is null before comparing the tag
So, when detection collides with an object that isn't of Tag Player, it returns null and therefore that error?
No
When u shoot a raycast it tries to get a reference to the collider that it hit
If the raycast isnt hitting anything it doesnt get a reference to a collider
Hence the NRE
yeah if its a cast the hit is a struct so you always got a value
no
null check it to see if you got a hit or not
Never ignore a NRE
if (detection.collider == null) return;
if you want to do nothing on a miss
Guard clauses. Nice
var drawnCardPrefab = Instantiate(_drawnCardPrefab, _playerDeckTransform);
drawnCardPrefab.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
Why does the right object spawn at that offset?
_playerDeckTransform is the left object. DrawnCardPrefab is the right object
beats nesting inwards for 90% of a function
Yeah bro i didnt even know that was a popular thing and had a name until like a week ago
This is what I've added. Now, when the player goes into the enemy line of sight and then leaves, the error shows again
Give me file-scoped namespaces 😩 I hate indentation
But only when the player leaves
🫡
"is" instead of == is even better because of operator overloading :p
Check if its null first
Can static methods be called from an uninstantiated singleton?
no
Anyone? :(
someone knows how IEnumerator works?
you want to make sure you hit the overloaded == unity has and not do a direct null check
Yes. It is an interface with methods like Next
For enumerating (moving over) a collection
Yeah unity has stated alot that there null check isnt C#s null check and that the objects under the hood arent really null
any resource I could check
Microsoft docs
Yes not for Unity objects
in the given usecase it was a collider though
ah gotcha ✅
yeah for non unityengine.object stuff i use is, ?. and ?? all the time
drawnCardPrefab.transform.SetParent(newCard.transform);
Why does setting the parent change the position?
How can I compare Layer rather than Compare Tag, in my If() statement?
whats the easiest way to detect how long a key has been pressed for and print the time to the console?
it has a 2nd arg
Input.GetKeyDown and Input.GetKeyUp
or simply Input.GetKey and add up delta time while its true
Oh so set that to true?
yeah otherwise it does not keep world pos, but keeps its local pos
var drawnCardPrefab = Instantiate(_drawnCardPrefab, _playerDeckTransform);
drawnCardPrefab.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
drawnCardPrefab.transform.SetParent(newCard.transform, true);
Mm, still seems to create that strange offset
This is the result without the set parent line
what game are you making
fr
Inscryption and Hearthstone Chefs Kiss
Ahh The witcher Card Game is dope to
Is the card supposed to go to the top of the deck?
Yes it's supposed to spawn there, so that it can move to the player's hand
Like a draw animation
Im not to familiar with the u wanna animate this so keep that in mind
But when u spawn (Instantiate) a card is it offscreen or does it just appear on top of the deck?
Wait let me record a gif
try setting local position to vector2.zero. i think what's happening is you are setting the anchor to 0 but that doesn't actually change position
setparent also doesn't change the position with what you're doing
Are the cards prefabs?
set parent, set anchor to 0, then set local position to 0
Should world position stays be set to false?
Ok let me try
you might be able to not set anchor? not sure
By anchor to zero, you mean anchoredPosition?
yeah
Didn't work sadly
Im not to familair with UI
But why dont u just spawn on top of the card deck and then set the parent ?
Can't you just grab the RectTransform of the top of the deck and then Instantiate a card there?
Yeah let me try that
If I’m not wrong this can cause a problem with different resolution
It might im not sure tbh
After you done it, try the lowest and the heightest resolution
But even if the runtime of the position changed depending on resolution whatever reference you have to the RectTransform should update as well i would assume
Emphasis on assume
I think your idea is ok, but you need to get the screen resolution
Because newly created ui during runtime doesn’t count screen resolution (I think)
var drawnCardPrefab = Instantiate(_drawnCardPrefab, _canvasTransform);
drawnCardPrefab.transform.SetParent(newCard.transform);
drawnCardPrefab.GetComponent<RectTransform>().anchoredPosition = new Vector2(
_playerDeckTransform.anchoredPosition.x,
drawnCardPrefab.transform.position.y
);
Locking y seems to work right now
Did you tried changing resolutions?
Always try that, because when you try the game once finished your gonna have a bad surprise (talking with some experience by now)
Yes congrats
idk this one seemed to do the trick :D
Thanks for the help! :)
Well you tried and you did good
Also keep me updated
That game looks sick
I have a problem with importing a texture onto a FBX file, where should I ask this? (it is not as simple as just embed/extract it)
thank you :)
anyone know how to make tilted (where i slide of off) objects count as if im grounded i deleted the layer Ground from the objects but doesnt work
Why did you delete the ground layer from them?
All you need a low friction pysics material on the objects (and set it to use minimum)
I'm also assuming you are using a rigidbody
wdym
i thnk u dont understand what im trying to ask
See #854851968446365696
If explicitly says do not respond with wdym
oh mb
No, I don't
sorry
You want to slide off objects that are tilted, right?
Oh, you want them to COUNT as grounded
So they just need the ground layer on them
they do
And use a physics query wide enough to hit it
Does anyone know if Error lens or something like that exist for Visual Studio? I'm not talking about Visual Studio Code 
Ok, I'm extra confused then.
You said:
i deleted the layer ground from the objects
oh yh i obvously put them back was just trying if that would chaneg anything(which it would obviously not)
but ty
i understand the problem
Ok nice, sorry I misunderstood at first. Glad you got it
im reading my question again and damn that was confusing
There's Code Lens yes, the little indicators that show how many times a property or method is used, for example.
It should be enabled by default, but they can be disabled from the settings.
!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.
- don't crosspost
- format your code properly
- show all error messages etc you are seeing
- Make sure your IDE is configured.
You mean a slope?
And what does your ground check look like?
Ah I was scrolled up
Also, don't multiply mouse input by Time.deltaTime (maybe that is the error? You just wrote detaTime)
Well, if the error says something like "no such things as detaTime" then yeah, it was. But the error will explicitly tell you what was wrong
hey im doing a combat based on turns in a 4 vs 4. i have the 3de models already. For the programming i was thinking of doing a heritage class of all they need and then just getters and setters. Then a empty object that controls the turns and so. Is this way okey or is there an easier way?
If there is any tutorial for this staff i could use i would be more than happy to check it out. Thanks
Then the detaTime is not the issue. Can you post the full error
Although, a praetor said, probably should configure your !ide if it is not already
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
it tells you how to fix it, read last sentence
What kinda class name is that anyway
putting a decimal in a script name is def not valid lol
If you need to keep track of your code changes, use Git instead :)
That doesn't sound code-related, ask in #💻┃unity-talk
Don't have version numbers in the file names (like the 0.1)
Use proper version control, like git, which you can Google to learn more about
can anyone help me? it doest play the falling animation😭
it played it before i added the jumping animation into the code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hey im doing a combat based on turns in a 4 vs 4. i have the 3de models already. For the programming i was thinking of doing a heritage class of all they need and then just getters and setters. Then a empty object that controls the turns and so. Is this way okey or is there an easier way?
If there is any tutorial for this staff i could use i would be more than happy to check it out. Thanks
any idea where he gets item.icon from here? I'm following the tutorial but I'm getting a "item does not contain a definition for icon" error and im really confused https://youtu.be/AoD_F1fSFFg?t=507
Inventory system is used in most of the games. If you need an inventory system in your game, this video is for you. In this video, I will teach you how to make an inventory system from scratch. Enjoy watching.
❤️Join My Channel to Support Me: https://www.youtube.com/c/SoloGameDev/join
💙Subscribe to My Channel: http://www.youtube.com/c/SoloGameD...
for turn based combat you essentially need a state machine
where can i learn about that?
He would have made an icon variable inside the item class (or struct?)
ohhhhh
i think i named it something else by mistake
thank you
Dot notation, which c# uses, does it like this
Thing . Thing inside the thing to the left . Thing inside the last thing
The words to the right are in the words to the left
Why doesn't Visual Studio like this?
char[][] HIDCodesToASCII = new char[256][];
HIDCodesToASCII[0x04] = ['a', 'A'];
Squiggly line under the bracket before 'a', says Invalid Expression Term '['
You cannot create arrays with the [ ] syntax in the C# version Unity is using
ah. k
You need to do something like = { 'a', 'A' } or = new char[] { 'a', 'A' }
Yeah it accepts the second one... Hmm. I'm going to be typing this out 100 times or so. Any recommendations on how to accomplish this more succinctly?
With a for loop? What are you trying to do here?
get a jagged or multideminsional array of characters, the first index of which is represented by an HID code, the second of which is indicates whether it's changed due to shift or capsLock
Right. Depending on the characters you're going to put in the array, and whether the indices are consecutive, you can do it all in one loop. Characters are convertible to int so you can do pretty neat stuff with them
for (char c = 'a'; c < 'z'; c++) { }
I'm just being lazy
Right but ultimately I should probably be putting the HID codes into an enumerator anyway
public virtual is used when you have heritage but its implemented in the father right==
??*
I think you are saying "heritage" when you mean "inheritance"?
virtual means "a child class is allowed/permitted to override this method"
without virtual, you cannot override the method
inheritance itself happens no matter what when you have a class derived from another class.
Again it all depends on if these codes are consecutive or not. Sometimes preparing the data in Excel or in an online compiler can remove a lot of the hassle
so if i have a dealDamage() method it would be
public abstract void dealDamage(int damage);
in the father and
public void dealDamage(int damage)
{
//code
}
in the children? im using like this and it says error if i dont use override
when its not virtual
@wintry quarry
abstract is different from virtual
virtual means you may override
abstract means you must override
ohhhh i see
and if you have neither abstract nor virtual , then you cannot override
In my Enemy script, I have a bool that determines if the enemy is alive. When the enemy is shot by the player, the bool turns to false and that stops the enemy from being able to function.
The problem is, if I kill 1 enemy, then all the other enemies that have the same script also stop working. Because of this, I can't use it as a prefab. How can I prevent this?
Did you make the bool static?
Seems like that boolean is wrongly marked as static? Or you're modifying the boolean on the prefab instead of one of its instances in the scene?
Is the bool static?
Triple
Triple kill
No
No
Are you changing the value of the prefab instead of the instance?
you'll have to show your code because your explanation doesn't add up.
I deleted the prefab, so I just have a singular enemy in my scene with the scripts attached
if there's only a singular enemy, then your explanation makes no sense
because it mentions multiples
if there's a prefab being used to spawn things, there should be ZERO enemies in the scene at edit time
ok show your code already
this is a code channel after all
we'd want to see the enemy script and whatever script is damaging/killing the enemies
!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.
Player health and death:
https://gdl.space/popeyikuma.cs
Enemy movement
https://gdl.space/teniruloqe.cpp
Enemy punch KickBack Force
https://gdl.space/legofifiqe.cpp
chatgpt the goat with helping!!!
So right now, if I kill 1 enemy, the other enemies still follow and punch me, but they deal no damage or generate a force to push the player back
@wintry quarry one more question please. once i made all the childs im thinking to do a controller which put all the GameObjects in a list and then call to their Attack() one by one. How would i do that in unity?
Not a code question, and disagree
maybe there is a better option
ok so this has nothing to do with enemies dying
you said it had to do with enemies dying
i mean it helped with my code thankfully! AND SORRY, next time i will ask a proper question.
Enemies can deal damage to me until I kill 1, then they can no longer deal damage
The spam-bot will hinder you more than it helps
you said this
When I kill an enemy, the bool which determines if the enemy is alive turns to false. i thought this might be the issue?
which bool is that?
I don't see such a bool in your code
I see canKillPlayer
could be true, first time i used it. might do it again but won't rlly as it won't help me improve.
Yes, this. It turns to false on a particle collision
The bullets from the players gun are particles
but htat's pointless
once i made all the childs im thinking to do a controller which put all the GameObjects in a list and then call to their Attack() one by one. How would i do that in unity?
and is there a better option?
because in your player code you're doing this:
https://gdl.space/popeyikuma.cs
if (collision.gameObject.layer == 8 && EnemyFollowRef.canKillPlayer == true && EnemyFistDamageRef.punchTypeEnemyCanHit == true)```
you're reading canKillPlayer from SOME specific enemy reference that you drag and dropped
you should be getting the component from the object you collided with
and checking it on that object
instead of some specifically dran & dropped enemy reference
basically there's no reason these fields should exist:
public EnemyFollow EnemyFollowRef;
public EnemyFistDamage EnemyFistDamageRef;```
The player should not have these references
I should check for the canKillPlayer on the collided object?
EnemyFollow collidedEnemyFollow = collision.gameObject.GetComponent<EnemyFollow>(); like that
You probably also want to make sure the collision is with a gameobject with that component first before you do anything else with it, or you'll get an NRE
This is what I've done. Is this correct? Because I still have the same issue
Or just use Try GetComponent
How do I do that?
TryGetComponent is the cleanest approach
if (thisEnemyFollow == null) { // do stuff differently, or just return }
GetComponent<> gives you null if it doesn't find the component, so if the player collides with something that doesn't have it you'll get a null reference exception if you try to do anything with that null reference. So catching that is important
collision.GameObject.TryGetComponent<EnemyFollow>(out EnemyFollow enemyScript)
Something like this, you can then use enemyScript inside your OnTriggerEnter
here, this is a good example of it
That way you can just do whatever u need to with the reference and if u dont have the reference then just do something else
Why did you add "out EnemyFollow enemyScript" at the end?
Multiple return types
you need to add it anyways
otherwise it wont work
TryGetComponent<> returns a bool to see if it does have the component but it ALSO has to return the component and it can only do that with the out keyword
but i added this so you have a reference to that component
so you can use that in your script as a normal variable
The out paramater is the same as doing: variable = return value from a method
But the syntax is a bit weird for it
Your basically just assigning a value
yeah it is, i was so confused when i first used that
I changed the explanation incase that doesnt make sense D&M
You can see regular arguments as giving values to the method. With out, it's the inverse: the method gives a value back to the code that executed the method.
And since that in C# methods cannot return more than one value (with the return keyword), then it uses out
out also means the variable that's used in the parameter will be modified, rather than returned in a form that can be discarded or used as you wish.
anyone knows how can I change the third person camera's position over the character's shoulder? I use Third Person Template scripts for character controller and camera
I can make a script for it or smth?
Is this correct? Because now no enemy does damage to me
jesus
you need it to have both components?
Also there's no need for == true
thats a cursed ass ifstatement
😦
Does the enemy have child objects with colliders?
Yes, but it's a trigger
in general, why don't you just break this stuff down a bit and use debug.log's to figure out how the behavior differs from what you expect
rather than going back and forth and having us guess
You are trying to get the component from the object that has the collider
Isn't the component on its parent instead?
how can i load a list of Characters from the combatManager? like have them all in the list
What is combatManager?
wdym by "load"?
its a empty GameObject i did to manage the combatOrder
and i need to fill the list with all the characters
Each character could add itself to the list in Start, for example
combatOrder is/has a script component, right?
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Aliado : Personaje
{
// Start is called before the first frame update
void Start()
{
currentHP = maxHP;
}
// Update is called once per frame
void Update()
{
}
public override void TakeDamage(int damage)
{
currentHP -= damage;
if (currentHP <= 0)
{
Death();
}
}
public override void HealHP(int HP)
{
currentHP += HP;
if (currentHP >= maxHP)
{
currentHP = maxHP;
}
}
public override void Death() {}
public override void Attack()
{}
public override void Attack2()
{}
public override void Attack3()
{}
}
```this is one of the 3 object cs i want to add and this is the manager:
```cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CombatManager : MonoBehaviour
{
List<Personaje> list = new List<Personaje>();
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
i want to put that list with the objects
You could add a method to that script, something like RegisterCharacter(Character character)
And each Character, when created, would call CombatManager.Instance.RegisterCharacter(this)
But first you would need to make CombatManager into a Singleton
That's the .Instance part
This page explains singletons
https://gamedevbeginner.com/singletons-in-unity-the-right-way/
Give it a read, it will be useful in game dev.
For these kinds of manager classes
i see
thanks
ill check it now
uff
global class
isnt that ilegal xD
or i can use it fine if its on the manager
It's a very common pattern in game dev
You should use a static, only on object you know you only need one
As long as you know that only one instance of the singleton will exist
So it’s fine using it on a Manager
But for example it cannot be in a Enemy script, ‘cause you need more than one
what on awake
Yeah you don't directly modify the singleton's variables, using a method is good (like my example RegisterCharacter)
Basically, it’s when the scene is loaded(I think)
It starts before Start, and is useful in case you want to put a reference of the static in another script in Start(), ‘cause it can cause an error if both are in Start()
Awful explanation but I hope you understood something
Yeah it can be done in Awake.
I just like to separate awake/start so that in Awake you do "internal initialization" (no references/dependencies to other objects) and Start for stuff that needs some other objects to be initialized first.
i see
Because you can be sure that every object's Awake has already been called when Start is called
This is the Singletone:
public class CombatManager : MonoBehaviour
{
List<Personaje> list;
public static CombatManager Instance { get; private set; }
// Start is called before the first frame update
void Start()
{
List<Personaje> list = new List<Personaje>();
}
// Update is called once per frame
void Update()
{
}
void RegisterCharacter(Personaje character)
{
list.Add(character);
}
}
This is the object:
public class Aliado : Personaje
{
// Start is called before the first frame update
void Start()
{
currentHP = maxHP;
CombatManager.Instance.registerCharacter(this);
}
}
Its not right, could you help me find how to instance that method?
https://docs.unity3d.com/Manual/ExecutionOrder.html heres the order of how unity functions get called
may be useful
Youre CombatManager.Instance hasn't been set to anything
I linked it a moment ago
ahh sorry, i just stepped in
also i didnt put the registerCharacter public
and i tried to access it
ok now i get it more less
is there a way to check if it works fine? like cout the list
but here xD
as its paralel i cant debug
Yes but you can also just serialize the list so it shows in the inspector:cs [SerializeField] List<Personaje> list;
Private fields won't be visible unless you tell unity to serialize them
wdym "paralel"? You can certainly use Debug.Log
this is a new list?
cause it say i cant have both this one and the one i had
i mean sorry if my questions are stupid
ohhhh
But yep you can also use Debug.Log to print stuff out
i see
and this will show it on the inspector?
IT WORKS
LETS GO
after 3 hours
feels good
damn thanks
sorry if stupid question
No worries, they were not stupid questions
Guys why would I use while() instead of an if() in the update void?
Because you will get a stack overflow and your game will freeze.
im gonna cry
So I should use while() instead of i
If
No, never use while unless you know what you're doing.
and btw its an Update Method or Function void is the return type..
like Vector3 or Float
What was the context it was used i
it irks me to hear "update void" or "why my void not work" lol
Like while integer =1 or something then do whatever
Don't remember clearly
I gotta check later
I actually gotta go to class now 💀
I'm eating lunch
I was just thinking so I decided to ask right now
But now I gotta go 💀
i modified my canon for it to shoot only if reloaded and it weirdly does not work
an if statement is for making decisions based on a condition, executing code once if the condition is true. A while loop is for repeating a block of code as long as a condition is true
but in the context of unity and the Update() loop for example its pretty similar.. if statements are the easier / thing u learn first
while loops take a little more pre-thought and get more useful more advanced u become
having this issue where because its inherited, it runs the manager script a second time when the weapon selection is enabled, which results in the starting weapon being spawned in twice... whats a way I can solve this?
It's unclear why the reload thing is its own script and which object/script it's referencing
what's inherited from what? Which function is running twice?
why do this in start? if ur onenable does it anyway?
the start function is running twice
which start function? Unity only calls Start once per object. Inheritance doesn't change that
did it to see what was running as i didnt know what the issue was
A class instance that's inherited is only present once. There isn't one instance per class definition
ahh okay
yeah, thats why im assuming its being spawned in twice
yes, that would have nothing to do with inheritance
health system is supposed to reference the player
reload canon script is suposed to declare if the canon is loading by going in it(invisible :0 )
select script is the canon script
you can pass context thru the debug
You have this script twice in your scene, at some point.
what would i put in to reference what is calling it
that way to see why it gets run twice
Unity Engine itself calls Start
Debug.Log("message", gameObject) - upon selecting the log in the console, it'll highlight in the Hierarchy which object sent it
whats running it the second time.
this is the issue, im unaware of what is
thats why the extra context..
it should only be run once.. unless theres two versions of it
just search the scene for your script
u cant manually call the Start() function from what im aware
It's being ran by the weapon selection controller, the script on the right but cant find how or why, like you said the start function cant be run, only by unity when its spawned in
yup, sooooo there has to be (2) of em.. if ur seeing the start function.. debug (2x)
make sure u dont have a phantom version of the script on the gameobject somewhere
Debug.Log($"Running WeaponManager.Start on {gameObject.name} (ID: {GetInstanceID()})", gameObject);
If you get two logs but the object name or Instance ID is different, then you have two scripts attached.
hi! does someone know why the position of the object the script is atached to doesnt match with the position my mouse should be on?
Does that script derive from the other script?
And you have both scripts in the scene?
If so then yes that makes perfect sense. A class that derives from another class inherits all of its members, including the Start function
you're mixing up world space coordinates (transform.position) with screen space coordinates (Input.mousePosition)
im 100 percent sure it does debug the value of mousePos.. and debug the value of transform.position
i readed them but cant figure out how i should make the center of the screen be 0, 0 and not the down left corner
There's no reason to "make the screen" do anything
convert your mouse position to a oworld space position is what you need
and how do i do that?
Use one of the options in this article: https://unity.huh.how/screentoworldpoint
srry im very new at programming and just got back at it again
Vector3 mousePosition = Input.mousePosition;
transform.position = mousePosition;
Debug.Log($"{mousePosition} + {transform.position}");
can someone help me find the part of the script where when you finish dialogue it switches the scene
im doing it in a 2d game
i dont know if that changes something at all tho
doesn't matter, it'll still log the same..
theres a bit more to it than setting it = to mouse position
https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html @radiant frigate check this link out
There's no such thing in this script right now. But, the very last else is configured to disable the object this script is on when there are no more dialogue lines to display.
omw and ty for the help!
okay so what i understand is that screen is measured by the pixels and the world point is the x y z, so what i have to do i wirte ScreenToWorldPoint before it so it transforms to WorldPoint?
What you could do instead, to make that script more versatile, is to expose a UnityEvent you'll invoke when the dialogue has ended.
If you used a button before, it's like the "On Click" box where you can drag-drop a script and select a function. But in your own script.
// Declare
public UnityEvent DialogueEnded;
// Invoke
DialogueEnded.Invoke();
So on one of them you could wire up a function that displays another dialogue, and on another wire up a function that changes scenes
All of that directly from the Inspector, without ever touching the insides of the script
i already got button and closed unity out
I got it covered.
i think this should work right?
just make sure you specify a z position for the mousePos otherwise it will be the same as the camera's z position so it will be too close to render
so i should just do z = -1?
once i have a list with gameObjects ordered by turn, how can i make so that till the first one attack it dont move to the next one
all the gameobjects update at the same time?
like, do they all start same tic
z would be in front of ur camera.
so 10 is a normal go-to
totally up to you tho what u set the z to
idk what is that but it looks cool
a WIP 😄 top down click to move turn/time based auto-shooter type game
thanks lol
kwel
kinda just going with the flow.. working out mechanics.. while i hunt for the fun
once i find the fun i'll reiteration on that
you gave me an idea with the mouse position...
air strike
cool
gonna work out a parabola formula to get a good arch
Do you mean like a turn based combat? I.E, only the object can act in the object's turn?
my project will also need a system like this
You'll need something which is keeping track of all the objects and some way for it to tell when each object has done its thing so that it can move to the next one. How that works is pretty much up to what game you're making.
Well, there are many ways to do that. It's a very broad question. I suggest trying find some tutorials.
haven tmade it yet tho
irc brackeys has a turn based tutorial.. like a pokemon battler thing
its basic as it comes.. might be able to get an idea of where u wanna go and how ud go about it
But essentially, you want a state machine that keeps track if the game is in a turn (so it pauses) or if it can move on (turn finished).
if you have DoTween, you could build a big ol' sequence with each object's actions and run through that
but does onbuttondown or on mouse down make you click with ray?
Or that
I think I overcomplicated lol
{
Debug.Log("Trigger Enter");
LayerMask mask = LayerMask.GetMask("Environment");
if (other.CompareTag("Player"))
{
playerHealth.Damage(damageValue);
Destroy(gameObject);
}
if (other.gameObject.layer == mask)
{
Debug.Log("Test");
Destroy(gameObject);
}
}```
Hey guys really weird issue I really cant figure out
My trigger works fine but when it comes to detecting it the trigger moves into a gameobject within a specific layer it does not recognise it
I have done VARIOUS debugging such as debugging the layer it detects on enter, it only seems to recognise the player and enemy, and i have applied the layermask in editor
i actual have my own method.. when u click down it starts the sequence.. then you can hover / and hold which is 1 type of selection.. or u can drag away from the object 2nd type of interaction.. or u can release 3rd kind of interaction
the layer property of a gameobject is the layer index, and LayerMask.GetMask returns a bitmask not the layer index. check this page out to learn how LayerMasks work https://unity.huh.how/bitmasks
ye but i saw someone having a problem with something called onMouseDown and does this make it click with raycast?
https://pastebin.com/3spGauC7 yes i shoot a ray into the world using the mouse position
you can check the code here.. but its a WIP and pretty nasty atm
i will check it thanks
when u press down it Starts the Sequence.. then it'll know if ur dragging or just hovering over the object you clicked..
depending on which one it does different things when u release
so this is all differant function?
the click calls 1 function.. and sets drag and hold both to true..
then those bools are in the update.. while they're running they both have an exit conditional (if i drag away from the object hold becomes false..)
if i release the mouse (drag becomes false)
👁️ 👄 👁️
same with the hold.. if i move off the object hold becomes false.. if i release the mouse hold becomes false..
Can anyone give me an idea on how i can create a door similar if not a copy of the door opened at the start of this video?
The part i want is the way the player can control the doors movement with his mouse, and collider.
https://www.youtube.com/watch?v=sQVUhEojF8A&ab_channel=nullnull
here you go show it
is it the same tho?
ahh 👍 but still.. just wnated to show what it does..
when i click i set all the bools to be true.. and then afterwards the update loop has the if(drag) and if(hold) each one is waiting for me to move away from the object.. or release the mouse
depending on which one i do first.. it'll set the bools to false.. so the loops stop running
and the action eventually happens (like selecting it) or (making it look a direction)
at that point i have to click again for the bools to go back to true and start over again
its a super simple/ if() type of state machine 😄
_transformContainer.localRotation = Quaternion.Euler(0f, 0f, degrees);
How would I do this smoothly?
that i need to refactor at this point
Like MoveTowards for Vector2
keraunos has the same door type as you
u probably want some type of physics.. you can use a sphere or something hovering in front of the player to manipulate it..
when u click u could for example add a hinge joint from the hovering sphere to the door
when u move ur mouse the floating sphere or w/e would follow.. and the door would be moved inthe process
ah right gotcha, ill have a crack at it thanks
ooor.. u can just use the starting mouse position and just detect when u go to the left or to the right
and u could translate that into a regular torque force on the rigidbody
am i correct in saying that instead of LayerMask.GetMask, I should use LayerMask.NameToLayer
or am i still misunderstanding
why are you even comparing the layer in the first place
i have a prefab that moves when instantiated
attached is a trigger
I am trying to see if a gameobject within [layer] is passed through the trigger, if so destroy
In this tutorial, I will show you how to make a door that you can open by dragging your mouse! We will do this by using a hinge joint and applying the velocity to it thorough the C# script. Many games have door opening like this, so it can be pretty useful.
Feel free to ask me any questions, like and subscribe!
CODE -https://docs.google.com/do...
that does not explain why you are comparing the layer
it is almost always better to just check for a tag or specific component and use layers to filter out unwanted collisions
yea, the attched rigidbody would be more immersive (would be something more suited for VR) and picking up objects..
but u could take the shortcut of knowing exactly what axis ur rotating on.. then ud just need mouse values..
dont trust the code in desc stuff, it's a trap
rotate this way or that way
i never trust code.. the way to do it is learn the concepts.. and then study the actual code / functions urself..
yep i did this error, i was too lazy to code so i downloaded scripts
okay noted
ill avoid this approach
i did not understand when i wanted to change it
exactly what happens
if u want the identical thing.. sure copy.. but when u wanna change stuff thats when it falls apart if u dont understand the basic concepts ur using
Guys why wouldnt the the Animation tab not open , im going Window > Animation > Animation and nothing opens, i cant ge the Window tab to open at all?
I dont have any Console errors or anything either
is it already open somewhere
it may be off the screen
my animation window always goes on my 2nd monitor for who knows what reason
yeah it was on my Graphics tablet that i couldnt see because it was turned off lol
How do I check if localRotation is approximately a certain value?
use a variable and expose it in the inspector.
ohhh mb lol 🤣
what is the actual use case for this? because there might be a better way to accomplish whatever it is you are trying to do
just for context
i did fix this tho im not going w this method anymore
i found a reddit thread that stated for ontriggerenter to work properly, a rigidbody is needed which i wasnt aware of
weird that the player still was detected spite any rigidbody
private void Update()
{
if (_targetDegrees is null) return;
var step = ROTATION_SPEED * Time.deltaTime;
var targetRotation = Quaternion.Euler(0f, 0f, _targetDegrees.Value);
_transformContainer.localRotation = Quaternion.RotateTowards
(
_transformContainer.rotation,
targetRotation,
step
);
if (_transformContainer.localRotation REACHED) STOP
}
I'd guess that your player has a CharacterController which can also send OnTrigger messages
if (Quaternion.Angle(transform.localRotation, targetRotation) < angleThreshold)
{
}```
AH thats it!
yeah makes sense now
appreciate the pointers
I'll try thanks
no problem, ive never used it.. but the docs seems to say thats how it works
use your words to describe it. don't just throw a bunch of pseudocode and expect everyone to know what you are actually trying to accomplish because that does not explain it. that just explains your current attempt at doing whatever it is you are trying to accomplish
and angleThreshold would be something small.. the smaller the closer it'd have to be to the target for it to return true
why i cant use
enemy1Unit.TakeDamage(damage);
if the enemy unit is a child of other class?
what happens when you try
can you provide actual error messages instead of a vague approximation of it
its not in english
let me change lenguage
1 sec
'Unit' does not contain a definition for 'TakeDamage' and no accessible extension method 'TakeDamage' accepting a first argument of type 'type' could be found (are you missing a using directive or an assembly reference?).
it sounds like you probably have a variable of type Unit which is not an EnemyUnit. you need to cast to EnemyUnit if that is the derived type that declares that TakeDamage method
of course you haven't shared actual code and you keep modifying the error message you've posted so that's really just a guess based on the little context you've provided
📃 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.
This is my battleManager the problem is on line enemy1Unit.TakeDamage(player1unit.Attack1());
public enum BattleState { START, PLAYER1TURN, ENEMY1TURN, WON, LOST }
public class BattleManager : MonoBehaviour
{
public GameObject playerPrefab;
public GameObject enemyPrefab;
public Transform player1Position;
public Transform enemy1Position;
Unit player1Unit;
Unit enemy1Unit;
public BattleState state;
void Start()
{
state = BattleState.START;
SetupBattle();
}
void SetupBattle()
{
GameObject playerGO = Instantiate(playerPrefab, player1Position);
player1Unit = playerGO.GetComponent<Unit>();
GameObject enemyGO = Instantiate(enemyPrefab, enemy1Position);
enemy1Unit = enemyGO.GetComponent<Unit>();
//setup de las HUDS -> playe1HUD.setHUD(player1Unit) idem con enemy
state = BattleState.PLAYER1TURN;
PlayerTurn();
}
void PlayerTurn()
{
}
void PlayerAttack1()
{
//diferenciar si es un ataque en area
enemy1Unit.TakeDamage(player1unit.Attack1());
}
public void OnAttackButton1()
{
if (state != BattleState.PLAYER1TURN)
return;
StartCoroutine(PlayerAttack());
}
}
The class Allie and Enemy are the same:
public class Enemy1 : Character
{
// Start is called before the first frame update
void Start()
{
currentHP = maxHP;
}
// Update is called once per frame
void Update()
{
}
public override void TakeDamage(int damage)
{
currentHP -= damage;
if (currentHP <= 0)
{
Death();
}
}
public override void Death() { }
public override void Attack1()
{ }
}
Its like Unit dont get the function cause its the children class?
i couldnt do it shorter sorry
its a basic attackTurnSystem
yeah so this is the answer #💻┃code-beginner message
you have to cast to EnemyUnit (or whatever the derived type that declares that TakeDamage method is called) because that method does not exist on the Unit class and you cannot use members from derived classes unless you have a variable of that type or an even further derived type
i see... thought i could declare units on derivative classes and access the ,ethods
you can only access the members that are accessible to that class because it doesn't know about any of its derived classes, it only knows about itself and its parent classes
a simple thing to do would be to type check and cast using the is operator like if(enemy1Unit is EnemyUnity enemy), or just store the enemy as an EnemyUnit
https://hastebin.com/share/tifunepuxa.csharp my update method isnt quite working out lol
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
it keeps getting faster the longer i hold down fire
its supposed to fire every 1 second
what is the value of volleyDelay (in the inspector)
because that appears to be the only thing that prevents it from firing again
in fire volly ur not resetting the velocity..
as a result each new projectile inherits the velocity of the previous one
0.8 second
GameObject playerGO = Instantiate(playerPrefab, player1Position);
player1Unit = playerGO.GetComponent<Unit>();
this problem is here right? Sorry bit lost
no that is not the issue since that is not the enemy unit
ok thanks spawn
if (Time.time >= nextGlobalCooldownTime)
{
nextGlobalCooldownTime = Time.time + globalCooldown;
}
i think thats the problem but its shooting like multiple volleys instead of every second
you mean when i declare it? or the class of enemy itself
the issue is on Unit script..
it can't find the TakeDamage() function
but its there 😢
the second code here
oh
no thats BattleManager
#💻┃code-beginner message
in the BattleManager do this
Hello!, I am having a problem with the triggers and the colliders, what is happening is that my player has a script to take damage and it is interacting with all the enemy's colliders, what I want is for it to only take the collision with it parent object of the enemy and a child that is the one that has the collider for the animation.
Put the separate colliders on different layers and use layer based collisions to disentangle the interactions
This is the damage detection script
ok ok I'll try that tnks
how would i make it so this only applies to me going forward
instead of both forward & backwards
if verticalInput is positive..
like this?
that's negative
oh wait yea
is this code only for 3d or does it work for 2d
Which code?
this
That has nothing to do with 3d or 2d, so it will work in both
thanks
it's not going to be useful outside of that person's particular script.
hi, how to reduce collider visibility to a single layer? exclude everything but the layer or include only the layer or both in the layer overrides area. How to dynamically change this from code?
👍
is this a good place to learn unity https://www.gamedevrocket.com/
The Game Dev Rocket is a 60+ hours program, taught by Blackthornprod, to turn your passion and dream of becoming a profitable game developer into a reality.
Ay I have a dumb question, I’m trying to get an empty to move around a pivot when I give a player action. Any idea how I can go about that
Basically what i am using to give the gameObject the angle to rotate
currentAngle += rotationInput * rotationSpeed * Time.deltaTime;
currentAngle = Mathf.Clamp(currentAngle, minAngle, maxAngle);
i just need it to then move around a 'pivot' tp that position
again, dumb question. Im an engineer and i cant figure it out
No idea. This is the best I know of, and it's free !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
if ur using an empty object.. that is the pivot..
alright i will check it out
Oh yeah, that one costs money? No, it's trash
just offset the object (the child) and rotate the main object
which one gamerocket?
Yeah
Learn.unity.com is free
right, but basically i have a turret targetting it, so i want to move that empty game object so see movement
nah its free if u go to the dudes channel
so i would have to create another empty gameObject for that gameObject to move around?
yea, u just rotate it.. theres many ways
do u want it to look at a certain target?
as long as u have the gun of the turret facing the same direction as the forward axis z then it should work fine
I'm making a controller and having an issue where what should be the forward/backward input is making the character go up/down.
The script only lets me assign x and y to a vector2, but unity is taking that y as up/down, not forward/back. Is there some way to fix this either in the script or unity itself?
[didnt mean to send this while a convo was up, mb]
alright
thank you
just wanted to make sure
Ok, that's better at least. The whole page looks super predatory though. Classic snake oil tactics. I would be highly suspicious of it
Edit: oh god, it's $700 USD! Insane
Because it is a single letter
The message explains why
ohhh
It keeps saying the non convex mesh collider with non kinetmatic body doesn’t work, any tips on how to fix?
So firstly, for contect, the game is in space, this will make sense
when rotating, the pivot doesnt really move the position of the turretsTarget, so when you move at certain angles, the turret will change directions
even if it wasnt told to
ya, make it convex
you cant use physics on concave colliders (non- convex) (colliders with valleys and/or holes)
think of a bubble of syranwrap around ur collider.s.
if you need some advanced shape you either have to build it from multiple simpler type colliders.. or buy an asset that does it for you (i think)
Can someone tell me how to remove the .csproj files form the side in VSCode. Really frustrating
In the unityExternalEditor settings I turned all the settings off and they still appear?
You turned them off an then what? Did you click regenerate project files?
Yeah i did, didn't change anything. Just did it to test it to no avail just yet
Have you tried just deleting the .cspoj files?
yeah just delete them, then regenerate project files when only the types of csproj files you want are selected
do note that you will not get autocomplete and stuff for types in the assemblies that you do not have csproj files for
Oh I see, I'll do that, that is why i was hoping to hide them over delete them hm
if there's some way to do that, it would be in the vs code settings. and if you need help with the vs code settings, you'd be better off asking somewhere more specific to vs code rather than a unity server
Thankyou, I'll give that a try, I have seen some ways online but I'll look into it. Thanks all
In my solution a preset is a list of objects. I want a list of every preset. This means I need a list of lists. Is that stupid and is there a different structure thats lets me do it more easily
Would a list of arrays not work?
lol! thats the only other thing i was thinking of too 😄
wooooosh.. haha
what about a Class? with a constructor..
You havent described what the actual problem is, so not really sure what answer you are expecting
and list of Classes instead..
He probably is looking for a simpler way to store his data
I would make a class with a list field and use a list of the class . . .
I was just wondering if a list of lists is... bad
public class Preset
{
public string Name { get; set; }
public List<object> Objects { get; set; }
public Preset(string name)
{
Name = name;
Objects = new List<object>();
}
}
List<Preset> listOfPresets = new List<Preset>();```
hows this? haha, j/k i have no idea whats the best approach..
but i hear people using lists of lists all the time
I have a script to paint tiles (basic 2 types, green/blue). I'm planning to tag the green (grass) tiles so I can grab them into an array and randomly generate a portal on one of those green tiles. Does anyone see a problem with that approach? Here's the script that creates those tiles of that helps explain my scenario.
Note: at the moment, it's only painting 1 color (green) for now.
I would call it suboptimal in terms of readability
The suggested list of a class that contains a list would be easier to deal with
But a list of lists is not inherently bad, no
!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.
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
The quick snippet of the code was just to support my scenario, I wasn't really asking for help to modify my code. But I can put it in a service website if needed.
then nvm
I'm trying to change the animator parameter "isAttacking" to false when the animation has completed so that it doesn't repeat the animation but it doesn't seem to work. Any thoughts?
Use animation event to set isAttacking back to false
If you're trying to stop the repeat animation, select animation Clip and in Inspector, turn "Loop Time" off.
what's the difference between Quaternion.Euler(0, 0, 0) and Vector3(0, 0, 0)?
one is a rotation , one is not
so Quaternion.Euler is essentially just the Vector3 of transform.rotation?
its euler angles to quaternion
in unity what you see in inspector is euler angles, so only xyz needed
What's the difference between transform.rotation and transform.localRotation?
!docs
-_-

tuple
A tuple isn't the same as a List
For initializing it with values, yeah I think
myList = new() { value1, value2 }
I can't remember
List is a dynamic collection of items. A tuple-value is a coupling of several values.
hmm yeah they prob tried to init it with (f,f,f)
i tried to add a list to a list
But it seems you cant do it directly and you need to add a list variable
like this
Apparently you cant serialize Vector3's so I have to do each component
ugh
You can't directly serialize monobehaviour's without a workaround, yeah. But vector3 is fine.
But you were adding it to a list, not saving a file.
What is the list?
A list of everything im saving
And what are you serializing with?
Json
Ok but WHAT is the list?
Show the declaration
And json is the format, what are you using to serialize TO json?
Different serializers have different capabilities
JsonUtility?
If you're using JsonUtility you can serialize anything unity can, if you're using something like JSON.net you do not have vector3 without workaround.
I clearly do not know how to use JsonUtility
I will continue doing the work around and just store it as a text
🙏
perhaps share error or show what isn't working exactly ?
looks like trying to serialize a MB?
Yeah but thats after doing multiple
what is mb :d
Monobehaviour
preset is serializable?
It is an issue
yeah why not just the data on it? then recreate on load
You can serialize the MB but doesn't like list of list iirc
A successful serialization has all the information you want serialized.
how do you make a height of an object based on the overall height of its children?
Is that a #📲┃ui-ux question?
I should say what Im serializing to make sure its possible.
A list of presets
Each preset has a name, date, List of Suns, List of Planets
each Planet has Vector3 position, Vector3 velocity etc.. a bunch of vector 3 stuff
the thing you're serializing needs to be serializable
I was told JsonUtility is good for all Unity variable types
The rules for serialization are here https://docs.unity3d.com/Manual/script-Serialization.html#SerializationRules
idk what "all unity variable types" means
that's very vague, and definitely not true.
Which is the monobehaviour? The Suns? And what are Planets
Unity has a problem if the Item in the List is a MB type
(it will store the instance ID of the MBs not the data)
does rb.AddForce account for gravity?
I noticed that when I update transform.position for physics it creates a curve and works with rb.gravity
but when I put the same variables into rb.AddForce it just sorta flies
AddForce adds force. It doesn't "Account" for anything. There is still gravity, also adding force
You should never be updating transform.position if you're using a Rigidbody
AddForce has one effect and one effect only which is to alter the object's velocity.
If you're plugging a position vector into AddForce, that makes no sense at all. Nonsense input = nonsense results.
You shouldn't manipulate the transform as it does not use the physics engine. It will fight against any physics methods, like AddForce . . .
in that case how do I specify direction
Wdym? AddForce accepts any force vector you wish
a vector is a direction and a magnitude all in one
you said "If you're plugging a position vector into AddForce, that makes no sense at all."
does that not mean "don't use vectors"
are you wanting to add forces or are you wanting to set the velocity directly or are you wanting to set the position directly?
it doesn't mean don't use vectors. It means don't use position vectors
either #1 or #2, definitely not #3
It means don't use a position
i'm not doing that
It takes a force
from your original description it seemed like you were.
actually this would be easier to send the code
private Rigidbody rb;
private Vector3 forwardForce;
private Vector3 upwardForce;
public int upwardForceMultiplier;
public int forwardForceMultiplier;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
forwardForce = Vector3.forward * Time.deltaTime * forwardForceMultiplier;
upwardForce = Vector3.up * Time.deltaTime * upwardForceMultiplier;
rb.AddForce(forwardForce, ForceMode.Impulse);
rb.AddForce(upwardForce, ForceMode.Impulse);
}
AddForce should never be used in Update
it belongs in FixedUpdate only
you also shouldn't be multiplying the force by deltaTime
and you shouldn't be using Impulse for continuous forces
okay that part i didn't know
you did 3 things wrong here
what should i use instead
nothing
the default
i mean it really depends what kind of effect you're going for
yeah i actually know about not using time.DeltaTime and using FixedUpdate for rigidbodies i just forgot lmaooo
why are you adding two forces as well?
the 3rd thing i dont have much experience with tho
Why not just one force in the direction you want?
tryna create a curve
a curve is a thing that happens over time
it's not something that would be expressed in an AddForce call
If you want to see a parabolic motion curve you can just do this:
void Start() {
rb.velocity = new Vector3(5, 5, 0);
}```
gravity and momentum will take care of the rest
if you want some other kind of "curve", well you'd have to explain what
wowie that's nice and easy
i've been tryna figure out curves cause im tryna make like, fireballs and grenades and stuff, arc projectiles
any other key info you think could help with that
if you think about how projectiles like that work in real life, there is usually one big force at the start to throw them
then they just fly on their own
that's what my code example is doing
it's just setting an initial velocity, and letting momentum and gravity take care of the rest
these things don't get forces added constantly as they fly
just once at the start
(unless you count the force of gravity)
hmm okay ill keep that in mind, i like that way of thinking, very practical
quick question
if you set rb.gravity to -1 or lower does that invert it
rb.gravity is a vector
it's the acceleration of objects it affects in m/s^2
by default it's (0, -9.8, 0) in Unity (which is similar to real life Earth gravity on the surface of Earth)
so... how do i invert gravity then :P
imagine the curve you just described, but happening upside down so the object flies infinitely upwards from the inverted gravity
Well Rigidbody doesn't have a gravity property
Unity 3D Physics has only a global gravity property
Unless this is 2D
You can set the global gravity with https://docs.unity3d.com/ScriptReference/Physics-gravity.html
how would i go about creating object-oriented inverted gravity
you would probably set the "global" gravity to 0 (or set useGravity to false on it) and implement your own gravity
it's very simple:
void FixedUpdate() {
myRb.AddForce(myCustomGravity, ForceMode.Acceleration);
}```
where myCustomGravity is a Vector3
would this create a curve similar to the one that global gravity has
like, say now I dropped the object, would it curve downwards for a bit but then start flying upwards after the apex of the arc
I wouldn't have written it if it didn't.
it wouldn't go downwards at all if you didn't give it a downwards velocity
also, assuming you set your gravity vector to have a positive y value
wouldn't there be conflict between the two forces though
what two forces?
cause it's not like the custom gravity has any special treatment compared to the other force that would hypothetically create the downwards velocity
wdym by "conflict"?
lets say i make the gravity inverted but then give the object downwards velocity too wouldn't they cancel each other out
Forces are in conflict all the time
You set apply a gravity to false then use your custom one
does random.range never select/chose the last option?
when you stand on the ground, the force of gravity is canceled by the force of the ground pushing up on oyu
this isn't a problem
Thats how forces work
oh okay
