#💻┃code-beginner

1 messages · Page 500 of 1

valid turtle
#
&& SchloppyLebt.SchloppyLebt == true)

Why SchloppyLebt.SchloppyLebt?

#

why not SchloppyScript.SchloppyLebt

deft grail
valid turtle
#

thats what I named the bool

#

which is a variable

#

correct?

deft grail
#

lol

#

the right one is what you named your bool, so it matters

#

the left one is what you named your variable, this can be anything

valid turtle
#

So I could put anything on the left rn and it would always work?

deft grail
valid turtle
#

what variable

#

which to be exact*

north kiln
#

the one that you're referring to with this line of code

#

you declared a variable with a name, you have to use that same name to refer to it

#

you can name it almost whatever you want

valid turtle
#

But the bool IS the variable no?

deft grail
#

1 for the script

#

1 for the bool

valid turtle
#

How are they named the same thing then tho

deft grail
valid turtle
#

No

deft grail
#

yes

valid turtle
#

I only named the bool like that

#

Xd

north kiln
#

public SChloppyScript SchloppyLebt;

#

You named it SchloppyLebt

valid turtle
#

OHHH

deft grail
#

exactly

valid turtle
#

Okay now I understand

#

I thought SchloppyLebt is used there so the current script knows that I want to use the bool

north kiln
#

It's a variable name, you can call it what you want

deft grail
deft grail
#

i said it at least 5 times 😂

valid turtle
#

Im so sorry

#

xD

crimson whale
#

The barrel of the cannon is not facing the enemy as it should and seems to adjust the base transform of the barrel. When I set the barrel's y rotation to 0, it isn't the same as 0 y rotation when I start editor playtesting.

    GameObject target = GameObject.Find("Enemy_" + targetID);
    if (target != null) {
        Transform barrelTransform = transform.Find("Barrel");
        if (barrelTransform != null) {
            Vector3 direction = (target.transform.position - barrelTransform.position).normalized;
            direction.y = 0;
            Quaternion lookRotation = Quaternion.LookRotation(direction);
            barrelTransform.rotation = Quaternion.Euler(-90, lookRotation.eulerAngles.y, -90);
        }
        else {
            Debug.LogError("Barrel object not found.");
        }
    }
    else {
        Debug.LogError("Target not found.");
        isTargeting = false;
    }
}```

Any help is appreciated.
valid turtle
#

So after 4 hours I fixed the isssue and understood it.

Thank you guys. ❤️

deft grail
valid turtle
deft grail
deft grail
#

they use the script name usually

#

for example public Rigidbody2D rigidbody; is what i would use
i wouldnt use public Rigidbody2D velocity; just because i want to do velocity.velocity

valid turtle
#

So like this:

public SchloppyScipt SchloppyScipt;

?

crimson whale
deft grail
crimson whale
#

It shouldnt rotate around that point though

deft grail
crimson whale
#

Hows come? Is this just a workaround for the issue

deft grail
crimson whale
#

Well I'm not understanding much about the issue as I have no clue why its happening

#

0 y rotation at the start of the project running and in the prefab editing mode is different than 0 y rotation after its tried looking towards a target

crimson whale
#

Which makes 0 sense, like the origin is being changed in teh code

deft grail
#

maybe thats why

#

the only difference in the 3 pictures you show i see is the z changed

#

the 2 pictures on the right are identical

crimson whale
#

Ok ill try that give me a few

#

🤷‍♂️@deft grail

#

A little bit more: the barrel slowly rotates towards that position without the Y changing at all, and then stays there

fierce geode
#

Is there any way to have a static variable show up in the inspector, because I want to have a static List of Items that any script can grab; but once I make it static, it disappears from the inspector, which means I can't add it. My only solution I can think of is like an in between a variable that isn't static, but when the game starts; it puts all the items into the static list.

deft grail
graceful osprey
#

someone can help me, post processing is not being applied

graceful osprey
marble hemlock
#

have decided to re-evaulate

#

should i use a rigidbody and attempt to code everything it doesnt do like a character controller

or should i use a character controller to get it to interact with physics

rich adder
#

its a physics object anyway

marble hemlock
#

i thought they ignored physics

rich adder
#

its like a mix kinematic type controller

#

calls OnTriggerEnter methods and OnCharacterControllerHit

#

but like kinematic rb it ignores external physics forces though

marble hemlock
#

in a frustrated rage of trying to figure out how to work with rigidbodies, i may have deleted a large chunk of my code

#

i probably have it saved somewhere

teal viper
marble hemlock
#

time to figure out what that is thinksmart

swift pilot
#

guys i need help with this

#

heres the script

#

wait

#

sending

#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Inventory : MonoBehaviour
{
private const int SLOTS = 9;

private IList<InventorySlot> mSlots = new List<InventorySlot>();

public event EventHandler<InventoryEventArgs> ItemAdded;
public event EventHandler<InventoryEventArgs> ItemRemoved;
public event EventHandler<InventoryEventArgs> ItemUsed;

public Inventory()
{
    for (int i = 0; i < SLOTS; i++)
    {
        mSlots.Add(new InventorySlot(i));
    }
}

private InventorySlot FindStackableSlot(InventoryItemBase item)
{
    foreach (InventorySlot slot in mSlots)
    {
        if (slot.IsStackable(item))
            return slot;
    }
    return null;
}

private InventorySlot FindNextEmptySlot()
{
    foreach (InventorySlot slot in mSlots)
    {
        if (slot.IsEmpty)
            return slot;
    }
    return null;
}

public void AddItem(InventoryItemBase item)
{
    InventorySlot freeSlot = FindStackableSlot(item);
    if (freeSlot == null)
    {
        freeSlot = FindNextEmptySlot();
    }
    if (freeSlot != null)
    {
        freeSlot.AddItem(item);

        if (ItemAdded != null)
        {
            ItemAdded(this, new InventoryEventArgs(item));
        }

    }
}

internal void UseItem(InventoryItemBase item)
{
    if (ItemUsed != null)
    {
        ItemUsed(this, new InventoryEventArgs(item));
    }

    item.OnUse();
}

public void RemoveItem(InventoryItemBase item)
{
    foreach (InventorySlot slot in mSlots)
    {
        if (slot.Remove(item))
        {
            if (ItemRemoved != null)
            {
                ItemRemoved(this, new InventoryEventArgs(item));
            }
            break;
        }

    }
}

}

rich adder
swift pilot
rich adder
#

add the namespace?

#

also !ide

eternal falconBOT
swift pilot
#

i did vs code

#

config

rich adder
#

not likely and if it were you can use quick-refactor to add the namespace

swift pilot
#

im quiet new to this so can someone explain whats a namespace..... 💀

swift pilot
#

bet

quick pollen
#

So let me get this straight
if I have a Vector3(0f, 1f, 2f), would Vector3.normalized be (0f, 0.5f, 1f)?

verbal dome
#

No, it will make its length 1.
(0, 0.5, 1) has a length of more than 1

quick pollen
#

what would it be equal to then?

verbal dome
#

I'm not a calculator, why not test it yourself lol

quick pollen
#

fair enough

quick pollen
modest dust
modest dust
#

Or when making diagonal movement the same speed as when walking up/down/left/right only

quick pollen
#

i see i see

#

yeah I was thinking of using it for charactercontroller movement

#

because I wanted a kind of "knockback" effect

#

thank you!

verbal dome
quick pollen
#

yeah, I basically want to take the direction from the enemy to the player, and add force in that direction

#

so yeah

#

this should be it

#

if it wasnt normalized itd probably make me get knocked back more or less, depending on the distance

#

which honestly, doesnt sound too bad, I could make that a mechanic

#

but yea

modest dust
verbal dome
#

Sure.

modest dust
#

But yeah, you basically want the normalized direction at the very least

quick pollen
#

although a different issue:
I'm using a charactercontroller to move the player, and if I call controller.Move() inside of fixedupdate, it jitters, while if I call it in update, it moves the character more/less depending on the framerate

verbal dome
#

Should use Time.deltaTime when calculating the movement in Update

quick pollen
#

I am

verbal dome
#

Show code?

quick pollen
#

or do you mean multiply the force with Time.deltaTime?

verbal dome
#

If by force you mean the value you pass into Move

quick pollen
#

a yea ur right

#

I mean this is the thing I have

    void ControllerMove(){
        forceToAdd = Vector3.Lerp(forceToAdd, Vector3.zero, Mathf.Pow(forceFraction, 100 * Time.deltaTime));
        controller.Move(forceToAdd);
    }
    public void AddForce(Vector3 direction, float force){
        forceToAdd += direction.normalized * force;
    }
}```
#

