#💻┃code-beginner

1 messages · Page 214 of 1

languid spire
#

so you want to apply an opposite force equal to the collision force to player2

stark ruin
#

yes,cause by default unity also if there is not a script behind calculates the collision between the 2 objects

languid spire
#

2D or 3D

stark ruin
#

3d

languid spire
#

so collision has an impulse property, apply the inverse of that

stark ruin
#

when player1 collides with player2,it is like player2 moves also if there is not a script behind that apply a force

languid spire
#

of course, physics is physics, scripts are irrelevant to that

stark ruin
languid spire
#

you want to alter the standard behaviour of physics you need a script

languid spire
#

then no collisions

hybrid gust
stark ruin
languid spire
#

physics has already happend at that point

hybrid gust
#

Collision > make it kinematic > handle the logic however you want > change it back?

languid spire
#

when you make it kinematic you can no longer use force

stark ruin
hybrid gust
#

oooooh i see

stark ruin
hybrid gust
#

But you don't want the physics engine to actually do things to the object right?

languid spire
hybrid gust
#

Why not just set the velocity and anything you want to ignore to 0 then do your logic?

stark ruin
hybrid gust
#

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

vapid mesa
#

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

stark ruin
#

anyway maybe i found a solution

frosty hound
spiral narwhal
#
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)

shell sorrel
#

thing its displaying anchored position in there

spiral narwhal
#

transform.position

shell sorrel
#

yeah since this is UI, you might want to get the rect transform

#

can use GetComponent for that or cast transform

#

_rectTransform = (RectTransform) transform;

spiral narwhal
#

Doesn't transform get a RectTransform for UI game objects?

shell sorrel
#

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

dreamy fulcrum
#
    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?

polar acorn
dreamy fulcrum
#

any way i can exclude the parent object from that?

polar acorn
spiral narwhal
#

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

dreamy fulcrum
polar acorn
dreamy fulcrum
#

how do i chose what to include in the array?

polar acorn
dreamy fulcrum
#

im not really sure how it works actually im just following a tutorial its not very clear

polar acorn
dreamy fulcrum
#

thats why im here

summer stump
#

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

summer stump
# dreamy fulcrum thats why im here

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.

queen adder
#

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

west sonnet
#

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?

queen adder
#

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?

west sonnet
#

What is the LayerMask? I'm struggling to understand what it does in this situation

queen adder
#

A layermask tells wether or not the raycast should collide with a collider

summer stump
queen adder
#

So in this case the Raycast will collide with whatever gameobject is on the Player Layer and The Ground Layer

summer stump
#

If it is in the layermask, it will return a hit. If not, it will be ignored

west sonnet
#

So, if I had an object that wasn't in the layermask, could the enemy see me through that object?

queen adder
#

Yes

queen adder
#

Ofc

#

The raycast will ignore whatever Layers WERENT included in the layermask parameter

#

So the raycast will phase thru the collider

summer stump
queen adder
#

Ur if statement is ur problem

#

Ur saying if the Raycast hits anything including the ground

#

That the enemy can see the player

west sonnet
#

I'm getting a NullReferenceException error on line 27. Why?

queen adder
#

Ur raycast isnt hitting anything

polar acorn
queen adder
#

So the Collider on it is null

#

Check if the collider is null before comparing the tag

west sonnet
#

So, when detection collides with an object that isn't of Tag Player, it returns null and therefore that error?

queen adder
#

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

west sonnet
#

Okay

#

So is it safe to ignore this error?

shell sorrel
#

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

queen adder
#

Never ignore a NRE

shell sorrel
#

if (detection.collider == null) return;
if you want to do nothing on a miss

queen adder
#

Guard clauses. Nice

spiral narwhal
#
            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

shell sorrel
queen adder
#

Yeah bro i didnt even know that was a popular thing and had a name until like a week ago

west sonnet
#

This is what I've added. Now, when the player goes into the enemy line of sight and then leaves, the error shows again

verbal dome
#

Give me file-scoped namespaces 😩 I hate indentation

west sonnet
#

But only when the player leaves

queen adder
#

D&M

#

Inverse that

west sonnet
#

🫡

spiral narwhal
#

"is" instead of == is even better because of operator overloading :p

queen adder
#

Check if its null first

wind raptor
#

Can static methods be called from an uninstantiated singleton?

queen adder
#

Yes

#

