#💻┃code-beginner

1 messages · Page 124 of 1

novel shoal
#

so i have to make it true when i declare it?

paper plaza
#

[SerializeField] private GameObject interactable;
[SerializeField] private GameObject hittable;

Do i do like this? Or is this bad

languid spire
#

no, just make it true at the start of Start

paper plaza
#

and like i try to get the component

timber tide
#
[SerializeField] Item item; //works
[SerializeField] IInteractable item; //does not```
polar acorn
#

Yes. After the coroutine has ended

paper plaza
timber tide
novel shoal
paper plaza
#

so i can attach a zombie or an item

#

is it good?

paper rover
#

I'm pretty new to coroutines, I'm trying to fade out all wall pieces at once but this does it slowly one at a time. Is there a way to make it so it fades them all out at the same time?

#

Maybe the yield is in the wrong place?

wintry quarry
tough lagoon
tough lagoon
wintry quarry
timber tide
paper plaza
tough lagoon
# paper plaza how should i name it?

Inheritance is good, and you can give them sub references to specific data stacks. Serializing all of that is AOK.

But your base class should make sense to someone without drilling into deeper context.

So InteractableBase and using that for doors, switches, chests etc makes sense. NPCBase would likewise do the same for NPCs. They could also derive one later deeper if you wanted common overlap.

The problem with Things is it isn't clear what it is or is to be used for. Is it used for UI? That's a thing. Input? That's a thing too. Is it the top or bottom of an inheritance stack? Anything that leads you to automatically answering those questions is good in practice.

That said, using inheritance and serializing it is perfect good in this case (imho).

paper plaza
#

ooh okay, now i understand, thank you

lavish terrace
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayerEquipment : MonoBehaviour
{
    public PlayerScript PlayerScript;
    public Animator HelmetAnimator;
    public List<SpriteRenderer> EquipmentSprites = new List<SpriteRenderer>();
    public List<RewardScriptableObjects> Equipment = new List<RewardScriptableObjects>();
    public SerializableDictionary<Stat, float> Stats = new SerializableDictionary<Stat, float>();

    public void Start()
    {
        SetStats();
    }

    [ContextMenu("Generate Stat")]
    private void GenerateStat()
    {
        Stats.Add(Stat.Damage, 0);
        Stats.Add(Stat.Health, 0);
        Stats.Add(Stat.Speed, 0);
    }
    public enum Stat
    {
        Damage, Health, Speed,
    }

    public void SetStats()
    {
        SetStat(PlayerScript.Damage, 0);
        SetStat(PlayerScript.HealthBar.MaxHealth,1);
    }

    void SetStat(float Stat, float StatNum)
    {
        Stat = Stats[0];
        int EquipmentNum = 0;
        foreach (RewardScriptableObjects EquipmentPiece in Equipment)
        {
            if (Equipment[EquipmentNum] != null)
            {
                Stat += Equipment[EquipmentNum].Stats[1];
                EquipmentNum += 1;
            }
            else
            {
                EquipmentNum += 1;
            }
        }
    }
}
#

Stat += Equipment[EquipmentNum].Stats[1];

.Stats accepts 0 but doesnt accept 1 for some reason

timber tide
#

Are you ever calling GenerateStat

gaunt ice
#

btw you should rename your variable

public PlayerScript PlayerScript;
terse raven
#

Hi peeps, I want to get a position of my player in my enemy script so it can taregt the player. whats the best method to get the players position?

gaunt ice
#

it can make your script failed to compile if you are trying to access static variable in future eg singleton

paper plaza
# tough lagoon Inheritance is good, and you can give them sub references to specific data stack...
[SerializeField] private GameObject interactable;
    [SerializeField] private GameObject hittable;
    private void Player_OnSelectedInteractableChanged(object sender, ThirdPersonMovement.OnSelectedInteractableHittableChangedEventArgs e)
    {
        if (!interactable.TryGetComponent<IInteractable>(out IInteractable interact)) return;
        if (e.selectedInteractable == interact)
        {
            ShowInteractable();
        }
        else
        {
            HideInteractable();
        }
    }

    private void Player_OnSelectedHittableChanged(object sender, ThirdPersonMovement.OnSelectedInteractableHittableChangedEventArgs e)
    {
        if (!interactable.TryGetComponent<IHittable>(out IHittable hit)) return;
        if (e.selectedHittable == hit)
        {
            ShowHittable();
        }
        else
        {
            HideHittable();
        }
    }

I did something like this

#

because i want the deadbody of the enemy to make show up a canvas when the interact ray cast is touching an Interactable.

lavish terrace
#

and btw is that from tranformice ?

paper rover
timber tide
lavish terrace
timber tide
#

no wait you're accessing a dictionary by the keyvalue of a integer

#

ok wait you're accessing it wrong

#

Your keys are references it seems actually looks like a enum

lavish terrace
#

come again ?

#

i need to make it into an int so i can do a loop of some kind

timber tide
#

What type is Stat

lavish terrace
#

public enum Stat
{
Damage, Health, Speed,
}

#

public SerializableDictionary<Stat, float> Stats = new SerializableDictionary<Stat, float>();

timber tide
#

ok right why I'm confused

#

enums are technically integers, but you want to be accessing by the enum type

gaunt ice
#

the key is enum not integer, safety checking will block you
btw why you dont use an array to store the data?

lavish terrace
#

ohhhhhhhhhhhhhhhhh

timber tide
#

I forget if you can directly access the kvp by index, but you need to foreach it

#

assuming you want to do it how you're doing it

lavish terrace
#

hold up

#

im securing the solution

gaunt ice
#
public float[] values
float x=values[(int)SomeEnum];
timber tide
#

ok right, you can iterate over a c# dictionary but through foreach iteration

#

same with hashset surprisingly