and I call ControllerMove() in update

#

so I'll just multiply ForceToAdd with Time.deltaTime

#

wrong vid

#

fuck

#

sometimes it launches me over the entire map, other times it barely knocks me an inch

#
                Vector3 knockbackDirection = transform.position - enemy.transform.position;
                knockbackDirection.y = 0;
                movement.AddForce(knockbackDirection, knockBackForce);```
modest dust
#

You're not normalizing your knockbackDirection, that's one thing you need to do

quick pollen
modest dust
#

Ah, alright

quick pollen
#
    void ControllerMove(){
        forceToAdd = Vector3.Lerp(forceToAdd, Vector3.zero, Mathf.Pow(forceFraction, 100 * Time.deltaTime));
        controller.Move(forceToAdd * Time.deltaTime);
    }```
#

and this is the function handling the movement

modest dust
#

Then debug it and check the values being passed to AddForce first

#

Either the force somehow changes, or AddForce is being called multiple times, or your lerping is wrong

quick pollen
#

Block only got called once so AddForce only gets called once

#

idk if the normalization is correct tho

modest dust
#

Check the force too

#

And mostly focus on the debug messages when the bug happens

quick pollen
#

it happened there

modest dust
#

Then debug how your forceToAdd changes over time

quick pollen
#

yea it still adds random forces

#

I mean

#

its not 100% random

#

it is more or less the same magnitude

modest dust
#

And what's the expected force?

#

What's the value of knockBackForce?

quick pollen
#

it is 100

quick pollen
#

so if I knock myself back twice, their magnitude should always be the same

modest dust
#

Then debug exactly that

#

Check the values where the knockback seems alright

#

What's the direction, force and resulting forceToAdd magnitude

#

And how it changes over time

#

Same thing when the knockback is too big, check everything and find out which part of the code causes this behaviour

quick pollen
#

okay I think I found a fix

#

I started using fixedDeltaTime in my wrong lerp

#

which seems to produce the same magnitude every time

flint thicket
#

hey can i get some help

eternal needle
eternal falconBOT
flint thicket
#

i'm trying to recreate this mechinic in unity

#

the dash and slash

#

how can i make this mechinic

#

in unity

#

bro i googled i cant find anything about it

eternal needle
#

theres really a ton of different steps here. all depends how you want it to look and feel. No one will be able to give you an exact answer here on how to do it
The first part already depends on how you're moving the player.

flint thicket
#

i have the movement code do you want to see it

eternal needle
#

break the problem down also, you have a dash and slash, this is 2 different problems. The dash depends on how you're moving. The slash is gonna be some vfx and like a physics query to get enemies within the area

flint thicket
#

so how so i make the dash daigonal

#

i have some code to relate to it but it doesn't work

#
Transform [] listOfDashableObjects; // Find list of dashable objects

void Update() {
  if (inAir) {
    // Get the closest dashable object
    Transform closest = null;
    float distance = Mathf.Infinity;
    foreach(var obj in listOfDashableObjects) {
      float dist = Vector3.Distance(transform.position, obj.position);
      if (dist < distance /** TODO: Add a max distance check here */) { 
       closest = obj;
       distance = dist;
      }
    }

    // if the user presses dash
    if (closest != null && Input.GetDown("dash")) {
        Dash(); // Add a force at that direction    
    }
  }
}

     💡 💡
👨   |  |
#
void DashTowards(Transform target) {
  Vector2 direction = new Vector2(0.5f, 0.5f); // 45deg up to the right

  // If the target is to the left of us, lets flip the dash direction around
  if (target.x < transform.x) { 
    direction.x *= -1;
  }

  // If the target is below, go down
  if (target.y < transform.y) { 
    direction.y *= -1;
  }

  rigidbody.AddFroce(direction * dashForce);
}

eternal needle
eternal falconBOT
flint thicket
#

i dont thin thats the problem my ide is not configured

#

also here is the player movement code

eternal needle
#

also the readme tells you how to send code

flint thicket
#

yah this my first time asking for help

#

oh well i try sovle it myself

eternal needle
tulip nimbus
#

Is there a tutorial anyone can recommend on timing in Unity?

I just cant find anything that really fits my needs regarding this topic, what im trying to do is for example:

gameObject.SetActive(false);
(Now wait for 5 or so seconds)
gameObject.SetActive(true);

How can i do something like this without using a timer variable or new Method all the time?

frigid veldt
#

hello, I have a question regarding sprite arrays

currently made a little dialogue system with text and audio, but now I want to add 2 character portraits. I created a Sprite[] array called images and put 4 images into it. Theres a function called NextLine() and I want the image to switch every time thats played, but ive been stuck on it for 3 hours now. Any ideas?

radiant frigate
#

how can i reference the child of an object i want to instantiate (that doesnt exist previously in the scene) via code?

eternal needle
# frigid veldt

Does the value of index here also align with what image should be on? Because if so you could just reuse that variable and access your array[index] and assign that to whatever image you need.

eternal needle
frigid veldt
eternal needle
#

I can see that, which is why I ask if that value would be the same for images. You can reuse it if so

frigid veldt
#

I think its reusable

radiant frigate
eternal needle
radiant frigate
# radiant frigate

the green points are start point and the red ones are endpoints, so now i just try to allign the start point to the last current endpoint

#

maybe its a bad way of doing it but thats the only way i thought that could work

eternal needle
#

I also have absolutely no clue what you're showing here or what that has to do in relation of grabbing a child object. It seems like you're talking about a new problem

radiant frigate
#

but yeah your solution works

wary canopy
#

Sir, why my codeium won't shows up on my left panel as it used to be @swift crag

#

this is my first week with codeium

#

previously I just block the whole code and ask to analyze

worldly bronze
#

I need to link a .uss stylesheet to my UXML, but I cannot see anywhere I can add it to be my visualelement.. ?

#

There is no + or anywhere I can drop my .uss it is only under data source I can do that, but that seems to be wrong, especially 'cause there is a place for stylesheets

#

I also just did the one where I click the + here:

#

But that also seems to be wrong, since it is not connected to the visual element then.

rocky canyon
wary canopy
#

coz previously I just allowed to block my whole code and right click for analyze
now the tool was missing

rocky canyon
#

i usually never use the left panel.. but it should be there if the extension is enabled

wary canopy
#

anyway can we adjust the UI size for the add on ?

swift pilot
#

can someone here help me make a hunger system for the unity 3D game kit

rocky canyon
#

j/k its pretty simple..
the logic is a variable being lerped or movetowards 0 in update

#

then u have a function to add back X amount

#

once empty or < 0 = ded

cosmic dagger
#

decrease (subtract) the hunger variable over time. when something is consumed, increase (add) to its value . . .

swift pilot
#

the thing is

#

i downloaded a hunger and thirst pack

#

and i cant get it to work

#

my original setup had a script named playerontroller

#

so does the hunger and thirst pack

#

so like

#

their clashing

willow scroll
#

Then you have to fix them manually

carmine skiff
#

is there a way tospeed up compilation of code i have a good midrange PC but it feels like so laggy for making smallest changes to code

lapis frigate
#

Is there a way to start coroutine an IEnumirator method inside an IEnumirator method? because everytime I do this its method just doesnt start