Static means its not tied to a instance

ionic zephyr
#

someone knows how IEnumerator works?

shell sorrel
summer stump
queen adder
#

Yeah unity has stated alot that there null check isnt C#s null check and that the objects under the hood arent really null

summer stump
shell sorrel
spiral narwhal
#

ah gotcha ✅

shell sorrel
#

yeah for non unityengine.object stuff i use is, ?. and ?? all the time

spiral narwhal
#

drawnCardPrefab.transform.SetParent(newCard.transform);

Why does setting the parent change the position?

shell sorrel
#

look at the docs for it

west sonnet
#

How can I compare Layer rather than Compare Tag, in my If() statement?

gaunt flume
#

whats the easiest way to detect how long a key has been pressed for and print the time to the console?

shell sorrel
#

or simply Input.GetKey and add up delta time while its true

spiral narwhal
#

Oh so set that to true?

shell sorrel
spiral narwhal
#
            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

noble summit
#

what game are you making

queen adder
#

NGL im interested to

#

Love Card Games Made in Unity

noble summit
#

fr

queen adder
#

Inscryption and Hearthstone Chefs Kiss

spiral narwhal
#

Something like Gwent :)

#

The standalone one

queen adder
#

Ahh The witcher Card Game is dope to

#

Is the card supposed to go to the top of the deck?

spiral narwhal
#

Yes it's supposed to spawn there, so that it can move to the player's hand

#

Like a draw animation

queen adder
#

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?

spiral narwhal
#

Wait let me record a gif

low path
#

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

spiral narwhal
#

This is my issue

#

If I uncomment the set parent line, there is an offset

queen adder
#

Are the cards prefabs?

spiral narwhal
#

Yes

low path
#

set parent, set anchor to 0, then set local position to 0

queen adder
#

Should world position stays be set to false?

spiral narwhal
low path
#

you might be able to not set anchor? not sure

spiral narwhal
#

By anchor to zero, you mean anchoredPosition?

low path
#

yeah

spiral narwhal
#

Didn't work sadly

queen adder
#

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?

spiral narwhal
#

Yeah let me try that

queen adder
#

It might im not sure tbh

queen adder
#

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

queen adder
#

Because newly created ui during runtime doesn’t count screen resolution (I think)

spiral narwhal
#
            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

queen adder
#

Always try that, because when you try the game once finished your gonna have a bad surprise (talking with some experience by now)

spiral narwhal
#

Yup! Picks the right spot as well

queen adder
#

Wait my idea worked?

queen adder
spiral narwhal
queen adder
#

Lowkey was a shot in the dark lmao

#

Im glad it worked tho

spiral narwhal
#

Thanks for the help! :)

queen adder
#

Also keep me updated

#

That game looks sick

languid timber
#

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)

languid timber
#

thank you :)

fading rapids
#

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

summer stump
#

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

fading rapids
#

i thnk u dont understand what im trying to ask

summer stump
fading rapids
#

oh mb

summer stump
fading rapids
#

sorry

summer stump
#

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

fading rapids
#

they do

summer stump
#

And use a physics query wide enough to hit it

rustic jolt
#

Does anyone know if Error lens or something like that exist for Visual Studio? I'm not talking about Visual Studio Code kek

summer stump
fading rapids
#

but ty

#

i understand the problem

summer stump
#

Ok nice, sorry I misunderstood at first. Glad you got it

fading rapids
short hazel
#

It should be enabled by default, but they can be disabled from the settings.

wintry quarry
#

!code

eternal falconBOT
wintry quarry
#
  • don't crosspost
  • format your code properly
  • show all error messages etc you are seeing
  • Make sure your IDE is configured.
verbal dome
#

And what does your ground check look like?

#

Ah I was scrolled up

summer stump
#

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

calm hull
#

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

summer stump
#

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

eternal falconBOT
wintry quarry
#
  1. Configure IDE
  2. Fix compile errors
rich adder
#

it tells you how to fix it, read last sentence

verbal dome
#

What kinda class name is that anyway

rich adder
#

putting a decimal in a script name is def not valid lol

short hazel
#

If you need to keep track of your code changes, use Git instead :)

oblique mountain
#

okay

#

ty

#

sorry

summer stump
#

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

opaque matrix
#

can anyone help me? it doest play the falling animation😭

#

it played it before i added the jumping animation into the code