gaunt ice
#
void SetStat(float Stat, float StatNum){
    Stat = Stats[0];
    int EquipmentNum = 0;
    foreach (RewardScriptableObjects EquipmentPiece in Equipment){
        if (Equipment[EquipmentNum] != null){
            Stat += Equipment[EquipmentNum].Stats[1];
            EquipmentNum += 1;
        }
        else{
            EquipmentNum += 1;
        }
    }
}
```i wonder what it is trying to do, have you clipped the code?
lavish terrace
#

ok hear me out

#

i got a list which has a scriptableobject

#

each scriptableobject has a dictionary of stats

#

enum, float

#

i need to add the stat.damage ( lets say 10 damage ) to the player base Damage

#

player also has a dictionary of the same type

languid spire
#

you miss the point your foreach gives you EquipmentPiece but then you go and use Equipment[EquipmentNum] for exatly the same thinhg

queen adder
#

send a code (with how you think it would look like) than explaining what you want to happen

gaunt ice
#

just to remain you that

public void Set(float a){
  a=10;
}

float b=0;
Set(b);
Debug.Log(b);//b is still 0
timber tide
#

First fix up the params such that

void SetStat(Stat stat, float statNum)

If you're going to continue using enum with dictionary

lavish terrace
#
public void SetStats()
    {
        // Setting Stats for the player
        SetStat(PlayerScript.Damage, Stat.Damage, RewardScriptableObjects.Stat.Damage); 
        SetStat(PlayerScript.HealthBar.MaxHealth, Stat.Health, RewardScriptableObjects.Stat.Health);
        SetStat(PlayerScript.moveSpeed, Stat.Speed, RewardScriptableObjects.Stat.Speed);
    }

    void SetStat(float Stat, Stat PlayerStat, RewardScriptableObjects.Stat StatType)
    {
        Stat = Stats[PlayerStat]; // first set basic stat
        int EquipmentNum = 0;       // for the loop
        foreach (RewardScriptableObjects EquipmentPiece in Equipment)
        {
            if (Equipment[EquipmentNum] != null) // check if item is equipped 
            {
                // equipped = give item stat to player stat (adding up)
                Stat += Equipment[EquipmentNum].Stats[StatType];
                EquipmentNum += 1;
            }
            else
            {
                EquipmentNum += 1;
            }
        }
    }
gaunt ice
#

you can debug.log to see if the player damage got changed
again please rename your variables....

lavish terrace
#

ok gimme a sec

short hazel
#

Stat = Stats[PlayerStat] - this overwrites the value of your float Stat parameter (those should be in camelCase, not PascalCase), so the parameter itself is not needed

timber tide
#

it's also a value type which you aren't returning so there's no actual usage of it in this code

short hazel
#

Yeah I think they're mistakingly thinking that value types are passed by reference

lavish terrace
#

my brain is lost

#

too much information

#

the stat is updated

timber tide
lavish terrace
#

however the playerstat isnt

timber tide
#

figure it out from that

lavish terrace
#

good point

#

sorry guys im new

timber tide
#

all good

lavish terrace
#

appreciate all the help

graceful citrus
#

how would i go about implementing a compass to point in the direction of a gameobject? i thought it sounded simple but im realising i don't know what the most effective way to do it would be

queen adder
#

can someone help me with my code i am getting this error: NullReferenceException: Object reference not set to an instance of an object
but i cant find anything wrong
here is the part that the error says its in:
private void Attack()
{
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);

foreach (Collider2D enemy in hitEnemies)
{
    enemy.GetComponent<Enemy>().TakeDamage(attackDamage);
}

}

gilded pumice
#

https://paste.ofcode.org/36mad2FcwkuU72qvdLtHxnN Hey all, I'm trying to make a timer that counts down (like an ability cd) that displays on the screen. My plan was to put the code in the game manager script, access it in my player controller script, assign it to an IEnumerator and call it when a Input key is used. It's the final method in this shared code that is giving me the issue. It wants me to pass a argument to the method and I don't want to because I can't do anything with it. If I swap out the variable "timeLeft" for the new argument, it doesn't work because I can't call that argument outside the method to display it on the screen (line 20 wouldn't be able to access it), I've tried thinking about rearranging the logic to be able to use an argument and I come up with nothing. I assume I'm going about the entire process wrong. Been sitting here for almost 2 hours and google hasn't helped, everything is adjacent to what I'm trying to do.

So I tried public void AbilityCooldown(float nothing)
{
if(timeLeft > nothing)
{
timeLeft -= Time.deltaTime;
phaseText.text = "Phase Cooldown " + timeLeft;
}
}

}

and set the argument to 0, it starts the countdown for a few milliseconds and then stops the countdown

sage mirage
#

Hey, guys! I want someone to explain me what's the difference between dynamic bool and static parameters?

#

On my inspector, I see dynamic bool and static parameters when I want to use a specific method from a class.

#

That's what I mean

graceful citrus
#

lol

short hazel
# sage mirage On my inspector, I see dynamic bool and static parameters when I want to use a s...

Take for example an Input Field. That has an On Value Changed event you can bind directly from the Inspector.
If you select from the Dynamic section, then you can use methods that accept a single string parameter. When the event is raised by the Input Field itself, the new value is passed to that method parameter and you can use it.
If you don't select Dynamic, then a field appears where you can provide a constant value to pass to the method, from the Inspector directly

west sonnet
#

I'm making a 2D shooter and I'm trying to get the triangle to follow my mouse, but it's following it from it's side? Can anyone help please. I want to the tip of the triangle to point towards my mouse

#

This is my code

river roost
#

On the needle. Although you have to remove the y

short hazel
#

Hah, same solution twice

west sonnet
rich adder
short hazel
#

You probably just need transform.right = dir where dir is the direction from the player to the mouse (world coords)

rich adder
west sonnet
rich adder
#

make a proper empty gameobject and parent needle graphics as child. Rotate empty parent

west sonnet
#

I still have the same issue though, the needle isn't facing my mouse 😦

rich adder
west sonnet
#

And I got what you mean now. I should add my script to the Empty, not the needle

rich adder
#

after is fixed yeah you can just do transform.right = dir

west sonnet
prisma silo
#

How do I choose a random game object from the scene with the same tag

#

For example selecting a random enemy from the scene

rich adder
#

put them in array and pick random index

west sonnet
short hazel
#

No, it replaces a good part of it

#

All the trigonometry you have here (Atan2) is from a very popular tutorial and is far from the easiest and simplest solution

#

So, taking your last screenshot, it will replace lines 17 and 18

west sonnet
#

right?

short hazel
#

I'd also avoid using "magic numbers" like 5.23f because as soon as you move the camera on Z, it'll break

short hazel
#

(mousePos - objectPos).normalized if you want to do it cleanly. Normalizing makes sure the length of the vector is equal to 1

#

Making it a direction vector

gilded pumice
#

Can anyone help me tweak this correctly? When I call this method I'm expecting to see timeLeft decrement by 1 per second until it hits 0 (value I've passed to the nothing argument) but instead it just instantly jumps to a near zero decimal number instantly when called.

public void AbilityCooldown(float nothing)
{
while(timeLeft > nothing)
{
timeLeft -= Time.deltaTime;
phaseText.text = "Phase Cooldown " + timeLeft;
}
}

west sonnet
short hazel
#

I wrote the code, literally

west sonnet
short hazel
#

You have to put the result into a variable, and use that

west sonnet
#

Okay

short hazel
gilded pumice
#

I did, sorry let me paste both code using paste of code link

west sonnet
#

This my code now

short hazel
#

You don't need lines 14-15

#

This screws with the direction calculation

#

Basically it was the "long form" of creating a direction vector

west sonnet
#

Okay, I've removed lines 14-15, but I still get this weird movement when the mouse is on the left side of the player

gilded pumice
short hazel
west sonnet
#

Could you give me some guidance on how to do that please?

short hazel
#

No your code is correct

west sonnet
short hazel
#

As long as both objects are in the same space, the direction will be correct. I've done both in the past (all world, all screen, even all viewport) and they worked correctly

short hazel
#

Are you sure there's no collider, even on the child objects?

west sonnet
#

The gun is parented to an empty which is parented to the player. Only the player has a collider

#

Also, should my Z rotation value be changing when rotating the gun?

short hazel
#

Only Z should be rotating

slender sinew
#

shouldn't you set the mousePos.z to 0? not 5?

#

if the direction calculated is Vector3, it will affect the cast to Vector2 after (if the direction is not actually in 2D space)

west sonnet
short hazel
#

If other axes change, then you've screwed up with the magic numbers and they're the ones making the calculation fail

west sonnet
#

Even with " mousePos.z = 0f " , the issue happens

short hazel
#

Basically line 11 should be removed, and to be extremely safe dir.z should be set to 0 prior to feeding it to transform.right, so the vector is "flat on the screen"

west sonnet
#

Yesssss, it's working now!

#

Thank you so much everyone 🙂

#

Wait, spoke to soon

#

When I turn, the needle turns and the direction becomes inverted

#

So the back of the needle is facing my mouse instead of the front

short hazel
#

How are you flipping the player when you need it to face left?

#

Setting the scale to -1 will cause that issue, because every child will also be flipped

west sonnet
#

ahh yeah, I'm setting the LocalScale to -1

rich adder
#

you should rotate 180

#

instead. of scale

short hazel
#

Or just flip the sprite

#

renderer.flipX = true / false

rich adder
#

yeah i prefer avoiding that, since it would be the player transform.right incorrect after

short hazel
#

No it would be correct because nothing on the object has changed

#

Except for some display setting

west sonnet
#

Why isn't it letting me do this? I'm trying to rotate it 180

rich adder
short hazel
#

Yeah they want to aim the gun to the mouse independently of the player rotation

rich adder
#

you would need to do transform.localRotation = quaternion.euler

ruby barn
#

Hey, what would be the best way to check if a new spawned room spawned in another room?
my room structure looks like this:
BiggerRoom
-> Floor
-> Floor 1
-> ...
-> Walls
-> ...

west sonnet
#

I'm confused as to what I do now

rich adder
west sonnet
# rich adder wdym

Oh wait, my bad. I was changing the Quaternion.Euler results and it was flipping the entire world

#

Thank you for the help it's working now! 🙂

ruby barn
gilded pumice
rich adder
ruby barn
summer stump
ruby barn
#

only basic so far, no real complex shapes. currently thinking about just doing box colliders on the prefabs but i dont know if thats good on long term

#

goal is to build a modular procedual dungeon generation. Done it with grids, now i want to try this out but i need a way to detect if they collide or spawn on the same spot

queen adder
#

Any ideas why this is consistently returning false?

#

I've checked and the position is accurate and the layers are correct

timber tide
#

Try debugging the minimal amount of parameters

#

then work your way up

queen adder
#

I've tried and I'm out of ideas

#

I will try drawing a gizmo on it to verify 100% its not the position

#

Position is perfect

timber tide
#

Strange, I've actually not tried CheckSphere, but perhaps trying SphereCast OverlapSphere* instead

#

otherwise I could only guess it's a collider issue if you're not defining a layer mask

queen adder
#

Oh I fixed it, it was the way I added it to the editor GUI wasn't proprely translating the layer numbers

#

I just put it on a different script and grabbed a reference. Works fine

sage mirage
#

Hey, guys! How to set my current resolution to my default pc resolution on my game in Start()?

#

I am making now resolution settings and when I am entering the game I don't see my current resolution there and I see another resolution I have in my dropdown list.

#

I did something like that!

#
{
    // Every variable or initialization that has to happen when the game starts in here!
    Screen.SetResolution(currentResolution.width, currentResolution.height, Screen.fullScreen);
    resolutions = Screen.resolutions;
    filteredResolutions = new List<Resolution>();

    resolutionDropdown.ClearOptions();
    currentRefreshRate = Screen.currentResolution.refreshRate;

    for (int i = 0; i <resolutions.Length; i++)
    {
        if (resolutions[i].refreshRate == currentRefreshRate)
        {
            filteredResolutions.Add(resolutions[i]);
        }
    }

    List<string> options = new List<string>();

    for (int i = 0; i < filteredResolutions.Count; i++)
    {
        string resolutionOption = filteredResolutions[i].width + "x" + filteredResolutions[i].height + " " + filteredResolutions[i].refreshRate + "Hz";
        options.Add(resolutionOption);

        if (filteredResolutions[i].width == Screen.width & filteredResolutions[i].height == Screen.height)
        {
            currentResolutionIndex = i;
        }
    }

    resolutionDropdown.AddOptions(options);
    resolutionDropdown.value = currentResolutionIndex;
    resolutionDropdown.RefreshShownValue();
#

I have also an error here

#

UnityException: get_currentResolution is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'SettingsManager'

rich adder
#

you have to call it from inside a function

sage mirage
#

Yeah!

#

@rich adder What can you say about my issue with resolution?

#

I have to set my current resolution when entering the game so in start() I have to do something.

What I did was that check it out:

#

Screen.SetResolution(currentResolution.width, currentResolution.height, Screen.fullScreen);

#

That's what I did in start method like you see in the code above

sage mirage
#

I fixed it right now anyway I just had to set my screen current resolution in start method like I did in code and that's all for one reason I had that error because I declare that Resolution currentResolution = Screen.currentResolution before Start method.

rich adder
green island
#
Vector3 pos = new Vector3(370,-25-(history.Count * 50),0);
Debug.Log(pos);
GameObject prf = Instantiate(messagePrf, Vector3.zero, Quaternion.identity, contentTransform.transform);
prf.GetComponent<TextMeshProUGUI>().text = message;
prf.transform.localPosition = pos;
contentTransform.sizeDelta = new Vector2(contentTransform.sizeDelta.x, contentTransform.sizeDelta.y + 50);

prf.GetComponent<TextMeshProUGUI>().color = color ?? Color.black;

history.Add(content);``` this is the code for an chat but the messages arent on the right coordinates first one is right on -25 but the second is on -125 but in the console it prints the right coordinates
rare basin
#

you need to use anchoredPosition

#

for rect transforms

short hazel
#

Or a Vertical Layout Group so it does the placement for you

green island
valid magnet
#

Hi all, I've been following the Cloning WoW series on youtube (from 4 years ago so I can't get support there unfortunately) - and I'm at the stage where I'm trying to control character movement but I'm having some issues - is there somewhere I can get help on this? also willing to pay for the solution

short hazel
#

You can ask here as long as it's about code, provide enough info, and follow the recommendations in #854851968446365696

#

Paid work might fall into the collab section and must be posted on the Forums instead

#

!collab

eternal falconBOT
sour fulcrum
#

If I have

Level : SciptableObject

and

ExtendedLevel : Level

Is there a easy way to (cast a level / create a new extendedlevel using a level) into an extendedlevel in a way where i don't have to manually re-assign all it's values?

timber tide
#

you don't need to reassign values when you extend

valid magnet
#

I have set up the camera controller so that when i hold left click it 'free looks' around the character - this is working at the correct speeds, but I also have it that when i hold right click it controls the character rotation with the camera - but the PAN (y) for this is moving at a very slow speed (the tilt x is corrcet speed)

robust condor
#

Is this bad?

private void OnTriggerStay(Collider other)
{
    if (other.CompareTag("Player") || other.CompareTag("NPC")) {
        if (other.TryGetComponent<Traits>(out Traits traits)) {
            RuntimeAttributeData energy = traits.RuntimeAttributes.Get(CharacterAttributes.energy);
            if (energy.Value <= energy.MaxValue) energy.Value += 0.1f;
        }
    }
}
#

Do I need to cache TryGetComponent?

timber tide
#

Do you specifically needs the tags

robust condor
#

Probably not if I only check for component

timber tide
#

right, the components themselves can serve to identify group types and behaviors

#

usually more of a job for interfaces

valid magnet
#

Please let me know what else I should add above to get an answer to my problem ^

robust condor
#

Is there a more performant way than TryGetComponent then?

timber tide
#

That's fine, just make sure the collider object itself limited with components for identity purposes

#