willow scroll
#

Is this what you mean?

cosmic dagger
lapis frigate
#

ye but it just doesnt work

willow scroll
#

Show the code

cosmic dagger
eternal falconBOT
lapis frigate
willow scroll
tender stag
#

can you override a class?

#

like u do with methods

#

i want a base class and add to it

#

or would inheretance be better

slender nymph
#

that's what inheritance is for

tender stag
#

right

tender stag
#

what does this mean

slender nymph
#

you can only inherit from one class at a time

#

and an "attachment manager" should not inherit from "attachment". at most it would reference the attachments

tender stag
#

yes i know

#

im just seeing if it even works

#

i have the whole attachment system finished

#

is just im rewriting it

lapis frigate
#

what do I do then

willow scroll
lapis frigate
#

the TypeDialogue method liiterly just doesnt start

willow scroll
#

Please, show it

willow scroll
# tender stag

You cannot inherit from multiple classes. You can inherit from multiple interfaces and a single class

lapis frigate
slender nymph
#

don't modify the string for typewriter style dialogue, instead assign the entire string then modify the maxVisibleCharacters property

#

but if that coroutine isn't being started, then the one you are starting it from is also likely not being started

lapis frigate
#

how do I use the maxVisibleCharacters property?

slender nymph
#

the same way you use any other property

ashen frigate
slender nymph
#

looks like your color has no alpha

ashen frigate
#

alpha ?

rocky canyon
#

transparency

slender nymph
#

that's the A in RGBA

ivory bobcat
#

Maybe show the script that's changing the color

rocky canyon
lapis frigate
#

I think the method just doesnt start

slender nymph
#

using maxVisibleCharacters has nothing at all to do with starting the coroutine.

#

i already told you what is likely not causing it to start

lapis frigate
#

the PlayerTurn method does start

slender nymph
#

prove it

lapis frigate
#

and i would be softlocked

slender nymph
lapis frigate
#

but I can play, the dialogue just doesnt sturt

slender nymph
lapis frigate
#

and when I change the player Turn to void the TypeDialogue does start

slender nymph
rocky canyon
#

the black bar underneath it indicates it has a value of 0 on the alpha..

#

it should be white

ashen frigate
#

but what in code makes it do it ?

slender nymph
#

it's not the code. it's the colors assigned in the inspector like i've already pointed out

rocky canyon
#

the colors that u have assigned in this script

ashen frigate
#

ohh isee the health controller

rocky canyon
#

thats a silly question. as the other script has nothing to do w/ colors at all

ashen frigate
#

you right my bad

rocky canyon
ashen frigate
#

and ty

rocky canyon
#

np 👍 🍀

tender stag
#

holy shit

#

i just discovered generics

#

or whatever its called

#

the T thing

slender nymph
#

this doesn't really seem like a good application of generics tbh

tender stag
#

trust me for my case it is

slender nymph
#

how

tender stag
#

because i need the base class

#

which is AvailableAttachments

#

and then use that

#

but for different things

#

like if i need to add a new attachment

#

i just write it in there

#

instead of like 5 classes at the same time

slender nymph
#

that does not explain how generics are useful here.

tender stag
#

dont worry

willow scroll
#

How to not worry if you've mentioned discovering generics just now?

tender stag
#

and saves me writing the same shit over 20 times

#

instead using a base class

slender nymph
tender stag
#

which i can pass different classes into

tender stag
night valve
#

Why not to make base Attachment class and put code there instead of 20milion places

tender stag
#

which is sight light and muzzle

#

if i wanted to add a new attachment type

#

i'd have to go to each script

#

and add it manually

slender nymph
tender stag
#

brother

#

its fine

#

chill

night valve
tender stag
slender nymph
#

alright, well when your code ends up being confusing spaghetti because you barely understand what you are doing and using a tool that is not right for the job you are using it for, don't come crying here

tender stag
#

sure

willow scroll
tender stag
#

no because one holds information for the holder item

#

which is visible to the player

#

and one is the world item

#

which is picked up

#

its two different things

#

which u cannot put together

#

one hold specific information to itself and the other as well

#

u cant just put this together in one code

#

one class

#

this has to work with my inventory system

#

and as you know every system is different

#

every system has a different design

#

my house is different than urs

willow scroll
#

Supposedly, you mean the item, which exists in the world as a GameObject and its image as a slot?

tender stag
#

i cba

slender nymph
# tender stag and as you know every system is different

finish a thought before pressing enter.
and this phrase right here is a good indicator that perhaps generics are not the right tool for this. generics are good for when multiple systems are similar not different. hence the name "generic"

tender stag
#

i was talking about the inventory system

willow scroll
tender stag
#

thats my point

slender nymph
willow scroll
#

What you need is class ItemData, class ItemController : MonoBehaviour and class ItemSlot : MonoBehaviour

tender stag
#

i am doing that

#

i know how inheritence works

#

and im telling you i cant use it for my attachment system

willow scroll
#

What is you attachment system used for?

tender stag
#

each item that has the AttachableAddon

#

can hold its own attachments

#

so if you attach a scope to an ak

#

it will hold that scope item inside that ak item

#

so next time you pick it up it will still be there

#

and then you have to actually enable the model on the ak model

#

if the specific ak your holding has a scope

willow scroll
#

A scope attached to the ak is supposed to be ak-specific, isn't it?

tender stag
#

yes

#

to that specific item

#

because u can craft many aks

#

so that specific ak has to hold its own attachments
which is what im currently doing

willow scroll
#

So you can have a class, derived from item, to have a field for scope?

verbal dome
#

I just have a component on each gun part that has a list of "plugs" and "sockets" which define what part types can be attached and where

solar arrow
#

is this error coding related? idk what is this

queen adder
queen adder
#

its usually fine to ignore it then, re-open the project

carmine skiff
#

I have no idea what is going on it just seems that VS doesnt like unity anymore

rich adder
carmine skiff
#

nvm fixed both now

gaunt solstice
#

Hey I'm making a top-down tank game in Unity 3D and does anyone have any good tips for making an enemy AI tank? I can use the navmesh system to make it move around and stuff but I am having trouble getting it to actually move like a tank

steep rose
#

although i would do a check for the AI tank to only shoot if the barrel is under a certain threshold of looking at the player

rich adder
#

wdym too much angle now?

steep rose
#

no if you look in the gif, when you go behind the wall and come out the AI tank shoots even when its not looking at you, well so yes the gun has to much angle before shooting target 😅

gaunt solstice
#

well mostly when it gets a point on the navmesh to move to it will turn as it moves to the point which is not something a tank could do, so my current solution is to have it stop and turn to face the point before moving towards it. if youve ever played a video game with tank controls its like that. the problem with that is that while its turning it makes it a very easy target to shoot, so i'd prefer for it to have a turning arc, so it keeps moving while also turning towards the point on the navmesh. i made a video showcasing the 2 turning styles with the player tank that im controlling

rich adder
steep rose
gaunt solstice
#

i know it can do turning in place that problem with that is that it just makes it a very easy target to shoot at

rich adder
steep rose
gaunt solstice
#

I do have some code that I was working on in order to get it to turn in more of an arc, the problem is that it messes with the navmesh so it keeps getting stuck on walls

steep rose
eternal falconBOT
steep rose
#

if you want it to arch i would just get the next position of the navmesh and move and rotate manually there

#

i would also keep the turning in place for if the agent gets confused

carmine skiff
gaunt solstice
steep rose
stiff fjord
#

how would i make it so the forces are constantly being applied till they make conatct then switch

deft grail
#

and in Update you can apply the force if the bool is true

blazing prairie
#

If I am making a android game what should be the save speed is ms for my game to save data consistently onApplocationQuit or any another function

stiff fjord
deft grail
stiff fjord
timber comet
deft grail
#

just do if(goingUp) Up(); in Update

verbal dome
#

And else Down(); assuming this is like Gravity Guy