polar acorn
eternal falconBOT
opaque matrix
#

omg than ks

#

im insane

calm hull
#

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

rancid tinsel
#

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...

▶ Play video
wintry quarry
calm hull
#

where can i learn about that?

summer stump
rancid tinsel
#

i think i named it something else by mistake

#

thank you

summer stump
#

The words to the right are in the words to the left

wind raptor
#

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 '['

short hazel
#

You cannot create arrays with the [ ] syntax in the C# version Unity is using

wind raptor
#

ah. k

short hazel
#

You need to do something like = { 'a', 'A' } or = new char[] { 'a', 'A' }

wind raptor
#

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?

short hazel
#

With a for loop? What are you trying to do here?

wind raptor
#

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

short hazel
#

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++) { }
wind raptor
#

I'm just being lazy

#

Right but ultimately I should probably be putting the HID codes into an enumerator anyway

calm hull
#

public virtual is used when you have heritage but its implemented in the father right==

#

??*

wintry quarry
calm hull
#

yes sorry

#

not english

wintry quarry
#

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.

short hazel
calm hull
#

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

wintry quarry
#

virtual means you may override
abstract means you must override

calm hull
#

ohhhh i see

wintry quarry
#

and if you have neither abstract nor virtual , then you cannot override

west sonnet
#

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?

summer stump
short hazel
#

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?

short hazel
#

Triple

summer stump
#

Triple kill

west sonnet
west sonnet
summer stump
wintry quarry
# west sonnet No

you'll have to show your code because your explanation doesn't add up.

west sonnet
wintry quarry
#

because it mentions multiples

west sonnet
#

I meant that I have multiple, I've just copied and pasted them

#

I have 2

wintry quarry
#

if there's a prefab being used to spawn things, there should be ZERO enemies in the scene at edit time

wintry quarry
#

this is a code channel after all

#

we'd want to see the enemy script and whatever script is damaging/killing the enemies

west sonnet
#

!Code

eternal falconBOT
west sonnet
opaque matrix
#

chatgpt the goat with helping!!!

west sonnet
#

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

calm hull
#

@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?

summer stump
calm hull
#

maybe there is a better option

wintry quarry
#

you said it had to do with enemies dying

opaque matrix
west sonnet
summer stump
west sonnet
#

When I kill an enemy, the bool which determines if the enemy is alive turns to false. i thought this might be the issue?

wintry quarry
#

I don't see such a bool in your code

#

I see canKillPlayer

opaque matrix
west sonnet
#

The bullets from the players gun are particles

wintry quarry
calm hull
#

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?

wintry quarry
#

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

west sonnet
#

I should check for the canKillPlayer on the collided object?

wintry quarry
#

yes...

#

doesn't that make sense to you?

brave robin
#

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

west sonnet
#

This is what I've done. Is this correct? Because I still have the same issue

rare basin
#

Or just use Try GetComponent

queen adder
#

TryGetComponent is the cleanest approach

brave robin
# west sonnet How do I do that?

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

timber comet
timber comet
queen adder
#

wrap that in a if statement