because basically you do a linear search (I think it's through reflection) through all components on the gameobject

wild cargo
bright zodiac
wild cargo
#

This is assuming the operation is frequent and you have profiled it and found a bottleneck in performance

robust condor
#

I did use OnTriggerEnter initially and npc.StartSleep() and when it was 100 I made it move out of the collider

timber tide
#

the problem with tag checking is if you have more than a handful of tags

#

but for what you have there it is probably the quickiest solution if we care about micro performance

robust condor
#

Does the component order in the inspector matter?

#

Will it hit the transform first?

bright zodiac
#

it checks for the collider bounds not the transform

robust condor
#

TryGetComponent ?

bright zodiac
#

huh?

robust condor
#

He said it's a linear search

#

So if I have 1000 components that would take longer I presume

bright zodiac
#

if you've 1000 of them, cache it when you spawned them for the 1st time

timber tide
#

im not sure if the ordering on the inspector matters, but it'll search through all components until a component is found

#

something to test but I wouldnt bet on it

eternal needle
#

The order of that could change if unity wants to change it, so best not to rely on it ever

bright zodiac
#

the order is guaranteed for GetComponents with what you see in inspector

#

the unordered one is the GetComponentsInChildren

timber tide
#

if they made the tag system a bitwise enum much like layer masks I'd probably use it

bright zodiac
#

why?

timber tide
#

1 operation to check against

bright zodiac
#

tags internally cached, it's super fast

#

thus they really want us to use it

timber tide
#

yeah but if you're searching if(playertag), if(enemytag)

warm condor
#

Hey, so I got this problem where I have tryed to use a function called AddForce from the rigidbody2d class to add a force when the player suddently changes direction. However, it is not working at all, as if it isin't even there. I have used debug.log to check if maybe the if statment that it is in is not working properly, however, the logic works perfectly fine. I have no idea how to fix this and I need help. Here is the part of the code where I am having an issue with:

{
    if(Input.GetKeyUp(KeyCode.A) == true && Input.GetKey(KeyCode.D) == true && rb.velocityX > walkingSpeed)
    {
        rb.velocity = new Vector2(0, rb.velocity.y);
        rb.AddForce(new Vector2(rightDirection * forceForSuddentChangeOfDirection, rb.velocity.y));
    }
    else if (Input.GetKeyUp(KeyCode.D) == true && Input.GetKey(KeyCode.A) == true && -rb.velocityX > walkingSpeed)
    {
        rb.velocity = new Vector2(0, rb.velocity.y);
        rb.AddForce(new Vector2(leftDirection * forceForSuddentChangeOfDirection, rb.velocity.y));
    }
}```
wild cargo
#

So you're saying it never executes the stuff inside the if loops or?

warm condor
#

no the if statment works fine, it is these two lines of code that is not doing what the're supposed to do

rb.velocity = new Vector2(0, rb.velocity.y);
rb.AddForce(new Vector2(rightDirection * forceForSuddentChangeOfDirection, rb.velocity.y));```
#

and this

        rb.velocity = new Vector2(0, rb.velocity.y);
        rb.AddForce(new Vector2(leftDirection * forceForSuddentChangeOfDirection, rb.velocity.y));
wild cargo
#

Copy that fast before it'll get deleted for being too long !code

eternal falconBOT
warm condor
lusty flax
#

I want to Instantiate an object from a prefab that is in my Assets folder. How do I reference this object without connecting it to the script via a public GameObject variable?

modern plank
#

https://paste.ofcode.org/rttykLcch2sYqT62ALEGN2

Hello everyone this code fora dialogue script im using and i wanna ask 2 questions:
1-How do i make that audio starts playing when the dialogue starts and stops playing when all dialogue is done
2- how do i make it that the next line starts immediatly after the first one is done instead of having to press "N" in this example

wild cargo
formal hawk
#
    {        
        
        Vector3 directionToTarget = targetPoint.position - transform.position;
        
        float distanceToTarget = Vector3.Distance(targetPoint.position, transform.position);

        if (distanceToTarget < maxDistance)
        {
            float forceFactor = forceStrength / rb.mass;

            rb.velocity = directionToTarget * forceFactor;
        }
        else
            StopDrag();
    }```

I would like to use AddForce instead of directly changing the velocity, but I don't know how to do it while still having a similiar snappy movement.
Any recommendations?
robust condor
#

I have a component that I need to have default values when I create the object. Do I need to prefab the entire object with the component to save them? What if I have two components with different values and want to decide what to attach to the object? I need to instantiate a prefab as a child?

rain brook
#

Just use a equal sign.

robust condor
#

I want to tune the values in the editor

rain brook
true pasture
#

dictionaries are mutable but this value is read only for some reason?

#

im new to dictionaries so i probably am missing something silly

bold swallow
#

How can I perform an action the moment the screen gets touched and only then. I have been trying for 2 hours straight at this point to make it work and I cant. Originally I used the old input system and I had this:

    Touch touch = Input.GetTouch(0);
            if(touch.phase == TouchPhase.Began)
            {
                planetToFall = Instantiate(currentPlanet, Spawner.transform);
            }

and then I changed to the new one and wrote this, and Unity keeps crashing everytime I touch the screen

    UnityEngine.InputSystem.TouchPhase phase = touchPressAction.ReadValue<UnityEngine.InputSystem.TouchPhase>();
        if(phase == UnityEngine.InputSystem.TouchPhase.Began)
        {
            planetToFall = Instantiate(currentPlanet, Spawner.transform);
        }

the problem in both cases is that Instantate() runs everyframe instead of one which is not what i want

rain brook
timber tide
lusty flax
#

I'm trying to make an inventory hotbar where the player presses one of the number keys to equip a certain item that they own. When I press the button, however, some of my models are off-center. Is there any easy way to fix this without having to fix some aspects of the model in blender?
I instantiate my models like this:
Instantiate(item.model, itemSpawn);

slender nymph
wild cargo
robust condor
#

Is there a way to map strings to scriptableobjects in the inspector? Since you can't use a dictionary

wild cargo
wild cargo
timber tide
#

make structs

robust condor
#

@wild cargoI have scriptable objects in the project and need to create components from them: Traits.SetTraitsWithClass(npc, <scriptableobject>);

rich adder
#

!code

strong path
#

there are already semicolons

eternal falconBOT
strong path
#

my apologies

true pasture
strong path
#

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

public class Controller : MonoBehaviour
{
    public float speed = 5f;
    public float mouseSensitivity = 2f;
    public float jumpForce = 5f;

    private Camera playerCamera;
    private CharacterController characterController;
    private float verticalRotation = 0f;
    private float verticalVelocity = 0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;

        playerCamera = GetComponentInChildren<Camera>();
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        // Player movement
        float horizontalMovement = Input.GetAxis("Horizontal");
        float verticalMovement = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(horizontalMovement, 0f, verticalMovement);
        movement = transform.TransformDirection(movement);
        movement = speed;

        // Jumping
        if (characterController.isGrounded)
        {
            verticalVelocity = -0.5f;

            if (Input.GetButtonDown("Jump"))
            {
                verticalVelocity = jumpForce;
            }
        }

        // Gravity
        verticalVelocity += Physics.gravity.y Time.deltaTime;
        movement.y = verticalVelocity;

        // Mouse look
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
        float mouseY = -Input.GetAxis("Mouse Y") * mouseSensitivity;

        verticalRotation += mouseY;
        verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);

        playerCamera.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
        transform.rotation = Quaternion.Euler(0f, mouseX, 0f);

        // Apply movement
        characterController.Move(movement Time.deltaTime);
    }
}

there are already semicolons, but the error is there

wild cargo
north kiln
eternal falconBOT
ruby barn
#

is there a way to automatically size a boxcollider around my gameobject ?

wild cargo
# robust condor <@579652339603079219>I have scriptable objects in the project and need to create...

You can lazily map them using a property, so like

[Serializable]
public struct MyMappingStruct
{
  public string myString;
  public MySO mySO;
}

private Dictionary<string, MySO> _soMappings;

[SerializeField] MyMappingStruct[] _mappings;

private Dictionary<string, MySO> SOMappings {
  get 
  {
    _soMappings ??= _mappings.ToDictionary(m => m.myString, m => m.mySO); // ??= is essentially just "if (someValue != null) then assign it to this value"
    return _soMappings
  }
}

This should give you an idea of the implementation

robust condor
#

@wild cargoStruct doesnt show up in the inspector

wild cargo
lusty flax
robust condor
#

[System.Serializable]
public struct CharacterClasses {
public ScriptableObject peasant;
public ScriptableObject knight;
}

wild cargo
wild cargo
true pasture
#

I dont udnerstand this error. I made a copy of the list before iterating on it. I still keep getting this error though. Not sure how thats possible.

robust condor
#

Okay got it

wild cargo
polar acorn
true pasture
#

oh, how would I fix the error then?

wild cargo
#

I would attempt to use LINQ's myCommands.ToDictionary() to do a soft copy first

wild cargo
#

Like what are the close children/parents of that object?

polar acorn
lusty flax
#

Here's the full situation:
This is my code:

void equip(ItemData item)
{
    if (inventory.Contains(item))
    {
        int childCount = itemSpawn.childCount;
        if (childCount > 0)
        {
            for (int i = 0; i < childCount; i++)
            {
                Destroy(itemSpawn.GetChild(i).gameObject);
            }
        }
        GameObject newItem = Instantiate(item.model, itemSpawn);
        newItem.transform.localPosition = new Vector3(0, 0, 0);
    }
}

itemSpawn is set to the "Item Spawn" object in the hierarchy below. The object that I'm spawning is a model imported directly from blender as a .fbx file.

timid quartz
#

I am having a weird tilemap instantiation offset problem. I am spawning a chunk of tilemap that is 20 by 20 at vector3.zero and in the inspector, both the grid and the chunk are correctly showing 0,0 for their positions. However, the actual center of the chunk is actually at 1, -1, and the borders start at -9 and go to 11 for the x axis (left to right), and -11, 9 for the y axis (bottom to top). So it seems even though the grid and the tilemap are at position 0,0, they are off by 1, -1 somehow. Anyone have any ideas?

bold swallow
lusty flax
wild cargo
robust condor
#

@wild cargoActually dont need to use string, can I get a reference to "ScriptableObject peasant" from the array looking up by type instead of looping through it?

polar acorn
wild cargo
# lusty flax it's just an imported model

Then if you want a custom center point without messing with the pivot in blender, you should make another prefab and nest that model seen in the image into it. This way that new prefab's root object is not the model, and instead the center point of it, so you can move the child (model) freely until the center relative to the model is where you want it to be

timid quartz
calm coral
wild cargo
wild cargo
true pasture
verbal dome
#

That's why it works in a foreach

polar acorn
static bay
#

some type of transform.children property or transform.GetChildren method would be much cleaner

#

there's likely some reason for this

lusty flax
calm coral
robust condor
#
[Serializable]
public struct CharacterClass
{
    public static ScriptableObject peasant;
    public static ScriptableObject knight;
}

[SerializeField]
CharacterClass[] _characterClasses;

How do I get the reference for peasant in this array?

Something like this but correct syntax:
ScriptableObject so = Array.FindIndex(_characterClasses, c => c == CharacterClass.peasant);

lusty flax
#

I have a model which is an empty with of the actual visible parts of the model parented to it (an empty with many meshes). I want to make this model act like a rigidbody, but how do I do this? Adding a rigidbody to the empty just makes it fall through the floor.

wintry quarry
#

but generally you get an individual one from the array with an index. e.g.

CharacterClass cc = _characterClasses[5];```
From there you can do whatever you want with it:
```cs
ScriptableObject peasant = cc.peasant;```
#

I will note a few concerning things here though:

  • Your class name should not end with Class. We already know it's a class, that's just noise for the brain.
  • Your fields are static which means they're not actually associated with any particular instance of the CharacterClass struct. This means my example above won;'t work but it's also pretty nonsensical for this to be static, though to be honest I don't really understand what you're trying to accomplish with these fields
robust condor
#

Class is a reference to the ingame class, not C# class

wintry quarry
#
  • Why are you using ScriptableObject as your reference type for those variables instead of your actual ScriptableObject derived class?
robust condor
#

But I dont want to find by hard index, instead lookup by type

wintry quarry
robust condor
#

Yeah but inspector doesn't work with dictionary

wintry quarry
#

You can put them in the inspector with an array and then populate a dictionary from the array at runtime in Awake

#

to get the best of both worlds

#

REgardless I have no idea what's going on with this:

[Serializable]
public struct CharacterClass
{
    public static ScriptableObject peasant;
    public static ScriptableObject knight;
}```
Why have a struct with nothing except a couple of static fields?
#

The struct is useless at that point since it holds no data

north kiln
#

it certainly isn't serializable!

robust condor
#

To populate in the inspector

true pasture
#

Is there a way to make a clone of a key, so I can have multiple of (technically the same key) in a dictionary. I know its hacky but It would instantly solve my problem. Like im adding 2 of the same CommandSO into the dictionary here and Is there a way via code like in my else statement?

wintry quarry
#

the static fields don't count

wintry quarry
#

If you want multiple things in the dictionary for a single key, make it a Dictionary<KeyType, List<ValueType>>

#

Or use a different key that's unique

warm condor
wintry quarry
warm condor
#

rb is a refrence to the rigidbody2d

wintry quarry
#

Yeah I got that part

#

velocityX is not a property that exists on Rigidbody2D

#

this should be a compile error

warm condor
#

really? I have been using it and it gives me the value of the x velocity

wintry quarry
#

I would expect rb.velocity.x

robust condor
#

@wintry quarrySo essentially I am forced to do it like this?

[Serializable]
public struct CharacterClass
{
    public ScriptableObject peasant;
    public ScriptableObject knight;
}

[SerializeField]
CharacterClass[] _characterClasses;

...
CharacterClass cc = new();
NPCManager.Instance.CreateNPC(cc.peasant);
...
Convert to a dictionary, lookup to get ScriptableObject
warm condor
wintry quarry
#

Oh good god

#

They added that apparently

#

that is new in 2023, interesting

wintry quarry
#

Again why are you using ScriptableObject fields?

#

nor do I understand this code snippet really.

robust condor
#

Because the assets are SOs

wintry quarry
#

they're some subclass of ScriptableObject

warm condor
wintry quarry
#

so why would you use ScriptableObject instead of the actual concrete type

wintry quarry
#

Please share it in a paste site

#

not uploading in discord

warm condor
#

wait sorry

#

@wintry quarry

timid quartz
#

ok so I have a bunch of tilemap "chunks" which are just sets of 20 by 20 tiles. in prefab mode, it seems like their center point is just... all over the place. what controls what the "center" of a tilemap or prefab is? they are both set to 0,0,0 in terms of position and 1,1,1 for scale (default) and are the same size (20 by 20 tiles)

#

As you can see they are really simple tilemap prefabs but the pivot point is just all over the place

#

it means that when I spawn random chunks at -20,-20 to 20,20 it's genuinely just hilarious, these chunks really think they are on some sort of grid somehow

wintry quarry
#

(by pressing Z or from this menu)

#

then you will see the actual position of your objects

timid quartz
#

that is, I believe, only for moving things around in the scene menu

wintry quarry
#

If you want it to appear at the object's actual pivot/position you set it to Pivot

#

If you want it to appear at the average of the bounds of all the renderers in the subhierarchy, you put it on Center

timid quartz
#

I re-ran the program with it set to center and as you can see, the origin of the instantiated tilemap chunks is still using its pivot rather than its center.

wintry quarry
#

your code will always use the object's pivot

#

assuming you're talkking about transform.position

timid quartz
#

Ah, let me rephrase, then.... I would love it if the pivot of my prefabs was reset to the center of the prefab. is there a way to set the pivot point to match the center?

wintry quarry
#

By setting it to pivot you can see the object's actual pivot and this will let you better think about things when writing your code

wintry quarry
timid quartz
#

it's just a tilemap, I posted the full hierarchy/inspector above, it's just 20x20 tiles

wintry quarry
#

in genral you can always add an empty parent object / move the renderer down to a child object. Then move the child object as desired to get it so the parent's pivot is where you want

#

for a tilemap you would actually repaint tiles

#

if you want to "change the pivot" for it

#

otherwise use the workaround with the empty parent

timid quartz
#

each chunk I've saved out has a different and very silly pivot point that, now that I think about it, might actually be the coordinates of the last painted sprite I've painted in that chunk

wintry quarry
#

Yeah it's basically due to how you created your prefabs

#

you weren't careful about the coordinates you were painting

#

so you painted different coordinate ranges on each

timid quartz
#

Ah, I see, so you're saying the relative coordinates of the sub-tilemap within the prefab controls the pivot?

wintry quarry
#

Just open one of your prefabs (with tool handle in Pivot mode)

#

and look at where the tiles are inside the prefab relative to the location of the root prefab object

#

that's your issue

#

fix all the prefabs so they are at the same position relative to the prefab root

timid quartz
#

there is only one object - the prefab itself - and it's only got one component - the tilemap. I see what you're getting at, though. I should adjust the tiles within the simulated "grid" so that they start at -10 and end at 10 in both directions and problem solved, since the pivot location is inherited from 0,0 within that sub grid I was painting on. funky stuff!

wintry quarry
#

yes, exactly

#

painting at the same coordinates in each is what you needed

timid quartz
#

that's quite strange. I suppose I had assumed the relative-to-the-sub-grid location was discarded in favor of the relative-to-the-real-grid location

#

ah well, as long as it works 😛

#

thanks!

wintry quarry
timid quartz
#

the grid that I am instantiating the tilemaps onto at runtime

wintry quarry
#

Doesn't each tilemap have its own Grid?

timid quartz
#

look at this, you've saved my project! what a hero! 😛

#

No, it's one grid, and then the tilemaps go onto it.

#

I have no idea if this is performant or not but it seemed like the proper way to structure this sort of generation?

wintry quarry
#

But what components on are on those spawned clones? Just Tilemap?

timid quartz
#

just tilemap

wintry quarry
#

interesting. Never tried it that way

timid quartz
#

well and a tilemap renderer

wintry quarry
#

Yeah not sure how that interacts with a parent Grid. I guess it doesn't interact at all?

timid quartz
#

I'm kind of winging it lol, I've done a ton of 3d procedural generation but never 2d. I think the parent grid still controls them the same way that a regularly drawn grid and tilemap works

#

I assume I am going to have to start culling the tiles eventually for perf reasons but I'm not sure when that "eventually" is

robust condor
#

How can I create an instance of a referenced scriptableobject in the inspector?

wintry quarry
wintry quarry
robust condor
#

Well, I give up for today

timber tide
#

giving up is not allowed

turbid quiver
#

hello, i’m new to programming, anyone would like to connect with me? i just need some people to talk with

tough geyser
#

hi, i started learning unity and the pathways on the site doesn't feel to be helping, what should i do?

tough geyser
#

it s just like showing you a concept game to make

#

not showing all the functions and classes that u can use

rich adder
#

those are in the documentation

tough geyser
#

yeah, it may help u a little bit

rich adder
#

you have to learn how to read the docs

#

practice more code if you want to learn code

tough geyser
#

ty

queen adder
#

I know im making a simple mistake but i cant tell what

#

!code

eternal falconBOT
queen adder
#

The raycast isnt working for whatever reason? I checked the Z positions theyre both zero. The layer mask parameter is set to bomb in the inspector and the Bomb Gameobject is set to the Bomb layer

north kiln
#

I'd also note that this snake-case naming convention isn't standard in C#

queen adder
#

The raycast was above the bomb hence why it wasnt working

queen adder
#

is there a bool that gets checked when unity is about to destroy everything (for when quitting game/playmode or switching scene)?

tacit estuary
# queen adder is there a bool that gets checked when unity is about to destroy everything (for...

For closing the game/play mode, you could use https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationQuit.html. Take a look at the notes towards the bottom depending on the platform you are building to. The closest thing you can do for the second one is to subscribe to the change scene loading events (very bottom of this page https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.html)

tacit estuary
queen adder
#

havent seen you since like before haloween though, people do carve you huh

tacit estuary
#

yeah I took a break for awhile 😅, had a bunch of class work to do

dark hatch
#

so, i have a static file (not inheriting from monobehaviour), and in one of the static functions in it, i want to create a short delay in execution. how can this be achieved?

#

is having an object with monobehaviour necessary to do this

wintry quarry
#

look into coroutines or async functions

#

I guess maybe async can work without a MonoBehaviour? I'm not that familiar with how async works in Unity

north kiln
#

One of async's benefits and downsides is that it's disconnected from Unity's object lifetime

#

So if you don't want async functions to leak out of scenes or into edit mode you should use a MonoBehaviour's destroyCancellationToken

#

On coroutines however: You can start coroutines in any class as long as you use StartCoroutine from a MonoBehaviour to tie it to its scheduler

dark hatch
#

hmm okay that helps

vapid yew
#

This is the first time I have written shader code. I am following this tutorial to help wrap my head around it all.

Traditionally, the code on the right of the screenshot was written in a .shader file I believe, however I am using Shader Graph in 2022.3.15f1 and can't seem to find a way to edit the custom function node through a text editor in Unity.

Can anyone help me figure out how I can follow this tutorial and write the shader code?

dark hatch
#

can the same coroutine have two instances of it run parallely (with different parameters)?

timber tide
#

you can read and set the member data of the object instance, but I'm not sure about the execution ordering. Probably related to when you start them.

dark hatch
#

i just need to make sure both will execute eventually, a frame or two of time delay is irrelevant in my case

timber tide
#

there's no parallel processing with coroutines, they run through the same update cycle as the rest of your code

dark hatch
#

ah, okay

timber tide
#

you can think of them as a standalone mono scripts without the overhead

#

and the benefit of sleeping them since polling in update is not always warranted when you want to check every 5 seconds or so

deft salmon
#

anyone know a basic playermovement skript i could use

#

to test in my project

cosmic dagger
deft salmon
#

ok

#

ty

eternal needle
scenic urchin
#

Gone back to Unity after a long time for a job and got this error in a old project, in my array. Looking the docs, RemoveAt is still a thing, shouldn't this work?

gaunt ice
#

where is the docu?

keen dew
#

Arrays are fixed size, it has never been a thing. Are you looking at List docs?

scenic urchin
#

google hates me

keen dew
#

I think this is the more relevant part:

#

Note: This is javascript only. C# does not use this feature.

scenic urchin
#

Now that you mentioned yeah I don't remember it being a thing

#

I gotta ask the me from four years ago what I was doing sadge

gaunt ice
#

there is no such thing in 2023 (2024?) so you need to change it

keen dew
#

If you need to change the collection size at runtime then use List instead

#

(which does have .RemoveAt)

scenic urchin
#

Thank you guys!

scarlet shuttle
#

i dont understand most of this code, its a third person camera that orbits the player but it doesnt stay behind the player when the player turns, ive been trying to google for a hour and cant figure how to do it

public class ThirdPersonCamera : MonoBehaviour
{
    public Transform playerTransform;  // The playerTransform object to orbit

    public float mouseSensitivity = 150f;

    float yRotation = 0f;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        yRotation -= mouseY;
        yRotation = Mathf.Clamp(yRotation, -10f, 60f);  // Limit vertical rotation to avoid flipping
        

        // Orbit around the playerTransform
        Quaternion rotation = Quaternion.Euler(yRotation, 0, 0);  // Only rotate around Y and Z axes
        Vector3 negDistance = new Vector3(0.0f, 0.0f, -5.0f);  // Adjust the distance from the playerTransform
        Vector3 position = rotation * negDistance + playerTransform.position;

        transform.rotation = rotation;
        transform.position = position;
    }
}```
scarlet shuttle
simple sun
#

yeah that bad setup, that makes the camera rotate along the player as the player rotates, am i right?

scarlet shuttle
#

it does, but not here cause the code overwrites it

graceful oar
#

I have a simple platformer game with Photon and parrelsync and for some reason when I start the game (only sometimes) some assets randomly disappear even from the scene view. Does anyone have any ideas why that happens please? I dont know how to test it since its literally random

vast ivy
#

could someone help me debug this problem, ive been on it for a while but dont see whats wrong with it.
I have an inventory system but the first slot keeps getting overriden because it thinks the slot is null or empty.
heres my inventorymanager function:

public void AddItemToInventory(GameObject pickedUpObject)
    {
        // Check if the item to add is not null
        if (pickedUpObject != null)
        {
            // Get the Item component from the picked-up object
            Item itemToAdd = pickedUpObject.GetComponent<Item>();

            // Check if the itemToAdd is valid
            if (itemToAdd != null)
            {
                // Iterate through the inventory slots to find the first empty slot
                for (int i = 0; i < inventorySlots.Count; i++)
                {
                    InventorySlot slot = inventorySlots[i];

                    // Check if the slot is empty
                    if (slot.IsEmpty())
                    {
                        // Log the slot index where the item is added
                        Debug.Log("Added item to slot " + i);

                        // Add the item to the empty slot
                        slot.AddItem(itemToAdd);

                        // Update the UI to reflect the changes
                        slot.UpdateUI();

                        // Item added successfully, so return
                        return;
                    }
                }

                // If no empty slots are found, handle as needed (e.g., show a message)
                Debug.Log("Inventory is full or no matching slots.");
            }
            else
            {
                Debug.Log("Picked up object is not an item.");
            }
        }
    }

heres my other functions:

private Item currentItem; // The item currently stored in this slot

public bool IsEmpty()
    {
        return currentItem == null;
    }
#

I've already checked and the slots are seperated into their own boxes so its not like theres only 1 slot to go into, the index is telling me its only trying to enter the first box, and considering the first slot image keeps getting overriden, it tells me that the IsEmpty function is not working how it should

gilded pumice
#

Guys how do I make Time.deltaTime useable with an int value instead of a float? I can see some solutions like using Math.FloortoInt but even in unity documentation there isn't a great example of how to implement it (do I instantiate a variable with Time.deltaTime?, am I forcing the float number to convert to a int in start method? etc). Here's the code in question: https://paste.ofcode.org/YGpTJHkHZK6sCRJiRRg4gu

code block in question starts at line 59. Any insight would be much appreciated

wild cargo
#

No sorry, your timeLeft variable is actually an integer, which means when you subtract Time.deltaTime from it at runtime it'll lead to a compile error

gilded pumice
#

timeLeft is a private float

#

oh I didn't remove the code I was playing with, mb

#

yes it throws an error, I was just trying to figure out where to/what to change to int, timeLeft or Time.deltaTime

wild cargo
#

But rhen why even convert 10.0f into an integer at start when you can just make it the default value in the definition, so
private float timeLeft = 10f

gilded pumice
#

I don't want it as a float, because I get a compilation error. If it remains a float, the timer shows like millionths of seconds on the UI and I don't want that

#

compilation error as int I mean

wild cargo
#

That can be fixed easily by rounding it into whatever decimal place in the UI script you want

#

The actual value should be kept as a float

gilded pumice
#

ah

river roost
#

If you just want it to show as an int in the UI just do this: ```cs
phaseText.text = $"Phase Cooldown {timeLeft:0}"; // the :0 tells it to display as a whole number, you can also do 0.0 for one decimal or 0.# to only show the decimal when there is one

wild cargo
#

Also, it seems like the bool "spaceCooldown" is never set to false, so line 59's if statement always runs, the else never does

wild cargo
gilded pumice
#

it is, I just left out the bottom half of the code to try to cut back on the reading others had to do (didn't figure it had anything to do with my question)

gilded pumice
#

is it better practice here to just paste the whole code regardless?

wild cargo
#

I'd just comment the 100 liner out to pseudo code and write what it does rather than copy paste it all

gilded pumice
graceful oar
#

I have a simple platformer game with Photon and parrelsync and for some reason when I start the game (only sometimes) some assets randomly disappear even from the scene view. Does anyone have any ideas why that happens please? I dont know how to test it since its literally random

river roost
gilded pumice
trail hull
#

Hi guys.
I am trying to build a map editor for my game.
I have a 8x8x8 grid, and i'd like to let the user create a cube by moveing the mouse and right click.
I am currently using a Raycast from mouse position, then taking the last raycasted item and create the cube at that position, but that's not what exactly i wanted because if the user wants to spawn a cube on the middle of the grid, this would be impossible because this will never be the last raycasted object.
Do you have any idea on how i can achieve this result?

ruby python
gaunt ice
#

raycast can hit multiple objects and you should introduce some ways so that users can select the exactly position as above comment

trail hull
trail hull
gaunt ice
#

the ray is created by mouse pos so i dont know how you mix them together, or you have already "mixed" them together

trail hull
#

i have not mixed them, it was an idea but i don't know if that makes sense.
I thought the raycast is giving me all the slots aligned with the camera and the mouse, so i may take the mouse world position and find the slot that has the same coord inside the raycasted list, does that make any sense?

ruby python
#

Is your scene 'static' or can the player move the camera around the grid?

trail hull
gaunt ice
#

the set of mouse pos in world space (yes "set of", not only a single point) is represented by the ray already

ruby python
#

Okay, well if you're already zooming, my idea would work, you just need to set a 'desired' distance from the camera for the ray to hit (I think), you've got most of what you need already.

trail hull
trail hull
ruby python
#

bit of pseudo....

If 'slot' != distance { ignore slot}; type of thing

teal viper
gaunt ice
#

again the ray can hit multiple objects including the object with larger z
so you must create other mechanisms to choose the exaclty block

#

ray doesnt ignore any z, but you let the ray ignore it

ruby python
#

Are you giving the player any feeback on which block is selected? (ie, hologram type block that appears)

trail hull
gaunt ice
#

i think you dont understand why a mouse position on screen can generate a set of position in world (the ray)
https://en.wikipedia.org/wiki/Ray_tracing_(graphics)

In 3-D computer graphics, ray tracing is a technique for modeling light transport for use in a wide variety of rendering algorithms for generating digital images.
On a spectrum of computational cost and visual fidelity, ray tracing-based rendering techniques, such as ray casting, recursive ray tracing, distribution ray tracing, photon mapping an...

teal viper
#

For reference, unity would usually place object on surface of other objects that you drag on to.

graceful citrus
#
        if (Input.GetKey("1"))
        {
            calibration = 1;
        }
        if (Input.GetKey("2"))
        {
            calibration = 2;
        }
        if (Input.GetKey("3"))
        {
            calibration = 3;
        }
        if (Input.GetKey("4"))
        {
            calibration = 4;
        }
        if (Input.GetKey("5"))
        {
            calibration = 5;
        }
        if (Input.GetKey("6"))
        {
            calibration = 6;
        }

how should i optimise this? i see its very unoptimised but i can't figure out an effective way to optimise it

trail hull
languid spire
gaunt ice
#

loop unrolling is already optimized
if you prefer flexible way to write this, use loop

graceful citrus
teal viper
teal viper
#

*at what depth.

ruby python
#

If I'm understanding correctly, this is the kinda thing you want to do?

languid spire
trail hull
graceful citrus
languid spire
#

exactly how I wrote ir, try to write the code then come back

teal viper
gaunt ice
#

yes, you dont understand mouse position to world position is one to many mapping
so you cant basically just use mouse position to get the block

ruby python
trail hull
graceful citrus
ruby python
#

My suggestion was to introduce a distance check of some kind as the player can already zoom into the grid and rotate around it. Can't think of another way.

trail hull
#

TheMightySpud answer is correct, using the wheel or numbers to let the user select the Z layer block, but i'd like to know if there something more automatic to get that

teal viper
ruby python
#

It would need to be a distance to camera check though I Think as the raycast hit distance would change based on xy position of the mouse.

graceful citrus
#

i've immediately run into an issue, how do i make an array of inputs? there is, to my knowledge, no variable type for inputs @languid spire

languid spire
#

no need, I said an array of keycodes

teal viper
graceful citrus
#

what like [1, 2, 3, 4, 5, 6]?

gaunt ice
#

i have said mouse position to world position will generate a ray and IMPOSSIBLE to just use the ray to get one position. sigh

languid spire
#

no, KeyCode.1 etc

graceful citrus
#

ahh, but whats the variable type for that?

languid spire
#

KeyCode

ruby python
#

KeyCode is the variable type.

graceful citrus
#

ohhhhhhhh

ruby python
#

!code

eternal falconBOT
graceful citrus
#

i didn't know that! thats useful

ruby python
#
[Header("Keybind Assignements")]
    [SerializeField] KeyCode forwardKey = KeyCode.W;
    [SerializeField] KeyCode backwardsKey = KeyCode.S;
    [SerializeField] KeyCode strafeLeftKey = KeyCode.A;
    [SerializeField] KeyCode strafeRightKey = KeyCode.D;
    [SerializeField] KeyCode sprintKey = KeyCode.LeftShift;

Not an array (yet)

teal viper
#

Maybe check if there are any blocks in vicinity and place at the closest cell to them..?🤷‍♂️

trail hull
graceful citrus
#

wait is it Alpha1?

#

and Alpha2?

languid spire
#

yes

#

unless you want the num pad ones

teal viper
trail hull
#

yes

teal viper
#

Then maybe avoid raycasts at all? Just use some math

graceful citrus
trail hull
languid spire
ruby python
#

NumPad1 etc. I think. if you just type KeyCode. (with the period), your IDE will bring up a list of everything you can add.

gaunt ice
#

@trail hull

  1. mouse position to world position mapping (or operator) returns a ray (ie a set of point)
  2. raycast can hit multiple objects
  3. so there is no any way to select exactly one objects just based on mouse position on screen
trail hull
brave tapir
#

So I added visual scripting to my unity game because i thought it would just open an editor not create whole package, so my build to web failed for some reason so i deleted the visual scripting folder to see if it would help and now my game wont even play

graceful citrus
gaunt ice
#

ok you have a 2d point and you want to get a 3d point
how can you do this? one axis is missing

teal viper
trail hull
gaunt ice
#

so why 2d to 3d mapping actually returns a ray not just one point

trail hull
languid spire
trail hull
#

so basically on other games 3d editors, what are them using for building the maps? I mean, does them force the user to build blocks near other blocks, does them let the user use the mouse and then scroll the wheel for the depth or how?

teal viper
#

You could cast into a plane a certain distance away from the camera

trail hull
# teal viper How?

that's the question, if there is a way to find it based on mouse position or something, without asking the user to select the depth or scroll the wheel

teal viper
graceful citrus
#
private ArrayList<KeyCode> big = (KeyCode.Keypad0, KeyCode.Keypad1, KeyCode.Keypad2, KeyCode.Keypad3, KeyCode.Keypad4, KeyCode.Keypad5, KeyCode.Keypad6);

alright so i've got this now, which is obviously wrong but i don't know what to do if i want it to work

trail hull
gaunt ice
#

actually i suggest scroll the mouse wheel and let the user set the sensitivity
a famous "3d voxel editor" is mineraft

teal viper
languid spire
teal viper
graceful citrus
trail hull
languid spire
teal viper
graceful citrus
teal viper
#

In the first place, making it a physical grid with colliders is not a great idea imho.

split raft
#

Is it a good idea trying to make player movement without using the "Update()" method and just using send message from "Player Input" component? I don't know if it is common to turn gravity on and off depending on player's state:

#
[SerializeField] Camera cameraRef;
[SerializeField] float moveSpeed = 10.0f;
[SerializeField] float jumpStrenght = 6f;

Rigidbody rb;
[SerializeField] float speed;
[SerializeField] bool doubleJumpReady = true;
float lookSensitivity = 0.05f;
Vector2 moveInput;
Vector3 currentRotation;
Vector3 velocity;
Vector3 cameraRotation;

void Start()
{
    rb = GetComponent<Rigidbody>();
    currentRotation = transform.rotation.eulerAngles;
}

void Update()
{
    //empty
}

private void OnMove(InputValue inputValue)
{
    moveInput = inputValue.Get<Vector2>();

    Move();
}
private void Move()
{
    if (rb.useGravity && Physics.Raycast(transform.position, transform.up * -1, out RaycastHit hitInfo, 1.001f))
    {
        if (hitInfo.transform.gameObject.layer == 0)
        {
            rb.useGravity = false;
            moveSpeed *= 2;
        }
    }
    float velocityY = rb.velocity.y;
    velocity = (transform.forward * moveInput.y + transform.right * moveInput.x) * moveSpeed;
    velocity.y = velocityY;
    rb.velocity = velocity;
}

private void OnJump()
{
    if (Physics.Raycast(transform.position, transform.up * -1, out RaycastHit hitInfo, 1.001f))
    {
        if (hitInfo.transform.gameObject.layer == 0)
        {
            doubleJumpReady = true;
            rb.useGravity = true;
            moveSpeed /= 2;
            rb.AddForce(Vector3.up * jumpStrenght, ForceMode.Impulse);
        }
    }
    else if (doubleJumpReady)
    {
        doubleJumpReady = false;
        rb.AddForce(Vector3.up * jumpStrenght, ForceMode.Impulse);
    }
}

private void OnLook(InputValue inputValue)
{
    Vector2 lookDelta = inputValue.Get<Vector2>() * lookSensitivity;
    
    cameraRotation = cameraRef.transform.rotation.eulerAngles;
    cameraRotation.x -= lookDelta.y;
    cameraRef.transform.rotation = Quaternion.Euler(cameraRotation);

    currentRotation.y += lookDelta.x;
    transform.rotation = Quaternion.Euler(currentRotation);

    Move(); //Updates direction
}
dark hatch
split raft
#

Whoops

river zealot
#

trying to make an inventory system for my game using ui item script player pickup scrip ui managmet scrip and inventory manager if anyone knows what there doing regarding this i would apreachiate input as i am getting a bit lost

frosty hound
#

What part are you getting lost with?

river zealot
#

everything my coding still are minimal and i am using chat gpt

#

if you are willing to go on call i can share screen

frosty hound
#

Nope. Especially if you're ChatGPTing it

#

Good luck

graceful citrus
#

@languid spire i've done a list iterating through it, and its throwing "IndexOutOfRangeException: Index was outside the bounds of the array"

river zealot
graceful citrus
graceful citrus
#

it might be hard to read idk

#
        for (int i = 0; i <= big.Length; i++)
        {
            if (Input.GetKey(big[i]))
            {
                calibratedMarkerTransform = MarkerTransforms[i];
                calibratedObjectTransform = ObjectTransforms[i];
            }
        }
        for (int i = 0; i <= MarkerTransforms.Count; i++)
        {
            if (MarkerTransforms[i] != calibratedMarkerTransform)
            {
                MarkerTransforms[i].GetComponent<MeshRenderer>().enabled = false;
            }
            else
            {
                MarkerTransforms[i].GetComponent<MeshRenderer>().enabled = true;
            }
        }

@languid spire the code is pretty much supposed to sort through a special compass to see what its calibrated to detect, then later down the line it runs the code to display the position of the calibrated objects

frosty hound
eternal falconBOT
#

:teacher: Unity Learn ↗

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

graceful citrus
#

the whole compass part works, its just calibration that needs work

river zealot
#

ive done all the other code bro not going to have afight new year new life

languid spire
# graceful citrus ```cs for (int i = 0; i <= big.Length; i++) { if (In...

ok 2 things

bool found = false;
for (int i = 0; i < big.Length; i++)
        {
            if (Input.GetKey(big[i]))
            {
                calibratedMarkerTransform = MarkerTransforms[i];
                calibratedObjectTransform = ObjectTransforms[i];
                found = true;
                break;
            }
        }
if (found)
        for (int i = 0; i <= MarkerTransforms.Count; i++)
        {
            if (MarkerTransforms[i] != calibratedMarkerTransform)
            {
                MarkerTransforms[i].GetComponent<MeshRenderer>().enabled = false;
            }
            else
            {
                MarkerTransforms[i].GetComponent<MeshRenderer>().enabled = true;
            }
        }
graceful citrus
#

i, don't get it

#

what is it doing?

#

@languid spire how could it not be found?

languid spire
#

If the right Key was not pressed

#

say I press A

graceful citrus
#

oh i see

#

gotcha

keen dew
#

i <= will always overshoot the array/list

languid spire
#

good point

graceful citrus
languid spire
#

i < big.Length

graceful citrus
#

my brain was screaming at me but i was telling myself that wasn't the case

#

i should've trusted myself on that one

#

alright im gonna implement that code now

#

ok @languid spire it works, but now i have a secondary issue very closely related

#

for some reason when its calibrated to 1, 2, 3, 4, 5 or 6 (which are all the objectives, 0 is calibrated to know where the enemy is) its pointing the same direction

#

which cannot be the case

languid spire
graceful citrus
opaque kettle
#

I really need help with this script i use to procedurally generate a map in my 2d game, the map generates just fine. using noise, but i cannot get the "GetHeightAtPoint" working, it never matches what i generated, it seems like it tells me some random height, idk. https://pastebin.com/dYKvZj1J

languid spire
graceful citrus
languid spire
#

no, I just hate them,

graceful citrus
#

but it would help to understand what the device does and what the problem is

languid spire
#

no it wouldn't because I would still not know anything about the underlying code

graceful citrus
#

okay in that case

#
        if (calibratedObjectTransform != null && cameraObjectTransform.GetComponent<Camera>().enabled)
        {
            SetMarkerPosition(calibratedMarkerTransform, calibratedObjectTransform.position);
        }

this code runs in the fixed update

#
    private void SetMarkerPosition(Transform markerTransform, Vector3 worldPosition)
    {
        Vector3 directionToTarget = worldPosition - cameraObjectTransform.position;
        float angle = Vector2.SignedAngle(new Vector2(directionToTarget.x, directionToTarget.z), new Vector2(cameraObjectTransform.transform.forward.x, cameraObjectTransform.transform.forward.z));
        float compassPositionX = Mathf.Clamp(2 * angle / Camera.main.fieldOfView, -1, 1);
        markerTransform.localPosition = new Vector3(0.5f * compassPositionX, 0, -0.00453125f);
        markerTransform.GetComponent<MeshRenderer>().enabled = (markerTransform.localPosition.x > -0.4495 && markerTransform.localPosition.x < 0.4495);
    }

this is the void which it is running

#

the device functions as a compass, but like one of those compasses that you get at the top of your screen in some games, to show where objectives are

#

currently, when i set the device to detect 1, 2, 3, 4, 5 or 6 its all pointing in the same direction

#

which is not what it should be

#

it should be pointing towards objective 1, 2, 3, 4, 5 or 6

languid spire
fossil ether
#

Hey guys, I'm trying to render a parametric sphere mesh but it isn't getting rendered correctly. I think there's something wrong with my indexing but can't find it.
https://gdl.space/igikubudey.cs

graceful citrus
#

its just that when its one of the objectives, it always points at objective 1

#

which is bad

languid spire
#

those statements are contradictory, either the code works or it does not

fossil ether
graceful citrus
#

does that make sense?

gaunt ice
#

dont understand how you create sphere but look like you missing one step (connect the last iteration to first iteration
ie i==UResolution - 1 and j==VResolution - 1

opaque kettle
#

I really need help with this script i use to procedurally generate a map in my 2d game, the map generates just fine. using noise, but i cannot get the "GetHeightAtPoint" working, it never matches the map i generated, it seems like it tells me some random height / the height of an entirely other map, like nothing even close to what its supposed to be. idk, because everything to me seems like it should work, but it doesnt. https://pastebin.com/dYKvZj1J

fossil ether
languid spire
graceful citrus
gaunt ice
#

i completely forgot how to get a point by theta and phi and radius and i dont want to do the math
you should store the result points of first iteration by theat or phi (you can use hashmap since most likely you will getting the exact result when calculate the angle) then you can just get the index of vertex back and create the triangle

languid spire
graceful citrus
#
    private void SetMarkerPosition(Transform markerTransform, Vector3 worldPosition)
    {
        Debug.Log(markerTransform);
        Vector3 directionToTarget = worldPosition - cameraObjectTransform.position;
        float angle = Vector2.SignedAngle(new Vector2(directionToTarget.x, directionToTarget.z), new Vector2(cameraObjectTransform.transform.forward.x, cameraObjectTransform.transform.forward.z));
        float compassPositionX = Mathf.Clamp(2 * angle / Camera.main.fieldOfView, -1, 1);
        markerTransform.localPosition = new Vector3(0.5f * compassPositionX, 0, -0.00453125f);
    }

this code needs to run every frame. that is crucial

fossil ether
languid spire
graceful citrus
gaunt ice
#

simple example of create a sqaure
CB
DA
you will calculate A then B then C then D finally go back to A to create the DA edge, so you can store the index of A by hardcode or look up table
btw i think you can hardcode the iteration of index anyway, you probably will store the vertex at some determistic way
0
1
2
3
4
5
6...

fossil ether
#

okay i'm thinking

#

wouldn't this result the same as what I'm doing now though?
Vector3 p0 = ParametricSphereFunction(u, v);
right now i'm picking a point on the surface and right after adding it to the vertices array i'm creating a triangle using that point. I don't go through the vertices array to create the triangles

gaunt ice
#

but you only create the triangles from 0 to UResolution - 2, you block it by if statement

#

as the same as i only create the edge of AB BC CD but missing DA

fossil ether
#

yeah that makes sense

#

ok i'll try to change the algorithm then, thanks for the help

boreal tangle
#

If I wanted to draw a background for my unity game should I make the drawing the same scale as the camera or is their an easier way.

wintry quarry
#

What you're describing would be a bug, and I don't think it's the case. Possibly something is wrong with your keyboard.

graceful citrus
#
cyl.localEulerAngles = Quaternion.Euler(0,i * 45,0);

i feel like i've done this a million times, but why isn't this working?

wintry quarry
#

Wait sorry

#

You are assigning a quaternion to a vector3 property

graceful citrus
wintry quarry
#

Oh would be localRotation =

graceful citrus
wintry quarry
#

Or use localEulerAngles = new Vector3

graceful citrus
#

cheers

#

wait why tf does altering y and altering z do the same thing @wintry quarry

wintry quarry
#

Gimbal lock probably?

graceful citrus
#

sounds scary

proven lark
#

!code

eternal falconBOT
proven lark
#
    {
        anim = GetComponent<Animator>();
        rb = GetComponent<Rigidbody2D>();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
     if (collision.gameObject.CompareTag("Traps"))
        {
            Die();
            deathSoundEffect.Play();
        }
    }

    private void Die()
    {
        anim.SetTrigger("death");
        rb.bodyType = RigidbodyType2D.Static;

    }
    

    private void RestartLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        
    }```

I have a pretty basic death script here but im confused on why the function "Die" hass to be called in order to take effect but not RestartLevel
graceful citrus
#

you failed

teal viper
proven lark
#

i woudlve thought i would have had to add "RestartLevel" somewhere in here

terse raven
#

Should I use A* or NavMesh (2D)

#

I have around 200 enemies for context

gaunt ice
#

surprisingly navmesh use a*

terse raven
#

oh perfect

gaunt ice
#

navmesh is the graph data structure not the pathfinding algorithm

terse raven
#

Alright thank you, would you say navmesh is easy to impliment?

gaunt ice
#

navmesh needs mesh renderer afaik

terse raven
#

im not sure what that is

gaunt ice
#

i googled you dont need it now

terse raven
#

Oh okay, can you recommend any learning resources?

gaunt ice
#

you can google lots of tutorual in youtube on how to use navmash in 2d

terse raven
#

are they quite common tutorials or are they years old lol

#

make it so when you jump the drag is adjusted for in air movement and on ground drag for when you are on the ground

#

This might work

#

have you tried adjusting gravity to see if they does anything, changing mass might also work

#

I think you can let me double check

#

My apologies thats only in 2D. Are you accessing gravity or just using forces>

#

maybe using a constant gravity force will help. I'm not that brill at 3D and dont have much experience maybe someone else might have a deeper insight

teal viper
proven lark
#

i probably just dont understand coding well enough to get whats going on tho

teal viper
proven lark
teal viper
golden otter
proven lark
#

this is the closest thing to calling it i have in the script

golden otter
#

or you’re might loading the scene by directly calling the unity api

teal viper
keen dew
#

If you see the animation before the level restarts I'm guessing it's triggered by the animator

teal viper
#

right click the LoadScene method and select "find by reference"

proven lark
teal viper
#

Then it's either what Nitku said or you're invoking it from a button/unity event

proven lark
#

leme rewatch the video and see if i missed something

#

oh wait

#

i think the death animation is a trigger for it

#

oh yeahh it is

#

sry i didnt realize

terse osprey
#

Hello, I wasnt to check if a bool has been false for 3sec or more. If yes then run a certain function

polar acorn
charred spoke
#

if bool false start timer if timer over DoSomething

terse osprey
#

ahh thats so simple as compared to what I found on the internet and makes so much sense

#

thankyou

polar acorn
misty obsidian
#

Hello! I need help. I'm using this script to only one object in 1 scene from 2 scenes and I want to make it's optional to set up, not obligatory. How to make it optional?

#

The script is connected to two scenes

polar acorn
graceful oar
#

I have a simple platformer game with Photon and parrelsync and for some reason when I start the game (only sometimes) some assets randomly disappear even from the scene view. Does anyone have any ideas why that happens please? I dont know how to test it since its literally random

terse osprey
ivory bobcat
#

You'll simply want to set the flag true in that function and evaluate it elsewhere - somewhere that occurs every frame.

terse osprey
ivory bobcat
#
Update:
    if isHit == true
        isHit = false
        elapsed += delta time
        if elapsed >= Time.time
            do stuff``````
Hit:
    isHit = true;
    currentHealth -= amount;```
waxen oracle
#

Is there a way to put the game in slow mo to get a better idea of what’s happening?

polar acorn
#

If you want to reset the timer, then reset the timer. Don't bother changing the boolean

frosty hound
waxen oracle
#

oh thats cool

#

thanks

bitter crest
waxen oracle
#

how would i alter timescale

#

would that be in scripts

bitter crest
#

Time.timeScale simple script yeah

waxen oracle
#

ill save that for the future

#

sounds pretty helpful

bitter crest
#

Well also think if you want your user to have a pause button

#

Unity makes it easy to slow/stop/speed up the flow of game time

#

And also keep things separate from that if you need to (like if you wanted music to keep playing while paused, etc)

waxen oracle
#

For a pause i assume timescale would be 0?

knotty gust
#

does JSONutility.FromJSON validate variables ?

languid spire
knotty gust
#

yhh okay thats good enough thanks

burnt vapor
knotty gust
#

are those already installed with unity/visual studio, and how would i use them in JSONutilities place

pastel sinew
#

Quick question, are the Input Systems 1D Axis broken, or is it me? It does not give me continous values. Rather I get -1, and 1.

rich adder
pastel sinew
# polar acorn What have you mapped it to

Want to use one pedal for negative input and another for positive. Or should I just use Up and Down Actions instead? (Which is what I am implementing rn as a workaround)

#

Vertical is also Value and Axis like Horizontal on the screenshot.

novel shoal
#

for (int i = 0; i < buttons.Length; i++)
{
buttons[i].gameObject.SetActive(false);
}
is this a good approach to deactivate all the buttons in the title screen?

wintry quarry
novel shoal
#

making an array with them and insteand of repeating button.gameobject.setactive(false), using a for loop

novel shoal
novel shoal
next stone
#

Hello, in my code I return a null since I'm am not sure what to return,
I have a score that is set up so that when it reaches a score of 25 the objects will stop spawning ( this because of the return null ) then the player can walk up to the set teleporter to teleport to the next room, where the spawn area has to change but that doesn't happen.
I don't know how I can fix my problem

opaque kettle
rich adder
#

read this

rich adder
#

then you didn't lock it

#

where are you running this function

opaque kettle
rich adder
eternal falconBOT
rich adder
#

pastebin sucks

opaque kettle
rich adder
#

why would i need "public" paste be bigger DIV than actual code 😵‍💫

#

put debug.log make sure that function is running

#

if it is you have another script unlocking it

rich adder
robust condor
#

How can I do TryGetComponent in children in a performant manner?

rich adder
#

if its locked it will be cetered, if its not locked then it wont be center. You have another one overriding it then

#

search your script

opaque kettle
rich adder
rich adder
opaque kettle
robust condor
#

@rich adderExtending TryGetComponent?

rich adder
rich adder
#

how did you search

opaque kettle
solemn wraith
#

Hi I have this custom struct inside my MonoBehaviour:cs [System.Serializable] public struct CameraZone { [SerializeField] public List<Transform> cameraCheckpoints; private Vector2 minCoordinates; private Vector2 maxCoordinates; private Vector2 centreTarget; }

and you can see I have private members, but this is not what I want. As it is serializable, I just want the currently private members to just not be visible in the inspector, however accessable and modifiable by the monobehaviour it is in. How can I do this?

rich adder
#

do you have any custom scripts named Grid ?

opaque kettle
#

OHHHHH

opaque kettle
solemn wraith
rich adder
#

it works fine if you click the gameview, only time it doesn't if you press escape

next stone
#

Hello, in my code I return a null since I'm am not sure what to return,
I have a score that is set up so that when it reaches a score of 25 the objects will stop spawning ( this because of the return null ) then the player can walk up to the set teleporter to teleport to the next room, where the spawn area has to change but that doesn't happen.
I don't know how I can fix my problem

solemn wraith
rich adder
# solemn wraith what how?

lookup properties

   [System.Serializable]
    public struct CameraZone
    {
        [SerializeField] private List<Transform> cameraCheckpoints;
        public Vector2 MinCoordinates { get; private set; }
        public Vector2 MaxCoordinates { get; private set; }
        public Vector2 CentreTarget { get; private set; }
    }```
eternal falconBOT
solemn wraith
rich adder
#

why exactly using SO for mutable data, if you change this one you will change values in all of them

solemn wraith
rich adder
#

eg if one SO has MinCoordinates as 0,3
then anything that has so with MinCoordinates will have 0,3

next stone
# next stone Hello, in my code I return a null since I'm am not sure what to return, I have a...
    // Function to determine the spawned target based on the player's score
    GameObject GetSpawnedObject()
    {
        // This MAIN Object Spawner Manager function for the spawn areas || NOTE: the other Object spawner area scripts are copies from this "main" script
        if (ScoreManager.scoreCount == 25 || ScoreManager.scoreCount == 50 || ScoreManager.scoreCount == 75 || ScoreManager.scoreCount == 100)
        {
            Debug.Log($"Score is {ScoreManager.scoreCount}, no targets will spawn.");

            // Set up logic for when the score matches specific values
            teleporter.SetActive(true); // Activate the teleporter

            // Enable player movement
            if (playerMovement != null)
            {
                playerMovement.EnableMovement();
            }

            return null;
        }

        else if (ScoreManager.scoreCount >= 50 && ScoreManager.scoreCount < 100 && TargetS != null)
        {
            Debug.Log("Selected TargetS");
            maxObjects = maxObjectsTargetS; // Change maxObjects for TargetS
            return TargetS;
        }
        else if (ScoreManager.scoreCount >= 25 && ScoreManager.scoreCount < 50 && TargetM != null)
        {
            Debug.Log("Selected TargetM");
            maxObjects = maxObjectsTargetM; // Change maxObjects for TargetM
            return TargetM;
        }
        else if (ScoreManager.scoreCount < 25 && TargetL != null)
        {
            teleporter.SetActive(false); // Deactivate the teleporter

            Debug.Log("Selected TargetL");
            maxObjects = maxObjectsTagetL; // Reset maxObjects for TargetL
            return TargetL;
        }
rich adder
#

not easy to read code like this, esp mobile

solemn wraith
#

So essentially the 1st field is given by the "level designer" and the remaining 3 fields are precalculated and stored to save time in each frame update. I think I may have to switch to classes but I'm not exactly sure.

rich adder
next stone
rich adder
#

do you know what links are?

next stone
#

yes I do

celest holly
#
public class Shoot : MonoBehaviour
{
    public GameObject bulletPosition;
    public GameObject bulletPrefab;
    [SerializeField] private float bulletSpeed;
    private Camera cam;
    [SerializeField] private VisualEffect muzzleFlashEffect;
    public float bulletLife = 4f;
    [SerializeField] private Animator animator;
    [SerializeField] private VisualEffect muzzleFlash;
    public bool isShooting = false;
    [SerializeField] private GameObject muzzleLight;

    private void Start()
    {
        cam = Camera.main;
        animator = GetComponent<Animator>();
        muzzleLight.gameObject.SetActive(false);
    }
    private void Update()
    {
        if (Input.GetMouseButtonDown(0) && !isShooting)
        {
            isShooting = true;
            ShootBullet();
            HandleVisuals();
            StartCoroutine(shootDelay());
        }
    }

    public void ShootBullet()
    {
        GameObject bullet = Instantiate(bulletPrefab, bulletPosition.transform.position, bulletPosition.transform.rotation);
        //Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
        RaycastHit hit;
        if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, Mathf.Infinity))
        {
            Debug.Log(hit.point);
            Vector3 bulletDirection = hit.point - bulletPosition.transform.position;
            bullet.GetComponent<Rigidbody>().velocity = bulletDirection * bulletSpeed;
        }
        else
        {
            Vector3 bulletDirection = (Camera.main.transform.position + Camera.main.transform.forward * 1000) - bulletPosition.transform.position;
            bullet.GetComponent<Rigidbody>().velocity = bulletDirection * bulletSpeed;
        }
       
        Destroy(bullet, bulletLife);
    }

Can anyone help me figureo ut why my bullet zooms away at light speed when i am not pointing at a target? it works fine if i hit an object with the raycast

eternal falconBOT
rich adder
#

god people who mindlessly paste their entire classes

rich adder
celest holly
#

bit entitled

#

ok ill put it in one of those code block things

#

https://hatebin.com/etcictfeey
Can anyone help me figureo ut why my bullet zooms away at light speed when i am not pointing at a target? it works fine if i hit an object with the raycast

rich adder
celest holly
#

it wasnt my entire class i had other functions i left out

rich adder
celest holly
#

because its to do with visuals and stuff

#

unrelated to my problem

keen dew
warm condor
#

hey guys, so I have prviously asked a question here, but no one helped me fix a problem I have. Can anyone check what I wrote in here to know what the problem is?#💻┃code-beginner message

rich adder
#

also the direction isn't normalized

celest holly
rich adder
#

so hit distance also affects it as you described in problem

celest holly
#

should i make the 1000 a smaller number?

keen dew
#

Velocity should be set to bulletDirection.normalized * bulletSpeed

celest holly
#

thank you

keen dew
#

same thing earlier when the raycast does find a target, now the bullet speed depends on how far the target is

celest holly
#

normalizingit seemed to fix all the issues

#

thank you very much

keen dew
#

although I don't see why you have to do the raycast in the first place, it looks like the bullet goes to the same direction in either case

celest holly
#

i was having problems with the bullet not going to the centre of my screen

#

the camera raycast was my solution and its working out alright

rich adder
# next stone yes I do

did you solve the problem or are you having problem pasting code in PasteLink provider

knotty gust
#

is there a way to get around dictionarys being non serializable

#

im tryna have it save from editor to play mode but it gets cleared on play

hoary locust
#

Hello there! when I try to create a URP shader it just becomes a pink missing texture. Anyone knows what's up with it?

slender nymph
hoary locust
#

ah alright ty

lusty flax
#

i got stuck in an infinite loop how do i stop the program

rich adder
#

End Task

timber tide
#

list of structs too (kvp struct)

lusty flax
#

i got stuck in an infinite "while" loop

rich adder
#

if you didn't save, you're fooked

#

always ctrl+s everytime I press play 🤷‍♂️

next stone
rich adder
#

make sure it showing how you instantiate

warm condor
#

you know adding force

thorn holly
#

Does it give an error?

warm condor
#

no

celest holly
#
public class BulletCollision : MonoBehaviour
{
    [SerializeField] private Rigidbody rb;
    [SerializeField] private float bulletForce;
    private void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    private void OnCollisionEnter(Collision objectHit)
    {
        if (objectHit.gameObject.layer == LayerMask.NameToLayer("Ground"))
        {
            print(objectHit.collider.name);
        }
        if (objectHit.gameObject.layer == LayerMask.NameToLayer("Humanoid"))
        {
            print(objectHit.collider.name);
            objectHit.gameObject.GetComponent<Rigidbody>().AddForce(rb.velocity * bulletForce, ForceMode.Force);
        }
    }
}

hi again, im not sure if this is programming or physics related (maybe theyre similar enough so that it doesnt matter) but a rigidbody component on a gameobject is causing my bullet to hardly ever detect the collision and phasing through it. I can send a video butim not sure if thats allowed lol

graceful citrus
#
cyl.localRotation = Quaternion.Euler(-90, 0, i * 45);

no matter how i alter this, it doesn't rotate on the right axis. why can't i rotate it how i want?

ruby python
# celest holly ```c# public class BulletCollision : MonoBehaviour { [SerializeField] privat...
keen dew
#

select the object in scene view and play with the rotation in the inspector until you find the right axis

solemn wraith
celest holly
#

yep

#

im trying to check overlapping objects now

#

i dont know why rigid bodies are affecting it

next stone
rich adder
next stone
rich adder
#

they all do the same thing

next stone
#

I pasted my hole call but still the same result, I'll try the other sites now

rare basin
#

Hatebin never worked for me aswell it's bugged

fringe perch
#

Hello my enemy (rigidbody) is rotating when hit by another rigidbody even when it has freezeRotation to true. I don't rotate of this object at all and only move it in 2d towards its target with addForce. Does someone maybe know where it could come from ?

rich adder
celest holly
next stone
rich adder
#

also how much of this script is written by AI

#

a lot of weird statements here

dry tendon
#

Hey, does someone knows how can i join a project that one friend shared me with unity version control? He has invited me with my mail... but i can't find the project anywhere and i'm incapable of start editing it hehe. Please... i need help :>

rich adder
dry tendon
#

Thaankss

graceful citrus
#

i have all these different transforms, yet they all return the same vector3 position. specifically, they all return the position of the first one (uniglow). if i change one of the list items to a random cube for example, it returns the position of that cube where i want it, but for some reason these glows and the objects related to this return position 1. whats going on?

next stone
lusty flax
#

This is a fragment of a script that I made to drop player-held items in my game. This is the part of the script that makes the item fall downwards until it touches the floor, where it stops. The problem is, since I'm using Physics.CheckSphere() to detect this, some objects clip into the floor because they are made of only one GameObject. What alternatives are there for Physics.CheckSphere() that would do this correctly?

while (running)
{
    newModel.transform.position = new Vector3(newModel.transform.position.x, newModel.transform.position.y - 0.01f, newModel.transform.position.z);
    for (int i = 0; i < childCount; i++)
    {
        if (Physics.CheckSphere(modelBody.transform.GetChild(i).transform.position, 0.01f, ground))
        {
            running = false;
        }
        else if (Physics.CheckSphere(modelBody.transform.GetChild(i).transform.position, 0.01f, incinerator))
        {
            Destroy(newModel);
            running = false;
        }
    }
    if (loopCount > 1000)
    {
        Destroy(newModel);
        running = false;
    }
    loopCount++;
    Debug.Log(loopCount);
}
rich adder
# next stone Most part of the scripts, to start the target spawning again

So start the coroutine again ?
My suggestion is to stay away from AI coding since it provides 0 learning and confusion when something breaks/goes wrong since you wouldn't know how to debug it. The code seems overly "complex" and jumbled for something probably easily done with a few lines of code

next stone
dry tendon
#

and then to introduce their mail there, right?

native flicker
#

If i wanted to make a idle game, is this good to calculate how much i earn when offline?

#
    private void OnApplicationFocus(bool hasFocus)
    {
        if (!hasFocus)
        {
            lastFocusTime = DateTime.Now;
            animator1.speed = animationSpeed;
        }
        else
        {
            animator1.speed = animationSpeed;
            TimeSpan offlineTime = DateTime.Now - lastFocusTime;
            int moneyToAdd = (int)(offlineTime.TotalSeconds / 15);
            if (moneyToAdd > 0)
            {
                moneyadd(moneyToAdd, 1);
                data.lastLoginTime = DateTime.Now;
                Debug.Log("You earned " + offline + " money while away." + offlineTime.TotalSeconds);
                offlineText.text = "You earned " + offline + " money while away.";
                moneyText.text = "Money: " + data.money.ToString("F2");
            }
        }
    }```
#

for android btw

keen dew
#

At some point the phone will kill the app so the values need to be saved to persistent storage

warm geode
native flicker
#

ah alr cause im a beginnner and thats why i thought this should be here

warm geode
#

What even is this abomination

keen dew
#

no this is fine

native flicker
#

ay idea how should do it?

warm geode
#

You can add strings in c#?

keen dew
#

Playerprefs should be good enough for this purpose

native flicker
#

whats that and what does it do?

warm geode
#

It stores player preferences

#

You use it to store data like high score, and other data