timber comet
short hazel
#

Unity will wait for all your scripts to have finished executing before it proceeds on rendering the next frame. If one of your scripts doesn't finish (eg. with an infinite loop), you'll freeze it.

#

Remember that when your code runs, nothing else runs (except for multithreaded code - coroutines aren't a part of that)

lost anvil
#

hi, im trying to clamp where the player can rotate the inventory to by the amount of objects but im not sure how i would go about doing it, i had a try with mathf.clamp but that didnt work, is there something i can do to reference if the index of the item list is at the start or end maybe?

input method - https://gdl.space/ewuhuweyoz.cs

short hazel
#

You need a variable to track what the current index you're at in the inventory

lost anvil
#

yeah i do i probably shouldve included that

swift pilot
#

what does this small plus icon next to the box mean

deft grail
swift pilot
#

ohh

#

how do i update 💀

deft grail
#

you can do it there

swift pilot
#

not there

deft grail
lost anvil
short hazel
#

Yep

lost anvil
#

great cheers

deft grail
#

i think i saw it being a button itself before, maybe depends on the Unity version not sure

#

but for you its overrides

swift pilot
#

oh shit it worked thanks alot

short hazel
#

Yeah means the children objects were added, compared to the prefab

swift pilot
#

also for some reason i cant drag the thirst text into the text area in the script in the inspector of the parent

short hazel
#

If you're using TextMeshPro, the type to use in the code is TMP_Text instead of Text

swift pilot
#

yup

#

it is

#

is there a way to make it normal text

deft grail
short hazel
#

Prefer TMP, it's better

deft grail
#

change the variable type like SPR2 said

swift pilot
#

oh

short hazel
#

Plus for simple operations it's used the same in the code, you won't have to change much

swift pilot
#

so i just edit the script and put TMP instead of text

deft grail
swift pilot
#

oh

#

alright

obtuse lagoon
#

hey guys, when i try to log into unity I need a code and i enter it and i get “Invalid code”

deft grail
short hazel
stiff fjord
swift pilot
#

im getting the same issue guys

crisp anvil
#

Hello, my start method isn't running on my prefab when instaitiated

    {
        gameManager = Game_Manager.Instance;
        if (gameManager == null)
        {
            Debug.LogError("Game_Manager instance is null in QuestSlot.");
            return;
        }

        questManager = gameManager.questManager;
        if (questManager == null)
        {
            Debug.LogError("questManager is null in Game_Manager.");
            return;
        }

        questSystemUI = questManager.questSystemUI;
        if (questSystemUI == null)
        {
            Debug.LogError("questSystemUI is null in QuestManager.");
            return;
        }

        Debug.Log("QuestSlot Start");
        Debug.Log(questManager == null ? "questManager is null" : "questManager is not null");
    }```

Any idea why?
The prefab is made during runtime. I get no Debug logs from this, but I do from my Game Manager and stuff.
short hazel
crisp anvil
#

it does

short hazel
#

If you added the script to an instance of the prefab (for example in the scene), make sure to Apply the changes to the prefab itself

crisp anvil
#

prefab is the same, like, If I add more debugging to the void start method it will work, its so confusing

#

it makes no sense ot me

short hazel
#

Do you get any exceptions logged in the Console? Make sure errors are not filtered out

swift pilot
#

heres the scipt that i edited still cant put tmp in the text area

short hazel
#

Also put a log, but at the beginning of Start

short hazel
#

You need to configure your !ide before proceeding any further.

eternal falconBOT
swift pilot
#

already done

crisp anvil
#

No exception or warnings, just my debug logs from other scripts.

#

I figured it out and it was dumb

#

dont wanna talk about it

short hazel
swift pilot
#

so how do i fix it?

#

not the config

#

but the script

short hazel
#

Having a configured editor is required to get help here

languid spire
#

without fixing your config you will get no help here

swift pilot
#

oh

late burrow
#

how to save variable when creating prefab but not save variable when instantiating

swift pilot
#

switched to microsoft visual

short hazel
#

Good choice

tulip nimbus
#

So for a reason i really cannot figure out, my OnTriggerEnter2D does not work anymore all of the sudden.

It worked fine before i added the if (shipDead == true) and IEnumerator ShipDeath.

Why is this?

    void Update()
    {


        if (ship_hp == 0 || ship_hp <= 0)
        {
            shipDead = true;
            
        }

        if (shipDead == true) 
        {
            StartCoroutine(ShipDeath());
            shipDead = false;
        }

        void OnTriggerEnter2D(Collider2D other)
        {
            if (other.gameObject.tag == "Bullet")
            {
                Destroy(other.gameObject);
                ship_hp -= 1;
                AS.PlayOneShot(hit);

            }

        }

        IEnumerator ShipDeath()
        {
            AS.PlayOneShot(explosion);
            Color color = Color.red;
            yield return new WaitForSeconds(1);

            Instantiate(Particles, transform.position, Quaternion.identity);
            yield return new WaitForSeconds(5);
            gameObject.SetActive(false);
            DestroyImmediate(Particles, true);
            yield return null;
            StopAllCoroutines();

        }


    } 
}
swift pilot
short hazel
#

Yes, refer to my comment a bit before

swift pilot
short hazel
#

With your keyboard

swift pilot
#

... 💀

short hazel
#

It's not .TMP_Text = ..., it's .text = ...

#

TMP_Text is the variable type

swift pilot
#

ohhh

languid spire
tulip nimbus
#

Oh, so certain functions do not work when inside the Update method? Do they have to be on their own to work properly?

late burrow
#

can i mark variable as non copyable on instantiate

languid spire
tulip nimbus
#

Thanks alot

steep rose
tulip nimbus
#

i appreciate it

short hazel
#

When they're inside, Unity cannot see them, so it cannot execute them

swift pilot
#

LESS GOO IT WORKED I LOVE THIS SERVER

carmine skiff
#

IS rotation Frame dependant or not my left and right roation on mouse feels so laggy and idk whyand its driving me insane

carmine skiff
verbal dome
#

Depends on your code.

carmine skiff
languid spire
carmine skiff
steep rose
languid spire
steep rose
carmine skiff
languid spire
#

because it shows you exaxctly what is happening and what values you are using. Debugging 101

carmine skiff
#

ive tried using time.deltatime in multiple places just doesnt help at all just makes the rotation not happen pretty much at all

cosmic quail
verbal dome
#

You should do camera rotation in LateUpdate, not Update

steep rose
carmine skiff
carmine skiff
errant fjord
#

hello guys, i have this script that controlls the location of the object , but i want to reference it to a controll those parameters in the shader how do i reference it?

#

the script was made by chatgpt , 😊 just want to controll couple of parameters with the script

short hazel
errant fjord
#

thanks!

bold saffron
#

For some reason This loop never starts:

#

(this is just a small part of the code)

keen dew
#

i > 2 should be i < 2

bold saffron
graceful osprey
#

is there any way to change the tree render distance?

ruby python
#

Hey all,

I'm working on a Vehicle Enter/Exit script and am trying to get the players 'pose' to change using Unity's built in IK solution.

The IK works perfectly 'outside' of the vehicle, but I'm having a weird issue when 'sitting' in the seat.

https://hastebin.com/share/anirakigeg.csharp

I have some 'target objects' attached to the vehicle seat (the idea is that I want to use the same script for multiple vehicles).

I used these 'target objects' as target positions for the IK target object positions (enter the vehicle, hands/legs/spine ik controllers move to the 'target' objects positions. Now, this does actually work (see image), the red Boxes are all in the correct positions.

The issue I'm having is that none of the character bones are moving to them as they should. The controllers still work (I can move them around and the arms/leg bones move, but from where they are in the image.

Can anyone see the issue? Been trying to figure it out for most of the day 😕

earnest wind
languid spire
earnest wind
#

idk never heard someone say method

short hazel
#

void is the return type, indicating that the method does not return any value

deft grail
languid spire
#

void is a return type. what would you call

int Mymethod() {}
short hazel
#

Method is the official name

earnest wind
languid spire
earnest wind
earnest wind
atomic flume
#

Does anybody know the encryption method for .dat save files for mobile unity games?

languid spire
atomic flume
languid spire
#

so ask the developers, they are the only ones that can tell you

atomic flume
short hazel
#

Decompilation/modding/reverse engineering of third party games is not something we offer help with here.

languid spire
#

we do not discuss these things on this server

atomic flume
#

Okay

crimson whale
#
using System.Collections.Generic;
using UnityEngine;

public class ProjectileLogic : MonoBehaviour {
    public int speed;
    public GameObject target;
    public string projectileType;
    void Update() {
        if (target != null) {
            Vector3 direction = (target.transform.position - transform.position).normalized;
            transform.position += direction * speed * Time.deltaTime;

            Quaternion lookRotation = Quaternion.LookRotation(direction);
            transform.rotation = lookRotation;
        }
    }

    void OnCollisionEnter(Collision collision) {
        if (collision.gameObject == target) {
            EnemyInitiate enemyInitiate = target.GetComponent<EnemyInitiate>();
            if (enemyInitiate != null) {
                enemyInitiate.health -= 20;
                Destroy(gameObject);
            }
        }
    }
}```
This ^ is the only code controlling the projectile's movement, and it's only telling it to go towards the target, yet it is equally drawn to the top left of the game towards literally nothing and I can't figure out why. Here's the instantiation code:

```void StartProjectile(int targetID) {
    GameObject target = GameObject.Find("Enemy_" + targetID);
    if (target != null) {
        GameObject newProjectile = Instantiate(cannonProjectile, transform.position, Quaternion.identity);
        ProjectileLogic projectileLogic = newProjectile.GetComponent<ProjectileLogic>();
        if (projectileLogic != null) {
            projectileLogic.target = target;
        }
        else {
            Debug.Log("Projectile logic script could not be found in cannon projectile.");
        }
    }
}```

Any help is greatly appreciated.
short hazel
#

Your projectile has a Rigidbody, yet you move it from the Transform directly. This bypasses the physics engine and might lead to weird results

crimson whale
#

I see, thank you. The issue with removing it is that the collision won't be detected when it hits an enemy, but I can just make it apply the damage once its within a certain range of the enemy rather than colliding if there's no easy workaround.

short hazel
#

You could use the Rigidbody to move it, using the MovePosition() or AddForce() methods

crimson whale
#

Well on second thought, can it pass through objects that are not the one its targeting? If not the alternative might be the way to go

steep rose
#

using the transform doesnt, i would just use the built in rigidbody functions

tulip nimbus
#

Is there a way to make it so that an IEnumerator method "locks" itself so it cannot be called again until the code is finished or yield breaked?

crimson whale
#

And only call it while the variable is false

short hazel
crimson whale
#

Just make it destroy and damage when its within say 1 distance from the target?

#

I don't need it to have physics

#

Just go towards the target

short hazel
#

Do you want realistic (bullet velocity, bullet drop) physics?

crimson whale
#

I do not

#

Making it like COC

#

But going over it has made the answer pretty obvious

#

Thank you :)