#
{
  reference.MethodToCall()
}```
timber comet
queen adder
#

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

west sonnet
queen adder
#

Multiple return types

timber comet
#

otherwise it wont work

queen adder
#

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

timber comet
#

but i added this so you have a reference to that component

#

so you can use that in your script as a normal variable

queen adder
#

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

timber comet
queen adder
short hazel
#

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

brave robin
#

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.

inner bane
#

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?

west sonnet
#

Is this correct? Because now no enemy does damage to me

rich adder
#

jesus

wintry quarry
#

Also there's no need for == true

rich adder
west sonnet
#

😦

verbal dome
#

Does the enemy have child objects with colliders?

west sonnet
low path
#

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

verbal dome
#

Isn't the component on its parent instead?

calm hull
#

how can i load a list of Characters from the combatManager? like have them all in the list

calm hull
#

its a empty GameObject i did to manage the combatOrder

#

and i need to fill the list with all the characters

verbal dome
#

Each character could add itself to the list in Start, for example

#

combatOrder is/has a script component, right?

calm hull
#

yes!

#

let me send it

#

!code

eternal falconBOT
calm hull
#
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

verbal dome
#

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

calm hull
#

so in the start of the objects?

#

i see

#

how can i make it a singleton sorry

verbal dome
#

Give it a read, it will be useful in game dev.

#

For these kinds of manager classes

calm hull
#

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

verbal dome
#

It's a very common pattern in game dev

timber comet
verbal dome
#

As long as you know that only one instance of the singleton will exist

timber comet
calm hull
#

i see

#

i dont break the encapsulation

timber comet
#

But for example it cannot be in a Enemy script, ‘cause you need more than one

calm hull
#

im new in game dev obv

#

i see

timber comet
#

No need to encapsulations

#

You can do it, also, on Awake

calm hull
#

what on awake

verbal dome
timber comet
#

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()

timber comet
verbal dome
#

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.

calm hull
#

i see

verbal dome
#

Because you can be sure that every object's Awake has already been called when Start is called

calm hull
#

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?

rocky canyon
#

may be useful

hexed terrace
#

Youre CombatManager.Instance hasn't been set to anything

rocky canyon
#

you got this part

#

but are missing this part

calm hull
#

oh that on Awake is needed

#

i thought was other way of doing the same

rocky canyon
#

check out that site

#

theres different ways to do it

verbal dome
#

I linked it a moment ago

rocky canyon
calm hull
#

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

verbal dome
#

Private fields won't be visible unless you tell unity to serialize them

wintry quarry
calm hull
#

cause it say i cant have both this one and the one i had

#

i mean sorry if my questions are stupid

verbal dome
#

Same list

#

Just add the SerializeField attribute

calm hull
#

ohhhh

verbal dome
#

But yep you can also use Debug.Log to print stuff out

calm hull
#

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

verbal dome
#

No worries, they were not stupid questions

calm hull
#

i need to read more documentation

#

but its diffult some times

sand frost
#

Guys why would I use while() instead of an if() in the update void?

low dawn
#

i js spent like 3 hours

#

trying to find out why intelisense wouldnt work

frosty hound
low dawn
#

im gonna cry

sand frost
#

If

frosty hound
#

No, never use while unless you know what you're doing.

sand frost
#

Oh

#

Unity learn taught me while()

rocky canyon
#

and btw its an Update Method or Function void is the return type..

#

like Vector3 or Float

sand frost
#

Ha

#

Ah

frosty hound
rocky canyon
#

it irks me to hear "update void" or "why my void not work" lol

sand frost
#

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 💀

clear seal
#

i modified my canon for it to shoot only if reloaded and it weirdly does not work

rocky canyon
#

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

formal arch
#

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?

wintry quarry
wintry quarry
rocky canyon
#

why do this in start? if ur onenable does it anyway?

formal arch
#

the start function is running twice

wintry quarry
formal arch
short hazel
#

A class instance that's inherited is only present once. There isn't one instance per class definition

rocky canyon
#

ahh okay

formal arch
wintry quarry
clear seal
rocky canyon
#

you can pass context thru the debug

short hazel
rocky canyon
#

to see whats running it

#

Debug.Log("Start has run, by: " + this);

formal arch
#

what would i put in to reference what is calling it

rocky canyon
#

that way to see why it gets run twice

wintry quarry
short hazel
#

Debug.Log("message", gameObject) - upon selecting the log in the console, it'll highlight in the Hierarchy which object sent it

rocky canyon
#

whats running it the second time.

formal arch
rocky canyon
#

thats why the extra context..

#

it should only be run once.. unless theres two versions of it

wintry quarry
rocky canyon
#

u cant manually call the Start() function from what im aware

wintry quarry
#

t: WeaponManager

#

(if that's the script name)

formal arch
#

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

rocky canyon
#

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

short hazel
#
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.

radiant frigate
#

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?

wintry quarry
#

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

wintry quarry
rocky canyon
radiant frigate
wintry quarry
#

convert your mouse position to a oworld space position is what you need

radiant frigate
#

and how do i do that?

wintry quarry
radiant frigate
#

srry im very new at programming and just got back at it again

rocky canyon
#
        Vector3 mousePosition = Input.mousePosition;
        transform.position = mousePosition;

        Debug.Log($"{mousePosition} + {transform.position}");
queen adder
#

can someone help me find the part of the script where when you finish dialogue it switches the scene

radiant frigate
#

i dont know if that changes something at all tho

rocky canyon
#

doesn't matter, it'll still log the same..

#

theres a bit more to it than setting it = to mouse position

short hazel
radiant frigate
#

omw and ty for the help!

queen adder
#

oof

#

ima just put a button

#

that says finished or skip

#

its going well

radiant frigate
short hazel
# queen adder ima just put a button

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

queen adder
#

i already got button and closed unity out
I got it covered.

radiant frigate
#

i think this should work right?

slender nymph
#

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

radiant frigate
#

so i should just do z = -1?

calm hull
#

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

rocky canyon
#

z would be in front of ur camera.

#

so 10 is a normal go-to

clear seal
rocky canyon
#

thanks lol

rocky canyon
#

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

clear seal
#

air strike

rocky canyon
#

thats what the crosshair is for..

#

but more for like grenades

clear seal
rocky canyon
#

gonna work out a parabola formula to get a good arch

nocturne parcel
calm hull
#

exactly that yes

#

i made a singletone and i have all the objects on a list

rocky canyon
#

my project will also need a system like this

night mural
nocturne parcel
#

Well, there are many ways to do that. It's a very broad question. I suggest trying find some tutorials.

rocky canyon
#

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

nocturne parcel
#

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).

night mural
clear seal
nocturne parcel
#

I think I overcomplicated lol

rocky canyon
#

something to look thru to get u started maybe

naive lion
#
    {
        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
rocky canyon
slender nymph
clear seal
rocky canyon
#

you can check the code here.. but its a WIP and pretty nasty atm

rocky canyon
#

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

clear seal
rocky canyon
#

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)

clear seal
#

👁️ 👄 👁️

rocky canyon
#

same with the hold.. if i move off the object hold becomes false.. if i release the mouse hold becomes false..

clear seal
#

i d not understand

#

i will check it later

lost anvil
clear seal
#

is it the same tho?

rocky canyon
#

you can see the booleans change on the right..

clear seal
#

the door he showed looks like it's the same

rocky canyon
#

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 😄

spiral narwhal
#

_transformContainer.localRotation = Quaternion.Euler(0f, 0f, degrees);
How would I do this smoothly?

rocky canyon
#

that i need to refactor at this point

clear seal
#

perfect :0

#

i dont understand but still looks interesting

spiral narwhal
clear seal
rocky canyon
#

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

lost anvil
#

ah right gotcha, ill have a crack at it thanks

rocky canyon
#

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

lost anvil
#

would that be simpler?

#

because it sounds it

naive lion
#

or am i still misunderstanding

slender nymph
#

why are you even comparing the layer in the first place

naive lion
#

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

rocky canyon
# lost anvil because it sounds it

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...

▶ Play video
slender nymph
rocky canyon
#

but u could take the shortcut of knowing exactly what axis ur rotating on.. then ud just need mouse values..

clear seal
rocky canyon
#

rotate this way or that way

rocky canyon
clear seal
naive lion
clear seal
#

i did not understand when i wanted to change it

rocky canyon
#

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

dapper zenith
#

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

spare mountain
rocky canyon
#

it may be off the screen

#

my animation window always goes on my 2nd monitor for who knows what reason

dapper zenith
#

yeah it was on my Graphics tablet that i couldnt see because it was turned off lol

rocky canyon
#

reset ur layout

#

and it'll make everything where it should be default

spiral narwhal
#

How do I check if localRotation is approximately a certain value?

rocky canyon
#

use a variable and expose it in the inspector.

spiral narwhal
#

No in code

#

like Vector2 Distance < 0.1f

rocky canyon
#

ohhh mb lol 🤣

slender nymph
naive lion
spiral narwhal
slender nymph
rocky canyon
#
if (Quaternion.Angle(transform.localRotation, targetRotation) < angleThreshold)
{

}```
naive lion
#