short hazel
#

You could make a script that raycasts from the last position of the projectile to the current position, and check that the colliders detected in between contains your enemy

steep rose
#

i would use the rigidbody to detect collisions and use the functions, using translation and detecting collisions yourself every frame by using Overlapsphere or checking the distance is slower than just using the rigidbodies built in collision detection

bold saffron
#

Hello, not sure whether this belongs in code-general but I am trying to make make script spawn in a turret and then set it to TurretList. All the turret prefabs have the turret tag and yet instead of being set on line 79 to feature the three turrets, on line 80 it tells me that turret list is 0 keys long. Does anyone know why this is happening? thanks! (The "GenerateTurret" code is hashed out on lines 75-76)

https://pastebin.com/NSyAHWgZ

tulip nimbus
#

Is there a way to dissable a function so it doesent react anymore? Like OnTriggerEnter doesnt react to any Triggers any longer?

polar acorn
#

Set a boolean on it and as the first line of that function do if (thatBool) return;

#

OnTriggerEnter specifically works on disabled objects because it's often used to "wake up" disabled scripts when the player is near them

tulip nimbus
#

On a diffrent note, when dissabling scripts, is there a status that an object can be in which dissables all interactions and codes? Like gameObject.SetActive() but without the object actually dissaperaring?

ripe shard
#

Officially there is no such state.

tulip nimbus
#

Okay one last thing i wanted to ask today

Theese operators are kind of messing up my code. How do i devide the Operators so they work on their own instead of combining each other?

Which means i want to make it that the if() statement returns true if:
(ship_hp = 0) + (OR ship_hp <= 0) + (AND shootable == true)

not if:

(ship_hp = 0) + (OR ship_hp <= 0 AND shootable == true)

I really hope this is not too confusing to ask for i really dont know how to word it.

#

Do i use commas? Or anything else?

ripe shard
tulip nimbus
#

Thanks, tho

How do i put them to seperate the operators?

ripe shard
eternal needle
tulip nimbus
ripe shard
# tulip nimbus This is great, i was wondering how you call those. Thank you!

This is the complete source of truth, but it has way more info than you need https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions

tulip nimbus
eternal needle
tulip nimbus
#

Ah i get it now. Was confusing since english isnt my first language. So youre saying i can leave out the ship_hp == 0?

eternal needle
#

Yes

tulip nimbus
#

Thats really helpful to know so my code wont be so messy, thanks man!

alpine cairn
#

I NEED he l p

polar acorn
eternal falconBOT
steep rose
#

the debug Path runs, but OVC and i does not, im not sure why 🤔