appreciate the pointers

rocky canyon
#

no problem, ive never used it.. but the docs seems to say thats how it works

slender nymph
rocky canyon
#

and angleThreshold would be something small.. the smaller the closer it'd have to be to the target for it to return true

calm hull
#

why i cant use
enemy1Unit.TakeDamage(damage);
if the enemy unit is a child of other class?

slender nymph
#

what happens when you try

calm hull
#

it says Unity dont find the definition for the method

#

but its written down

slender nymph
#

can you provide actual error messages instead of a vague approximation of it

calm hull
#

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?).

slender nymph
#

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

calm hull
#

let me send it sorry

#

!code

eternal falconBOT
calm hull
#

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

slender nymph
rocky canyon
#

show Unit

#

that's what the error is about.

slender nymph
#

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

calm hull
#

i see... thought i could declare units on derivative classes and access the ,ethods

slender nymph
#

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

pastel dome
#

it keeps getting faster the longer i hold down fire

#

its supposed to fire every 1 second

slender nymph
#

what is the value of volleyDelay (in the inspector)

#

because that appears to be the only thing that prevents it from firing again

rocky canyon
#

in fire volly ur not resetting the velocity..

#

as a result each new projectile inherits the velocity of the previous one

pastel dome
#

0.8 second

calm hull
slender nymph
pastel dome
#

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

calm hull
#

you mean when i declare it? or the class of enemy itself

rocky canyon
#

different issue then...

#

how are u calling the function to fire them?

rocky canyon
#

it can't find the TakeDamage() function

calm hull
#

but its there 😢

rocky canyon
#

show the unit script

#

youve shown Enemy1 and BattleManager but not Unit so far

rocky canyon
#

no thats BattleManager

slender nymph
rocky canyon
#

i wanna see Unit

#

or boxfriend may already have a solution.. idk

calm hull
#

omg

#

i got it

#

finally

#

thanks for the patience @slender nymph

haughty stream
#

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.

wintry quarry
haughty stream
vernal plume
#

how would i make it so this only applies to me going forward

#

instead of both forward & backwards

rocky canyon
#

if verticalInput is positive..

vernal plume
#

like this?

wintry quarry
#

that's negative

vernal plume
#

oh wait yea

rigid cobalt
#

is this code only for 3d or does it work for 2d

summer stump
summer stump
rigid cobalt
#

thanks

wintry quarry
sour ruin
#

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?

sour ruin
#

👍

rocky canyon
#

up to u how u use them

#

either exclusively or inclusively

rigid cobalt
oak mist
#

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

summer stump
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

rocky canyon
rigid cobalt
#

alright i will check it out

summer stump
#

Oh yeah, that one costs money? No, it's trash

rocky canyon
#

just offset the object (the child) and rotate the main object

rigid cobalt
summer stump
oak mist
rigid cobalt
#

nah its free if u go to the dudes channel

oak mist
#

so i would have to create another empty gameObject for that gameObject to move around?

rocky canyon
#

do u want it to look at a certain target?

oak mist
#

yes

#

the target moves in an arc

rocky canyon
#

as long as u have the gun of the turret facing the same direction as the forward axis z then it should work fine

chilly edge
#

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]

oak mist
#

thank you

#

just wanted to make sure

summer stump
rigid cobalt
#

ok

#

wait why is k banned

summer stump
#

The message explains why

rigid cobalt
#

ohhh

rose imp
#

It keeps saying the non convex mesh collider with non kinetmatic body doesn’t work, any tips on how to fix?

oak mist
#

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

rocky canyon
#

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)

mighty prairie
#

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?

summer stump
mighty prairie
summer stump
slender nymph
#

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

mighty prairie
#

Oh I see, I'll do that, that is why i was hoping to hide them over delete them hm

slender nymph
#

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

mighty prairie
supple citrus
#

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

vernal minnow
#

Would a list of arrays not work?

rocky canyon
#

lol! thats the only other thing i was thinking of too 😄

vernal minnow
#

I was trying to crack a joke tbh😅

#

He most likely needs the list of lists

rocky canyon
#

what about a Class? with a constructor..

eternal needle
rocky canyon
#

and list of Classes instead..

vernal minnow
cosmic dagger
supple citrus
rocky canyon
#
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

sour dome
#

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.

summer stump
#

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

eternal falconBOT
rich adder
#

!screenshots

eternal falconBOT
#

mad No

Be mindful, if someone requests your code as text, don't send a screenshot!

sour dome
# rich adder !code

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.

cloud gull
#

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?

rich adder
queen adder
craggy oxide
#

what's the difference between Quaternion.Euler(0, 0, 0) and Vector3(0, 0, 0)?

rich adder
craggy oxide
#

so Quaternion.Euler is essentially just the Vector3 of transform.rotation?

rich adder
#

its euler angles to quaternion

#

in unity what you see in inspector is euler angles, so only xyz needed

craggy oxide
#

What's the difference between transform.rotation and transform.localRotation?

north kiln
#

!docs

eternal falconBOT
craggy oxide
#

-_-