if(pathfinding)
            {
                Debug.Log("Path");
                while(true){

                    Collider[] OVC = Physics.OverlapSphere(currentnode.position, AISphereRadius, WPtransformmask);
                    Debug.Log("OVC");

                    for (int i = 0; i < OVC.Length; i++){
                        Debug.Log("i");

                     Openednode.Add(OVC[i].transform);

                     float OpenStartCost = Vector3.Distance(OVC[i].transform.position, Startpoint.position);

                     float OpenEndCost = Vector3.Distance(OVC[i].transform.position, Endpoint.position);

                     int OpenIntStart = (int)OpenStartCost;

                     int OpenIntEnd = (int)OpenEndCost;

                     int OpenFinalCost = OpenIntStart + OpenIntEnd;


                      if(FinalCost < distmin && Openednode.Contains(OVC[i].transform)){
                        currentnode = OVC[i].transform;
                        Openednode.Remove(currentnode);
                        Closednode.Add(currentnode);
                      }

                    }
                }
steep rose
teal viper
#

If an error is thrown, the code execution stops. It doesn't matter if you catch the error later on.

alpine cairn
#

help me make first person game

#

plzzz

steep rose
steep rose
alpine cairn
#

help me make first person game

teal viper
alpine cairn
#

stop being rude plez

eternal needle
teal viper
steep rose
alpine cairn
#

why are u mentioning a mod

frosty hound
#

@alpine cairn This isn't the place to spam for people to make games for you. This is a learning server.

alpine cairn
#

im not spamming

steep rose
#

@alpine cairn you might get muted or even worse banned if you keep it up

north kiln
#

You are repeatedly posting "plzzz", which is unecessary spamming

eternal needle
#

Oh sorry I didnt see a mod was already typing.

frosty hound
#

Yes, you are. If you want to collaborate with people, use the Discussions site. !collab

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

alpine cairn
#

im just asking for help not collabing

#

2 different things

steep rose
#

help on what?

frosty hound
#

So ask a specific question.

steep rose
#

speak up

alpine cairn
#

need

north kiln
#

Nope. Post a complete sentence.

frosty hound
#

!mute 1268096070488166451 3d Return when you can actually ask a question.

eternal falconBOT
#

dynoSuccess zen_gull_53076 was muted.

steep rose
eternal needle
#

I've seen others say sometimes you can attach the debugger during it and pause but I've never gotten it myself to work lol

steep rose
teal viper
#

They could attach it to process

steep rose
#

i just closed unity but it didnt close and everything seems fine? im not even gonna question it

steep rose
#

do you need to yield for while(true) or else it will hang unity?

teal viper
#

It would hang any program, not just unity.

steep rose
teal viper
#

In any other case, you need to break out of the loop

dry geyser
#

can anyone help me with this error i cant find or fix with photon's pun2? the error: Got DisconnectMessage. Code: 104 Msg: "InvalidEventCode". Debug Info: {}. the script I believe is causing this is:

teal viper
dry geyser
#

oh ok

bold iron
#

Is there a function that will play when the script ends?

teal viper
bold iron
# teal viper Wdym by "the script ends"?

i have a another script that turns on and off the game object. When it turns off the game object the script associated will also stop. I want it to run a code when the script associated with the game object stops.

teal viper
sour ruin
#

Hi, I'm not sure if this is the best chat to ask but had anyone experienced transform handle offsets that don't align with the actual position and rotation? I have a joint hierarchy for the character and none of the joints are represented correctly. Furthermore trying to rotate the joint rotates it around this phantom handle axis instead of where it's actually located. I know where it's actually located since visually all the meshes are in the right place and rotation + draw gizmo pins the positions correctly, just the handles are off

wintry quarry
#

Right now you likely have it on Center

sour ruin
#

Yup

#

Thanks

waxen adder
#

Anyone else get into a situation, where you feel like you can do something better in your programming, but can't quite think of it?

#

Like, you can get something to work, but the code is kinda weird

lavish topaz
#

I'm new to Unity so I don't have the most experience with cameras, so I decided to look at cinemachine since some tutorials were using it. They used Camera.main to assign the Object to a variable, but when I do that it is null.

I do have the tag as MainCamera for the cinemachine virtual camera object. Everything I can find online says that's the issue but nothing else.

cold stag
#

Someone hepl this is extremely frustrating. I spent the entire weekend on this rpoject and I can't build it. The thing keeps saying UI doesn't exist in the namespace unity. wtf do I do I've literlaly tried everything, reinstalling the editor reinstalling the 2D package and the UI package and trhe textmeshpro packacge deleitng the librarby folder deleting all the visual studio folders reinstalling the visual studio package

eternal needle
eternal needle
waxen adder
wintry quarry
teal viper
bold gale
#

In godot, you can connect a collider signal to a script in another object.
In Unity, a Box Collider calls OnTriggerEnter when something enters the area. Is there a way to connect this function call to another script, or do I have to always add a script to this Box Collider/GameObject if I want to do that/and for every functionality?

wintry quarry
bold gale
#

Is there any way one single gameobject can listen to multiple objects by itself, or do these multiple objects always have to subscribe that one single gameobject first?

languid spire
bold gale
#

i see, the parent isnt a rigidbody, its just a GameObject. I'm doing things with areas in a prefab hallway that a player walks into, and the level will change and add prefabbed hallways depending on the area that the player walks into.
Since the hallways will be generated in runtime i thought it would be easier to have one single manager script listening to those box collider areas rather than having to code multiple box colliders subscribing to one script

solid marlin
#

Hey yall, not sure if this kind of question fits here or not so I apologize if it doesnt, I have decided to start learning unity as I was always interested in game dev. Someone told me that I should learn the C# basics, as in loops, classes and functions mostly. Are those enough to start tinkering around in unity? If yes, do I just look up a random tutorial and go off of that?

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ruby python
#

Mornin' all.

I'm having a bit of a weird issue that I can't for the life of me see where the problem is. I've got a simple 'enter/exit vehicle' script that works almost perfectly.

https://hastebin.com/share/ozetovafoz.csharp

This gets called by an 'interaction' script on the player.

https://hastebin.com/share/ifowokarux.csharp

The issue is that the first time I try to interact to 'drive' the vehicle(s), the switch script behaves as if I am already 'driving' the vehicle (as if the bool isDriving is set to True), and I'm a little confused as to why.

Can anyone see where my error is please?

Video for reference.

https://streamable.com/57yrpn

Watch "2024-09-30 08-34-37" on Streamable.

▶ Play video
eternal needle
astral falcon
solid marlin
#

Thanks for the answers, yeah, I have the concepts already since I programmed in other languages, should I just keep following unity learn until I feel comfortable with smaller projects then learn whatever I need in smaller bits?

ruby python
worthy veldt
#

only those 2 Enter and Exit is changing isDriving ?

ruby python
#

Yeah.

tranquil lintel
#

hi, im a beginner in unity and am currently trying to make a basic crossy road esque game to learn stuff. So basically I want the game over screen to pop up whenver my chicken collides with a car. Both game objects have colliders and the chicken has a kinematic rigid body too. The car is tagged correctly and I don't think theres a problem with layers. But the OnCollisionEnter2D still doesnt execute. Can anybody help me with why?

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.transform.tag == "Car")
        {
            Debug.Log("Game over");
            gameOverScreen.SetActive(true);
            chickenIsAlive = false;
        }
    }
}```
eternal needle
# solid marlin Thanks for the answers, yeah, I have the concepts already since I programmed in ...

have you used java before? c# is basically the same. if so, yea u could just keep going on unity learn or make your own small project if you have an idea. Really the tutorials should just be there to tell you what exists in unity, and roughly what its used for. If you understand coding well, you'll quickly see that most tutorials really are bad. for example, the unity docs is purely just to show you how to use the functions. a lot of the time the code itself is questionable. Not sure about unity learn as ive done like 2 lessons on it.
The same goes for youtube tutorials. Most are really bad when you look closely. But you can always use them to get an idea of what exists or how something can roughly be done

astral falcon
worthy veldt
#

he put it in update, and isdriving is false when he is on bike

languid spire
solid marlin
ruby python
astral falcon
tranquil lintel
languid spire
#

so do as I suggest. You KNOW nothing until you do you are just assuming atm

astral falcon
tranquil lintel
languid spire
tranquil lintel
languid spire
ruby python
astral falcon
tranquil lintel
astral falcon
compact light
#

I am having an issue where editor attributes such as range and editor button are not appearing or having an effect in the toolbox. Is there any setting or whatnot that I have to change?

        [SerializeField] [Range(0, 100)]
        public float dragCoefficient = 0.1f;
        [SerializeField] [Range(0, 1000)]
        public float maxSpeed = 100.0f;
        [EndGroup]
        
        [EditorButton("ResetMotion", "Reset Motion")]
astral falcon
compact light
compact light
ruby python
astral falcon
compact light
#

no

astral falcon
#

https://docs.unity3d.com/Manual/ExecutionOrder.html physics before input. So I guess, its exeucting the update of the physics script first. Why not just make the interaction check for itself and switch the boolean instead of you mixing up update input and physics raycast at the same time?

ruby python
astral falcon
astral falcon
compact light
astral falcon
#

And what does your current script look like?

compact light
#
[SerializeField] 
        [Range(0, 100)] 
        public float ThrustForce = 10.0f;
        [SerializeField] 
        [Range(0, 100)] 
        public float ManeuverForce = 10.0f;
        
        [SerializeField] 
        [Range(0, 100)]
        public float DragCoefficient = 0.1f;
        [SerializeField] 
        [Range(0, 1000)]
        public float MaxSpeed = 100.0f;
languid spire
astral falcon
#

this is working perfectly fine on my side. even if public values are serialized anyways

compact light
alpine yarrow
#

hi im new to coding

astral falcon
#

Also, just remove [SerializeField] for now for the public values

compact light
#

restarted the editor one moment

#

do I need serializable on the class?

astral falcon
#

what is the class type

compact light
#

class PlayerController : MonoBehaviour

astral falcon
#

Did you remove the serializefield and leave only range?

compact light
#

yes

astral falcon
#

What does Range show you as tooltip when hovering it?

compact light
astral falcon
#

Can you show the top of your class? PlayerController : Monobehaviour etc.? You sure there is no custom editorlayout lying around somewhere?

#

And did you restart your visual studio/vs code?

alpine yarrow
#

what coding app do you guys sugest?

astral falcon
compact light
#
using UnityEngine;
using UnityEngine.InputSystem;

namespace SpaceAsh.Player
{
    public class PlayerController : MonoBehaviour
    {
        # region Inspector Variables

        //[BeginGroup("Game Objects")] 
        public InputActionAsset playerControls;
        public Camera playerCamera;
        public GameObject ship;
        public Rigidbody2D shipRigidbody;

        //[EndGroup] [BeginGroup("Movement Variables")] 
        [Range(0, 100)] 
        public float thrustForce = 10.0f;
        [Range(0, 100)] 
        public float maneuverForce = 10.0f;
        
        [Range(0, 100)]
        public float dragCoefficient = 0.1f;
        [Range(0, 1000)]
        public float maxSpeed = 100.0f;
        //[EndGroup]
        
        //[EditorButton("ResetMotion", "Reset Motion")]
        

        # endregion

        /.../
    }
}
astral falcon
alpine yarrow
compact light
#

thats a whitespace

alpine yarrow
#

yuh

#

on ur left

#

same thing

compact light
#

regions allow you to block off code

astral falcon
#

Please keep personal chats out of this 😄

alpine yarrow
#

alr

#

thats my friend

astral falcon
alpine yarrow
compact light
#

its a whitespace lol

#

rider has a weird default code style

astral falcon
compact light
#

commented it out nothing changed

astral falcon
alpine yarrow
astral falcon
compact light
#

yes

compact light
#

lmfao

#

this happens every time I touch this damn editor

astral falcon
#

Somethings def. broken on your side. no errors or warnings in unity?

compact light
#

there is no setting or anything that may change the behavior of the editor?

languid spire
#

no

compact light
#

thats all

astral falcon
#

Are you in debug mode or something?

compact light
#

nope

solid marlin
astral falcon
compact light
#

this a good version to be using?

astral falcon
#

Did you check this box by any chance? ProjectSettings => Editor

compact light
#

def inspec?

astral falcon
#

Yep, it should be unchecked, at least its on my editor

compact light
astral falcon
#

Hm, out of ideas then

compact light
#

back to godot I go ig 😭

astral falcon
#

Just try another editor version and see if things change

compact light
#

I def have a corrupted install

compact light
astral falcon
#

Last one I used was .41f1

#

There is .48 out, maybe update

compact light
#

im going down to 2021 lts

compact light
astral falcon
#

Ah okay, because it says 47 on your screenshot

compact light
#

edited.

languid niche
#

can someone help i am getting a null ref error at enemy script line 26 when checking for isEnemyArea, which is in player script

cosmic dagger
languid spire
cosmic dagger
#

you need to assign a value to playerScript . . .

languid niche
#

playerscript = getcomponent<Playe>()
i di this too but it was same

#

sorry for typo error but this is assigning right ?

languid spire
#

is Player on the same Game Object?

cosmic dagger
#

well, does the GameObject this script is attached to have a Player component?

languid niche
#

I did a serializedfield and assigned the player object to it

#

no player and enemy are different game objects with different scripts

languid spire
#

so GetComponent on it's own can never work

languid niche
#

actually i want to access the bool variable from the player script in enemy script, can u let me know a better way

languid spire
#

you have the GameObject player in your script so

playerScript = player.GetComponent<Player>();

would have worked

languid niche
#

yeah that was i thinking why is it returning null when i am adding the component

languid spire
#

because the component cannot be found on the CURRENT game object

astral falcon
#

Is there only one player present at all time?

languid niche
#

yup

#

a unity window

astral falcon
#

Then you could use the singleton pattern to always have access to your player

languid niche
#

the private set and public get thing, i mean instance

astral falcon
#

Yep, that instance thing

languid niche
#

Ok I will try Thanks :), i will try get a solution around it

queen adder
gritty cloak
#

Hi, is there any reason a Debug.Log is being called non stop when the function I call should work only when I click certain button in my app? For instance, I click once a button that calls ChangePhase function and now the debug says "Current Phase is Create List" without non stop, I have checked the script and the Inspector but there are no other ways this should be called so many times. Last week I did not had any problem, is just today that I opened the project and it went crazypikachuface

languid spire
gritty cloak
#

how do i check?

languid spire
#

select the message, the stack trace appears below

gritty cloak
languid spire
#

just screenshot the console window

gritty cloak
astral falcon
#

And what code are you triggering? Can you share it

languid spire
gritty cloak
#

public void SetListType(int type)
{
listTypeIndex = type;
for (int i = 0; i < typeListButtons.Length; i++)
typeListButtons[i].interactable = (i != listTypeIndex);
currentListType = (ListType)listTypeIndex;
Debug.Log("Current type of list is " + currentListType);
}

This is called from the buttons on the UI

public void ChangePhase(string text)
{
if (Enum.TryParse(text, out MenuPhase newPhase))
{
if (menuPhase != newPhase)
{
menuPhase = newPhase;
UpdateMenuObjectsWithAnimation();
Debug.Log("Phase changed to: " + menuPhase);
}
else Debug.Log("Phase is already " + newPhase + ". No change needed.");
}
else Debug.LogError("Invalid phase name: " + text);
GeneralInfoText();
Debug.Log("Current phase is: " + menuPhase);
}

This is called from different sources since changing phase happens when I click certains buttons in the app

eternal falconBOT
languid spire
gritty cloak
languid spire
gritty cloak
languid spire
# gritty cloak what should be looking for again?

it is very clear to see which part of your code is in the call stack calling, eventually, the Debug.Log. So you need to look at the messages you think should not be there and see if they are all being called from the same place

languid spire
gritty cloak
#

well everything was solved as magic when I just restarted Unity, now things work without the console calling the same function countless times

worthy veldt
#

i looked into how to save a game, in stardew valley clone game should i go for BinaryFormatter or JSON ?

#

it utilized scriptable object for recipe and player can make their own crafting recipe (cooking game). im not sure how to save SO in json

#

but i read that binary method is unsecure ?, i dont mind if player cheating the save file but i dont want to make it too easy

silk night
#

A scriptable object is just serialized data, you can serialize the data to json and back

eternal needle
#

Json being human readable also means it's easier for you to see when something goes wrong

worthy veldt
#

i only learned the basic so it will be tedious though, storing that information one by one. i watched binary can store custom class.

#

welp, better savfe than sorry. json it is

eternal needle
worthy veldt
#

yes as i mentioned i just learned the basic, perhaps there is more technique down the line

eternal needle
#

Look into Newtonsoft. There is also some plugin that has a bunch of conversions for unity types so you can serialize stuff like vector3

#

There isnt much to it honestly. If you can save an int, you can save your custom class. It's literally the same code.
Also it's a bit easier when you make classes that contain only the information you want to save.

dry geyser
#

anyone know why u cant see my player object in the game tab?

wintry quarry
#

This is also not a coding question

vagrant harness
#

There's a better way of doing this, isn't there?

    public InputActionAsset inputActions;
    public Animator animator;
    InputAction move;
    InputAction look;
    InputAction punch;
    InputAction jump;
    InputAction crouch;
    public bool canMove;

    // Start is called before the first frame update
    void Start()
    {
        move = inputActions.FindAction("Move");
        look = inputActions.FindAction("Look");
        punch = inputActions.FindAction("Punch");
        jump = inputActions.FindAction("Jump");
        crouch = inputActions.FindAction("Crouch");
    }
north kiln
#

Serializing InputActionReferences; using the C# generator of the Input Action Asset; or just doing what you've done, as there's nothing really wrong with it.

vagrant harness
#

Anyone know how to make VS always

{
    
}

instead of doing a normal line break when you press enter in the middle of a {}?

vagrant harness
#

Anyone know why characterController.isGrounded rapidly switches between True and False?

    private void FixedUpdate()
    {
        if (!(characterController.isGrounded))
        {
            velocity += (Vector3.down * Time.fixedDeltaTime);
        }
        else if (velocity.y != 0 || velocity.y < 0)
        {
            velocity.y = 0;
        }
        velocity = velocity * (characterController.isGrounded ? 0.5f - Time.fixedDeltaTime : 1 - Time.fixedDeltaTime);
        Debug.Log($"Velocity: {velocity}, Grounded: {characterController.isGrounded}, movement: {move.ReadValue<Vector2>()}");
        characterController.Move(velocity);
    }
frosty hound
#

Probably because you're resetting the y velocity to zero whenever it is grounded resulting in the capsule cast on the CC to not actually go in any direction to detect the ground that frame.

#

The docs have an example on how to move and jump, use that as a working base.

red helm
#

What API to use for the Database of the Unity Game?

wintry quarry
#

What are you trying to do

red helm
#

Like storing completed levels

wintry quarry
#

Why do you need a database for that

#

Sounds like you're just asking about a saved game system

thorny basalt
silk night
bright arch
#

why does clicking on my object not input anything into the debug log at all, regardless of whether or not i clicked the collider?

slender nymph
#

do you have an event system in the scene with a Physics2DRaycaster on the camera?

bright arch
#

ou sweet, i did have event system but not the raycaster, thank you

wintry quarry
bright arch
#

i needed to just make sure it was actually clicking the object, when i click on it i want other things to happen so it does have a purpose

normal mango
#

ive got a simple script on a bunch of doors that calculate how close or far the player is, and opens the door when they get close, but the variable isnt syncing with the animator. how can i fix this? do i need to declare the animator component?

slender nymph
#

where do you set the parameter on the animator?

languid spire
normal mango
#

so declare the class and getcomponent in awake?

languid spire
#

or declare as a serialized variable and drag the animator component into it

normal mango
#

does the avatar part of the animator component matter?

slender nymph
#

presumably a door does not have an avatar, so no

normal mango
#

still got nothin

slender nymph
#

and are you actually setting the parameter or did you think just referencing the Animator component would magically tell the parameter the value of your completely unrelated variable?

normal mango
#

how can i set that then?

slender nymph
#

did you look at the docs for the animator component?

normal mango
#

not yet

#

from the unity 3d manual?

slender nymph
#

!docs

eternal falconBOT
languid niche
#

I also doing same thing except when i get past the point i make the bool true and if less false, so you can play the animation when close to the point and closing animation when past the point,
there is a codemonkey tutorial also which states this opening and door closing thing that may help 🙂

normal mango
#

i got it working, thanks

frozen plaza
#

hi!

I'm trying to manipulate a mesh. for that I want to look at the triangles of the mesh. I would expect triangles to be int[][], an array of 3 integers each which are the indexes of the vertices of the triangle

the triangles array is int[] for me though.. anyone know why this is?

frozen plaza
silk night
#

triangle is just listing indexes of verticies

frozen plaza
silk night
#

so a drawn triangle would be:

PSEUDO CODE
mesh.vertecies = [(0, 0, 0); (0, 1, 0); (1, 1, 0)]
mesh.triangles = [0; 1; 2]
#

the 0, 1, 2 telling that they reference the first, 2nd and 3rd vertex

frozen plaza
#

ah! so it's always pairs of 3?

silk night
#

yes, three connected vertecies that draw a triangle

frozen plaza
#

ah, now I see it.. ok, that's a bit unfortunate but I understand it

#

thank you!

languid spire
low lagoon
frozen plaza
#

right..

alpine yarrow
#

@astral falcon hi remember me?

silk night
# frozen plaza right..

you can just use a for loop that increments by 3 every step and go with i, i+1 and i+2 to access the vertecies

alpine yarrow
#

I wanna get a good code app but what should I use?

frozen plaza
willow scroll
alpine yarrow
silk night
low lagoon
alpine yarrow
#

Alr but there a are 2

#

Insider and normal

#

Well I think normal

willow scroll
alpine yarrow
astral falcon
#

Just imagine some punctuation in the sentence 😄 "There are 2 (,) visual studio code...."

alpine yarrow
#

Well I think it worked and ima try to. Get a walking script and looking arround

silk night
night valve
#

sorry i had to :c

verbal dome
#

I'd use tuples or vec3int instead of arrays, for storing individual triangles

#

Less garbage

willow scroll
# alpine yarrow

Got it. None of them were advised by me. I mean "Visual Studio", and this is the whole application name, without "Code"

valid turtle
#

where would I seek help for something like the particle system?

alpine yarrow
#

Alr thx

obsidian granite
#

if there's two bodies in a collision, collision.impulse will always point toward one body, even if both objects are receiving the OnCollisionEnter message. is there a way i can have the impulse always face the rigidbody on the object that the script is attached to? right now i'm thinking of using dot product to check if the impulse vector is more than 180 degrees away from the vector pointing from the colliding body toward the attached body, and if it is, i'll just multiply it by -1, but i'm wondering if there's a better way

willow scroll
alpine yarrow
#

I think I did it idk

silk night
#

not 100% sure on this tho

alpine yarrow
#

I got the wrong one

silk night
#

the impulse is not pointing at "any" object, it is pointing where the combined forces add up to

obsidian granite
#

it points

silk night
#

what you are looking for is the impact position + normal i think

valid turtle
obsidian granite
#

impulse is unit force times a change in unit time

#

force is a vector

#

therefore impulse is a vector

silk night
#

A, speed (0, 3, 0) -> Impulse (0, -2, 0) <- B, speed (0, -5, 0)

#

iirc

obsidian granite
#

impulse is the change in force needed to resolve a collision, my issue is that the impulse i'm getting from a collision points in the wrong direction. i.e, if a car hits another car, one of the car's impulses will be pointing in the correct direction, but the other one's impulse will be pointing in the wrong direction

junior saddle
#

why do they let me do this

willow scroll
#

You can also have as many spaces before putting one, for instance

low lagoon
# alpine yarrow Alr thx

use "Visual Studio" which comes with Unity. "Visual Studio Code" can be a pain to set up if you aren't already experienced dev

willow scroll
low lagoon
# junior saddle

you could probably ban that in your lint if you really don't like that it can be done

low lagoon
#

I guess that last part is the reason it was a pain for me lol...

junior saddle
#

I feel like this is wonderful

#

random semicolons everyone

willow scroll
#

If you want to decrease your readability, sure

alpine yarrow
#

Sashok so if I wanna code for unity I use c#

low lagoon
#

that is correct

alpine yarrow
#

Alright thank you all so much for helping

#

Another question (sorry for all the question I'm new to this)

#

I wanna make a 3d game what should I do for a walking? Mouse looking script

silk night
#

You should !learn through tutorials

eternal falconBOT
#

:teacher: Unity Learn ↗

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

astral falcon
alpine yarrow
#

Wdym?

astral falcon
#

You decide what game you are going to do. There is no best practice for a "3d game". Walking could be anything depending on platform, movement mechanics and what not. But as sidia suggested, first go through the tutorials

alpine yarrow
#

Is that in this server?

low lagoon
alpine yarrow
#

Alight well wish me luck ima start

frozen plaza
#

so.. if I want to sub my mesh into 2 submeshes, I do

        this.mesh.subMeshCount = 2;

        this.mesh.SetTriangles(someTriangles, 0);
        this.mesh.SetTriangles(someOtherTriangles, 1);

        MeshRenderer renderer = this.GetComponent<MeshRenderer>();
        renderer.materials = new Material[] { someMaterial, someOtherMaterial };

and then I have 2 submeshes with a different material, no?

#

well i did try and it does not work lol so that's why I'm asking

willow scroll
silk night
frozen plaza