static cedar
supple citrus
#

lol

#

never seen that before

rich adder
#

tuple

ivory bobcat
supple citrus
#

shit

#

list is {} isnt it

summer stump
#

myList = new() { value1, value2 }

#

I can't remember

ivory bobcat
#

List is a dynamic collection of items. A tuple-value is a coupling of several values.

rich adder
#

hmm yeah they prob tried to init it with (f,f,f)

supple citrus
#

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

summer stump
#

You can definitely serialize Vector3 though

supple citrus
#

When i try it just bugs out

#

and this guy said it 7 years ago

summer stump
supple citrus
#

A list of everything im saving

summer stump
#

And what are you serializing with?

supple citrus
#

Json

summer stump
#

Show the declaration

summer stump
# supple citrus Json

And json is the format, what are you using to serialize TO json?
Different serializers have different capabilities

supple citrus
#

JsonUtility?

rich adder
supple citrus
#

I clearly do not know how to use JsonUtility

#

I will continue doing the work around and just store it as a text

#

🙏

rich adder
supple citrus
rich adder
#

looks like trying to serialize a MB?

supple citrus
#

Yeah but thats after doing multiple

rich adder
#

just save the data on it in a plain c# object

#

don't use mb

supple citrus
#

what is mb :d

rich adder
#

Monobehaviour

supple citrus
#

I was serializing this list

rich adder
#

preset is serializable?

supple citrus
#

Ye

#

preset has monobehaviour though

#

if thats an issue

summer stump
rich adder
#

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

supple citrus
#

What does a successful serialization look like lol

#

Not this i am guessing

wintry quarry
grand sigil
#

how do you make a height of an object based on the overall height of its children?

supple citrus
#

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

wintry quarry
supple citrus
#

I was told JsonUtility is good for all Unity variable types

wintry quarry
#

idk what "all unity variable types" means

#

that's very vague, and definitely not true.

grand sigil
#

my bad

summer stump
rich adder
#

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)

craggy oxide
#

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

polar acorn
wintry quarry
cosmic dagger
craggy oxide
wintry quarry
#

a vector is a direction and a magnitude all in one

craggy oxide
#

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"

wintry quarry
#

are you wanting to add forces or are you wanting to set the velocity directly or are you wanting to set the position directly?

wintry quarry
craggy oxide
#

either #1 or #2, definitely not #3

polar acorn
#

It takes a force

wintry quarry
craggy oxide
#

actually this would be easier to send the code

wintry quarry
#

maybe share your code

#

yes

craggy oxide
#

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);
    }  
wintry quarry
#

it belongs in FixedUpdate only

#

you also shouldn't be multiplying the force by deltaTime

craggy oxide
#

oh yeah haha

#

double oh yeah

#

god damnit

wintry quarry
#

and you shouldn't be using Impulse for continuous forces

craggy oxide
#

okay that part i didn't know

wintry quarry
#

you did 3 things wrong here

craggy oxide
#

what should i use instead

wintry quarry
#

nothing

#

the default

#

i mean it really depends what kind of effect you're going for

craggy oxide
wintry quarry
#

why are you adding two forces as well?

craggy oxide
#

the 3rd thing i dont have much experience with tho

wintry quarry
#

Why not just one force in the direction you want?

craggy oxide
wintry quarry
#

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

craggy oxide
#

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

wintry quarry
#

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)

craggy oxide
#

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

wintry quarry
#

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)

craggy oxide
#

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

wintry quarry
#

Well Rigidbody doesn't have a gravity property

#

Unity 3D Physics has only a global gravity property
Unless this is 2D

craggy oxide
#

how would i go about creating object-oriented inverted gravity

wintry quarry
#

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

craggy oxide
#

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

wintry quarry
wintry quarry
#

also, assuming you set your gravity vector to have a positive y value

craggy oxide
#

wouldn't there be conflict between the two forces though

wintry quarry
craggy oxide
#

cause it's not like the custom gravity has any special treatment compared to the other force that would hypothetically create the downwards velocity

craggy oxide
#

lets say i make the gravity inverted but then give the object downwards velocity too wouldn't they cancel each other out

wintry quarry
#

Forces are in conflict all the time

charred spoke
#

You set apply a gravity to false then use your custom one

brazen narwhal
#

does random.range never select/chose the last option?

wintry quarry
#

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

craggy oxide
#

oh okay