#💻┃code-beginner

1 messages · Page 108 of 1

queen adder
#

im using 2017 and my vsc is configured

rich adder
#

mate your code editor and unity version have nothing to do

polar acorn
#

it's for every unity version ever made

#

Because it's not a Unity thing

#

it's an IDE thing

meager sentinel
rich adder
#

you'll be fine

meager sentinel
queen adder
#

yea, didnt noticed that before, such bad misinformation

#

(still waiting for peeps to pull you over to VS though)

rich adder
#

they're getting rid of mac version of vs

queen adder
#

oh mac, that changes things

rich adder
#

so annoying having to switch to vscode for my mac

queen adder
#

so that's why no "use VS" comments in 😁

rich adder
#

Use VS if don't want problems 🙂

slender nymph
#

or rider if you can't use vs

queen adder
#

mac have rider?

rich adder
#

ye

#

all platform

queen adder
#

android rider is promising

rich adder
#

im just poor

slender nymph
#

just be a student and get it for free. or grab it during one of their EAP times

queen adder
#

but actually, ill buy rider if they can do android

rich adder
#

ew coding on mobile lol

queen adder
#

not that bad if you have work with lots of idle times

#

anyway too chitchat already, let's drop UnityChanOops

amber spruce
#

Vector2 screenPos = cam.WorldToScreenPoint(target.position);
Vector2 offset = new Vector2(0, 50);
Vector2 finalPos = screenPos + offset;
transform.position = finalPos;

smth like that

rich adder
amber spruce
#

i know it can be compressed down but that would work

#

right?

rich adder
#

yea

#

well if its UI shouldn't you use anchoredPos ?

amber spruce
#

idk it works

rich adder
#

sweet

#

how did you come up with 50? don't use magic numbers XD

eternal needle
#

try it on different aspect ratios, that 50 might cause it to break in certain resolutions

rich adder
#

smart

amber spruce
queen adder
#

hardcoding numbers are nasty and usually will bite you later 💯

amber spruce
#

how would i get the correct number then?

queen adder
#

wait i dunno the whole problem

rich adder
amber spruce
#

this was my original message

rich adder
#

but. i think the problem was the anchord pos

amber spruce
rich adder
#

anchoredpos should be on the canvas no?

queen adder
#

ah it was offset, it should be fine as long as it looks what you wanted, thought u are using hardcoded for anchors/pivots

rich adder
#

honestly I havent done too much UI to have a straight answer sorry

slender nymph
#

easy answer: instead of hardcoding any sort of offset, give the object this UI element is follow a child object that the UI object will follow instead and just offset the child object. then you won't need an offset specified for the UI object

amber spruce
slender nymph
#

right so make it follow a child of that object that is offset so that this object appears in the location you want

amber spruce
#

ah ok

slender nymph
#

then you won't need to do any addition to get the position, you just get the target's position in screenspace and make that the UI object's position

amber spruce
#

now i gotta figure out where exactly i want it to go so it doesnt look weird

queen adder
#

What callback can I use that works like update but in scene mode?

rich adder
#

Update can work in editor btw

queen adder
#

just every refresh though

#

I kinda want a constant thing

#

nvm, ig i can just use menuitems for this case

rich adder
queen adder
#

i press w it put wall on where my mouse in scenetab is

whole isle
#

would any1 like to assist me in the animation chat

#

ive been at it for a while

#

still cant find a fix

rich adder
queen adder
queen adder
lethal kestrel
#

with dictionaries is there a way i can get the just the string inside the brackets. e.g get "string" from [string].

slender nymph
#

like you have a string that contains brackets in the string? or do you mean something else?

lethal kestrel
#

so im basically using a raycast to hit an object and get the string name from that object. string itemToDrop = hit.transform.GetComponent<GroundItem>().ToString(); . then i pass it to another method called addItem which takes the string and checks it in the dictionary.

slender nymph
#

well for starters, you shouldn't be relying on object names for logic. that's a road that leads to ruin

lethal kestrel
#

but the dictionary cant find the item

queen adder
#

I'd add my own string field actually, what is it for?

lethal kestrel
#

the object also has a scriptable item on it called wood for example

#

AddItem("Wood", 49); this works
AddItem(itemToDrop, 1); but this doesnt

queen adder
#

oh inventory system?

lethal kestrel
#

its for picking up items and adding it into an inventory

#

yeah

fluid kiln
#

hello!
I'm making my code modular!
Let me make an example

Health stat

% Health stat

They are both stat objects
Is there any way to make Health stat scale with % at an updated value without it increasing infinitely?

queen adder
#

what is itemToDrop?

#

a string?

lethal kestrel
#

yeah

#

i get a string based off the item scriptable

#

well i think i do.

queen adder
lethal kestrel
#

no error just cant find it in the dictionary

#

thats why im thinking the brackets are including in the check

queen adder
#

try to log what it is first before trying to look ipt up in dict

lethal kestrel
#

so its trying to check [Wood] instead of "Wood"

queen adder
#

instead of guessing if it have [] or not

lethal kestrel
#
Debug.Log(itemName);```
thats how i check for it after it passes
queen adder
#

log it before, nvm it's a tryget

slender nymph
#

okay so the issue was actually removing the brackets from a string the whole time and isn't really related to the dictionary.

#

but still, don't rely on the names of gameobjects for your logic. give your GroundItem class a variable that you can assign the item type to and use that instead

lethal kestrel
#

ohh right so its checking "Wood" instead of [Wood]?

queen adder
#

sq brackets makes it confusing if you dont apprecite dictionaries being list with keys

lethal kestrel
#

i might have done this the hardest way without even needing to

slender nymph
#

cause that leads to a scriptable.
UnityChanHuh

lethal kestrel
#

ill pm u its weird

#

if thats okay

slender nymph
#

no

lethal kestrel
#

my apologies

slender nymph
#

post your !code here

eternal falconBOT
lethal kestrel
slender nymph
#

instead of calling ToString on your GroundItem component, you should access its itemScriptable variable (not a very good name btw) then access that object's itemName variable

queen adder
#

yea, it's total fail if that thing is cloned

slender nymph
#

i would personally not even rely on a string to determine what the item actually is. i personally prefer enums for item types

queen adder
#

id do both, one for dicts, one for functionality lookup

#

id rather do strings in dicts than enums

slender nymph
#

but why?

lethal kestrel
#

i see can. My thought was using scriptables as an easy way to change different variables of my item. then just to call it and check it

queen adder
#

orange font more readable than enum blue blushie

slender nymph
#

with an enum as the key you know there will only be a set number of different items in the dictionary. with a string if you have any that are perhaps spelled wrong (since there's no compile time checking for it) you may end up with a different number of objects in the dict than you'd be expecting

queen adder
#

but strings as item name makes itmore versatile in editor

#

I can easily add an item without having to change code

#

if it needs a function, like eat a food, only then i will extend my enum

#

dont have answer there, really hard to find an inventory system to follow

#

it's an intermediate concept (with a lot of way to implement)

lethal kestrel
#

yeah i made my inventory first then tried using scriptables as items and dictionaries to store them just gotta finetune some things i guess. appreciate the respones tho very helpful!

fluid kiln
rich adder
queen adder
#

add a second float field that is total heath modifier?

#

thats my understanding of the q

#

like there's a constant hp, and a percentage hp

fluid kiln
queen adder
#

oh.. your character parameters are it's own classes

slender bridge
fluid kiln
fluid kiln
#

Im trying to make something modular for a long term complex game

queen adder
#

I can imagine the concept, idk what the question is though

fluid kiln
#

And I wasn’t using scriptable objects at all which many told me is a mistake

queen adder
#

you dont need SO for this

#

better not to

#

just composition

fluid kiln
#

Hmmm I think it’s better shown than explained

queen adder
#

nvm,SO can do better

fluid kiln
#

I do not make classes for every stat.
But I make a skeleton of what every stat would need

#

And then I make a SO to create the stat itself

queen adder
#

ye i understand that part, i just dont know what you are mainly asking

#

you seem to be good enough to implement it

#

if you asking if it's doable, it is, is that what you need?

fluid kiln
#

There is a subclass that is called percentage stat , and it increases another stat by a percentage based on its base value, what I’m asking is, how can I do that modularly

#

Cuz if I use update it’s gonna increase it infinitely

#

If I use start it’s gonna happen only once

slender bridge
#

ok so here i thought you were asking about a design question

queen adder
#

use a float that get's accessed when you needed the field

fluid kiln
teal viper
queen adder
#

anyway, if you're still not totally set on that, interfaces are cleaner way to keep modular data

#

might as well consider it

fluid kiln
queen adder
#

we could give better insight if you share some of that juicy codes

teal viper
fluid kiln
#

Oh it’s a lot of separate codes and sadly I’m on bed.
I would have to give you a tour of my project haha

fluid kiln
teal viper
#

You can't predict what you'll need in the future and wether it would fit your existing code. The best you can do is decide on the feature set of your app and make sure current implementation is built with it in mind.
You can also always refactor.

#

There's almost no code that can't be adjusted to fit some new purpose. Especially since you have the whole source code.

fluid kiln
#

Do you feel like my current approach would be even better with interfaces?

My old project didn’t even use subclasses nor abstract classes, it truly was a disaster

teal viper
#

I've no single clue what your current approach is. You didn't share any code.

fluid kiln
#

Fine fine let me get up of bed lol

#
using UnityEngine.UI;

public class HealthManager : MonoBehaviour
{
    public int maxHealth = 100;
    public int currentHealth;
    public Text healthText; // UI Text element to display health

    // Event triggered when health changes
    public delegate void OnHealthChanged(int currentHealth, int maxHealth);
    public event OnHealthChanged HealthChanged;

    void Start()
    {
        currentHealth = maxHealth;
        UpdateHealthUI();
    }

    // Method to take damage
    public void TakeDamage(int damageAmount)
    {
        currentHealth -= damageAmount;
        if (currentHealth <= 0)
        {
            currentHealth = 0;
            // Trigger any events or actions for player death
            // You can add a method call here or dispatch an event
        }

        UpdateHealthUI();
        NotifyHealthChanged();
    }

    // Method to heal
    public void Heal(int healAmount)
    {
        currentHealth += healAmount;
        if (currentHealth > maxHealth)
        {
            currentHealth = maxHealth;
        }

        UpdateHealthUI();
        NotifyHealthChanged();
    }

    // Update UI text to display current health
    void UpdateHealthUI()
    {
        if (healthText != null)
        {
            healthText.text = "Health: " + currentHealth.ToString();
        }
    }

    // Notify subscribers that health has changed
    void NotifyHealthChanged()
    {
        HealthChanged?.Invoke(currentHealth, maxHealth);
    }
}

Example of old code, the healthmanager did EVERYTHING for the health stat

queen adder
#

omg

fluid kiln
#

this is the new code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "NewPlayerStat", menuName = "ScriptableObjects/Player Stat/Player Stat")]
public class PlayerStat : ScriptableObject
{
    public string name;
    public float amount;

    public float GetAmount(){
        return amount;
    }
    public void SetAmount(float x){
        amount = x;
    }
    public void AddAmount(float x){
        amount += x;
    }
    public void RemoveAmount(float x){
        amount -= x;
    }

}```
queen adder
#

that can be like cut 1/3

fluid kiln
#

and this is a subclass of it

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

[CreateAssetMenu(fileName = "NewRegenerativePlayerStat", menuName = "ScriptableObjects/Player Stat/Regenerative Stat")]
public class RegenerativeStat : PlayerStat
{   


    public bool canRegen = true;
    public PlayerStat affectedStat;
    float timer=0;
    public void Update(){
        timer += Time.time;
        if(timer>=1 && canRegen){
            affectedStat.AddAmount(amount);
            timer = 0;
        }
    }
}
queen adder
#

still can be simplified, just do a prop setter

fluid kiln
#

wdym?

queen adder
#
public float Amount 
{get; 
set{
  amount = value;
 // do some logic with value
}```
teal viper
#

Okay, so you want to have a generic stat class?

queen adder
#

my derpy heart cant

timber tide
#

I actually don't dislike being verbose on the data being set because when you run into stuff like DealDamage(float value) method sometimes I ask myself do I put negative values in here or positive

fluid kiln
#

yes that and if i want to add something i'd have to bugfix stuff much more, where in this system i feel like thanks to polimorphism and overriding i have to be way less worried

queen adder
teal viper
fluid kiln
#

oh, then they are NOT what i tought they were

#

i tought they were like gameobjects and prefabs but no need to be instantiated

#

pain.

queen adder
#

they are more of a normal object

#

that you can turn into asset

fluid kiln
#

problem is and what confuses me the most is, you can do that with gameobj aswell

timber tide
#

well, it depends how you want to do it. It's not necessarily incorrect to write to them but usually you'd just use a plain c# script

queen adder
#

gameobjects lives in unity heirarchy

#

SO's dont (they live in references)

fluid kiln
#

you lost me here sorry

#

X.X

#

so since its unchangeable stuff you're saying i should use them for things like

#

unique items

queen adder
#

they're not unchangeable

timber tide
#

you use them as if you were to use json or plain text

queen adder
#

it's just their stats are decided at the start

fluid kiln
#

oh i see

#

well ill drop them then

#

still learned a lot from sublclassses,static classes and such;(they fixed a lot of clutter in my old code)

Now ill go back to bed and watch a video about interfaces.

queen adder
#

but you're right on that fact that they are more useful on storing data of unique items

timber tide
#

You can treat them like prefabs and create instances of them to write to which is fine.

#

even use them like a singleton/static class

solemn fractal
#

is better to use always fixedupdate or just update?

queen adder
#

but yea, interfaces are interesting if you understand it, you can do

public class Goblin : IHealth, IMana, ISanity

#

and stuffs

fluid kiln
#

that sounds like dragging scripts into an object?

queen adder
#

hard coding capabilities blushie

fluid kiln
#

like if i want a goblin to walk i'd just put a walking script on him?

#

oh

#

ill have to check that

#

cuz i won;t understand it without scenarios haha

queen adder
#

actually, ignore the verbs there, just do store the interface for the stats

#

the attack, run and walk better go in inheritance imo

fluid kiln
#

I’ll have to check that out cuz like SOs I’m not fully grasping it and I’ll end up using it wrong

#

But the doubt is the same why use SOs when there is prefabs and why use interface when there is components and viceversa

lethal kestrel
#

huge thanks to @slender nymph got it working after some messing around with what u said.

#

and @queen adder ❤️

slender bridge
fluid kiln
#

Oh I get it now it’s like class inheritance but instead of inheriting you only share a method

#

For sake of polimorphism

solemn fractal
fluid kiln
#

Well that’s super useful!!

queen adder
slender bridge
queen adder
#

so each stats can do differently depending on where they are

fluid kiln
fluid kiln
slender bridge
queen adder
#

they're the same, except, gameobjects are physical obj

#

and SO's are like immaterial

#

if you put it that way

fluid kiln
#

I see thanks!

#

So like when an item drops on the ground and is looted instead of keeping it in the scene I can just turn it into a SO?

queen adder
#

and btw, avoid using GO prefabs as holders u pass around

timber tide
# fluid kiln I’ll have to check that out cuz like SOs I’m not fully grasping it and I’ll end ...
public interface IEntity : IAttackable{}

public class Enemy: IEntity
{
  [SerializeField] EnemySO data; //can also inject it through an assign/init method for object pooling
  
  float health = data.health; //copy data you are going to change into the class
  float attack = data.attack;

  //EnemyTags enemyTags = data.tags 
    //you don't always need to copy data and instead choose                    
    //to read directly from the SO if it's not meant to ever change

  public EnemyTags Tags => data.enemyTags;

  public Attackable(IEntity attackingEntity) //Required implementation via interface
  {
    //Attack
  }

  public ChangeHealth(float healthValue)
  {
    health += healthValue;
  }
}```
queen adder
#

that's just not their job and can be nasty if it go wrong

fluid kiln
queen adder
fluid kiln
#

I need to put some kind of on start auto attach on them to fix that

timber tide
#

it was more complicated before I realized maybe it didn't need to go too crazy

#

almost had the interface IDoesYourTaxes

fluid kiln
#

Ugh with all these tools the hardest part is figuring out when to use what

#

I guess that’s been the main issue for me

#

But yes everything is doable with anything

#

So far interfaces sound so good for things like Iclickable Idraggable that’s the first thing that comes to my mind

#

So the inventory system will make me hate myself less at least

queen adder
#

but, if you understand interfaces as how they are, it's great

timber tide
#

they're useful because otherwise you'd have to type check the implementation, but interfaces guarantees that if your enemy has the IAttackable interface then it must have the method implementation Attackable(attacking entity) and you can directly call it without caring what logic is contained

fluid kiln
#

Yeah and if you want to animate say 3 different things in a given List<> you can just do foreach animate with IAnimable

timber tide
#

and likeso, you can pass types around by their interfaces, not caring what the actual type is. This is helpful to group stuff such as all your enemies and allies together such as a list of List<IEntity>

fluid kiln
#

Ooooooh that’s amazing omg I’ll have to theorycraft so much tomorrow on paper

#

When I used unity some months ago it didn’t have an integrated version control, or better yet, it did have it but it was a hella bugged add on. Is this new one good?

robust condor
#

How do I NOT hide the cursor when I click on the play window?

fluid kiln
#

Sorry for bombarding you with questions lol.

queen adder
#

do you use Cursor anywhere in your code?

fluid kiln
#

Oh now I get it

robust condor
#

@queen adderNo, I have the 3rd person controller installed, maybe that does it?

queen adder
#

what is that? a new unity package?

#

if so, i guess that does it

#

cant help there though

robust condor
#

Yeah that was it, it is a starter asset

fluid kiln
#

Besides SO, prefabs, inheritancy, interfaces, extension do you think there are more tools that are important?

queen adder
#

delegates my beloved

#

and unityevents

fluid kiln
#

Okay events I think I know about

#

But it’s basically interfaces 2.0 with one less step nay?

queen adder
#

no

#

they are more or a box that can hold method/s and call it later

fluid kiln
#

Like when x Triggers every class triggers Y method

queen adder
#

no

#

x and y can put letters in that box, then you can call that box later, anything inside will fire then'

solemn fractal
fluid kiln
queen adder
#

they just can hold methods, doesnt care where from, as long as the methods match them, they will hold it and fire when you want\

#

if you want to do something when your main character die

#

have a delegate hold it, then fire when the player die

#

or if you want the goblin king to get mad when you kill a goblin, have a goblin register their deaths to the goblin king,

fluid kiln
#

Thanks!

rich adder
#

going to come in handy , making some editor tools

#

thx!

queen adder
#

I 100% hope my tile pallete isnt so slow for me though that I needed to go make this

rich adder
#

doesn't Keycode better than a string

#

or was that not working?

queen adder
#

i prefer string than enum in inputs (because vsc sometimes do weird suggestions)

#

esp in editor things

#

I do change it on final builds though

rich adder
#

yeah I'd make an abstraction class for rebinds but I'll stick with enum
was just wondering if Event.keyCode worked, i'll just try it out ig 😅

slender bridge
# solemn fractal if I use fixed in one script i need to use in all the others?

If its rigidbody movement I would always use fixed update unless you have a good reason not to. The only thing that can cause more crap is if you have any object positions that need to be synced that run in different update methods. rigidbodies are normally used in fixed update for consistency in physics calculations.

queen adder
#

answer is, fixedupdate and update have their own jobs

#

update are guaranteed per frame (it will catch anything that happens)
fixed only happens at physics interval

woven crater
#

Any good tutorial on how to use interface?

rich adder
queen adder
rich adder
# woven crater Any good tutorial on how to use interface?

this guy is good though for gamedev
https://youtu.be/-asqmmY-FUM

2023 Game Dev Course - https://game.courses/bc?ref=15
Fantastic Fantasy Asset Sale - https://prf.hn/l/me3dPA0

00:00 - Introduction
00:21 - What are Interfaces?
00:56 - Why they Exist
01:20 - IInteractable Example
02:12 - MonoBehaviours & Interfaces
02:40 - Plugins / Mod Systems
03:50 - Unit Testing
04:47 - Event Systems

▶ Play video
rich adder
#

also that youtube channel is pretty good, which part do you not understand ?
although that video he don't put rigidbody movement in fixed update which is wrong

timber tide
#

that assignment looking a little overdue

queen adder
#

i got past the first one then in the middle of the second one he switched to somthing else in the play view

#

i was copying what he did exactly but when he got to that part

#

my stuff broke

rich adder
#

🤷‍♂️ whatever that means

queen adder
#

ill try doing it again right now

slender bridge
queen adder
#

doesnt say what year though

#

u is safe

#

lol

#

could be 2079 or could be 1990

#

i wasnt even in existance then

#

wait unity didnt block the "lol", i remember server blocks short comments

#

bug?

#

mayhaps

#

ok imma go work on it, ill send a message here if it doesnt work

rich adder
#

also the mods put it not unity lol

queen adder
#

regex is handling it?

rich adder
#

yup

queen adder
#

oh my god, i dont even have microsoft visual installed on my laptop

#

how do i install it again i forgot

#

!ide

eternal falconBOT
queen adder
#

thmank

magic linden
#

Probably a dumb question but how would I reference the collider of a gameobject in a script that isn't attached to said gameobject?

low perch
magic linden
#

No the other object is just an empty gameobject with a collider attached, no script

low perch
#

yeah ik

magic linden
#

Oh sorry I thought you were asking me if the other object had a variable, I misread

low perch
#

public GameObject collider_object;

fill it in in the editor

collider_object.getcomponent<>

#

i don’t really remember the exact syntax but you get the point

rich adder
#

why do that

#

just reference the collider directly

low perch
#

why not do that

#

because you can’t serialize components

tender breach
#

I'm making a tetris-like game, but when the pieces aren't 0 degrees, they don't fall down.

rich adder
low perch
#

and you mean are 0 degrees

low perch
rich adder
magic linden
#

Testing that one now

nimble tartan
#

Hello guys do you have any article that advises about good practices and mainly patterns for Assets folders and Hierarchy?

rich adder
rich adder
#

i always put my script folders as _Scripts they're always ontop the project files

#

same with _Prefabs

tender breach
rich adder
#

dude what shite IDE are you using

#

why is the code not formatted

tender breach
#

Visual Studio

rich adder
#

visualstudio ? did you configure it

teal viper
magic linden
#

Sorry forgot that SerializeField was a thing

tender breach
low perch
#

You need to reset rotating = true

tender breach
#

I think I formatted it

tender breach
teal viper
tender breach
#

Well I forgot.

rich adder
#

scroll up

hoary karma
#

private void OnTriggerEnter(Collider other) { Debug.Log("test"); if (other.CompareTag("Snowball")) { currentHealth = currentHealth - snowballDamage; Debug.Log("damage taken"); } else if (other.CompareTag("Gift")) { Debug.Log("Work"); CameraEffects.ShakeOnce(); currentHealth = currentHealth - snowballDamage; } } why is this ontriggerenter not working? when it hit the "Snowball" object it does register and subtract the health. but when it hit the "Gift" object, the Debug.Log("test") is printed on the console but it doesnt subtract the health or print the Debug.Log("Work")??

rich adder
#

this code doesnt move anything anyway @tender breach

low perch
#

Yes but you never set Rotating to true after it goes false

rich adder
#

three

#

!code

eternal falconBOT
tender breach
low perch
#

oh

teal viper
#

It doesn't sound like physics is moving it.

low perch
#

and move the one always at 0,0,0

tender breach
teal viper
#

In code.

tender breach
teal viper
#

You must be moving it somewhere, otherwise it wouldn't movem

low perch
teal viper
#

Share that code

tender breach
rich adder
#

lol

eternal needle
#

what on earth is that formatting

hoary karma
rich adder
rich adder
tender breach
teal viper
tender breach
#

They are different scripts

eternal needle
#

you should first format your code properly, because there is no way you can clearly understand what its doing

rich adder
tender breach
rich adder
#

regardless of rotation its gonna go same way nvm then hah

tender breach
#

How do I fix it?

teal viper
#

At this point, I think you should follow a tutorial...

teal viper
tender breach
#

I tried tetris tutorials, but they had similar code.

teal viper
rich adder
teal viper
rich adder
#

ah ok forgive me then 😅

teal viper
#

That's fine. I don't use it either.

rich adder
#

put it to world space direction, so keys always put it same direction regardless of rotation

magic linden
rich adder
#

Dependecy Injection

#

assuming the only way you cant use serialize field is the object is prefab and ur referencing something in scene or vice versa
otherwise you should be using only serializefield, no reason otherwise .
Maybe TryGetComponent for other realtime stuff

eternal needle
rich maple
#

how do i pause only the vector movement and not the animation in unity?

rich adder
rich maple
#

i mean, i just want to pause movements of gameobjects

rich adder
#

so put a bool?

#

if(canMove)
//do movement stuff

rich maple
#

coool

#

thanks

#

i think i can do thate

rich adder
#

all i could think of with limited info 😅

rich maple
#

ah no problem

queen adder
#

im trying to write a bit of code that makes the projectiles destroy when they hit objects other then their clones all the layers are set up and its still not working could i have some help?

queen adder
#

ok

#

gms

hoary karma
eternal needle
nimble tartan
#

What may I have to put on Awake method and Start method? The same for Update and FixedUpdate?

summer stump
#

They are pretty different, in that start and awake run once in the objects lifetime, while update and fixedupdate run many many times

nimble tartan
#

The main diference about what kind of code I have to put inside each one.

verbal dome
#

You dont have to put anything in them

north kiln
#

You don't have to do anything

summer stump
nimble tartan
north kiln
#

Generally Awake is used for gathering references/early setup, Start is used to act on that setup.
Update is self-evident, and FixedUpdate is for physics.

summer stump
nimble tartan
verbal dome
nimble tartan
#

I have one player variable like total HP that is intialized one time... where should I have to put in Awake or Start? I have a GetComponent to get for example, a AnimationControl... where I have to put?

#

What question I have to make to decide where I'll put the code that is called only once

summer stump
north kiln
#

Why is total HP not initialised in the declaration/inspector?

nimble tartan
#

I have more than one player and each one have its own total hp

summer stump
rich adder
#

with databases ideally you want async

#

unity is meh with asyc tho so ig coroutine too works

#

they have async void Awake() 😬

timber tide
#

make an init method and just populate that until ready

sly wasp
#

Hey, how would I do a yield return new WaitForSeconds(timeF) but if a bool is set to true do a different function?

#

So it interrupts and stops the waitforseconds

rich adder
#

nvm

sly wasp
#

Ik how to use wait until a bool is true, but I don’t know how to do both

rich adder
#

i dont understand why wouldnt a regular if + else work?

#

if(somethingTrue) DoOtherThing(); break;

pseudo ermine
#

Hey Hey!

I hope everyone is well, it’s currently 4AM and I’ve had an idea for a college project however, I would like some ideas/advice on how to construct it, you could say.

The idea is a checkpoint system where UI is used, if the player has reached this checkpoint, unlock it on the checkpoint selection menu and then when they load in again, they can choose to go from that checkpoint.

summer stump
#

if (bool)
yield return WaitForSeconds(10);

else
yield return WaitForSeconds(20);

?

sly wasp
#

Ok I need to explain better, you guys obviously can’t read minds (I’m meaning this literally not an insult)

summer stump
rich adder
pseudo ermine
#

OH

#

OOPS

#

ITS 4AM 😂

north kiln
#

don't use WaitForSeconds, instead use yield return null; inside of your own loop that counts, and break out of the loop based on a boolean

#

or use WaitUntil with two checks, one against time and the other against the boolean

#

Or switch to async, learn how all that works, and use a cancellation token 😄

robust condor
#

I am using triggercolliders, how can I call "other.MyCustomFunction" on the object that enters the trigger? Ofc trigger script does not know if MyCustomFunction exists or not beforehand, so need to see if it does before calling

sly wasp
#

So I have a bool
saveMeTime = false

When my character crashes it runs a coroutine and needs to wait for a specific amount of seconds (5.95f in my case), then it runs some other stuff under that. But I’d like that to not happen if I use a saveMe (revive) function. So what I did was create that bool, and under the wait for seconds I put
If (saveMeTime == true)
Other balalalalaaa

That works great. But what if I crash and revive, then crash very soon, the wait for seconds hasn’t finished yet so then it will run that code too early because it sees saveMeTime as true

#

I put saveMeTime to true at the beginning of the crashing coroutine

north kiln
#

You should cancel the old coroutine

summer stump
#

Coroutine routine = StartCoroutine(Method());

(Not the best way, but just an example of how to cache the coroutine in order to stop it)

verbal dome
sly wasp
#

I’ve done a lot of attempts to try to stop the coroutine, but it seems to not work. I also don’t know how to rephrase that coroutine because it has
CrashCoroutine(string anim) (I have something for it to determine it’s an animation already)
So when I need to run that corutine I have CrashCoroutine(“fallAnimation”)

When I rephrase it it gives me errors then, I’d also have to change all the other parts in my script to match this new rephrased coroutine

#

Pretend rephrase says cached

verbal dome
north kiln
sly wasp
north kiln
#

I have no idea what that means or why that stops you from using this method in any way

#

If you're talking about passing a parameter to the coroutine, just do that

sly wasp
north kiln
#

and did you pass a string to your coroutine?

sly wasp
#

Yes

north kiln
#

Show your code then

robust condor
#

I have some navmesh agents I move on click, and I spawn like 100, but some are really slow at moving while the other 80 are going in a huge blob, the rest are kind of lagging behind and not moving to the point

verbal dome
#

From a quick google search I saw that apparently there is a limit of around 100 agents until they start bunching up

sly wasp
# north kiln Show your code then

My computer is taking a while
I’ll send a short example

private Coroutine deathPlayer;

void Start()
{
deathPlayer = StartCoroutine(DeathPlayer()):
}

public IEnumerator DeathPlayer(string anim)
{
WaitForSeconds(f):
Functions
}

robust condor
#

If I make them kinematic they will move where they need

north kiln
sly wasp
north kiln
#

No, that's not how you pass an argument to a function

ivory bobcat
#

You'd only need the type if you're declaring a new variable or casting - not including class member definitions and whatnot.

north kiln
#

Your function is declared as DeathPlayer(string anim), it needs a string passed to it. Either pass a string variable DeathPlayer(MyString), or use a string literal DeathPlayer("Example").

sly wasp
north kiln
#

Then pass it to your coroutine

#

I don't know how clearer I can be. You declared a function that takes a string, you never passed it a string. That's an error. Pass it a string and the error will go away

rich adder
summer stump
#
public String foo;


deathPlayer = StartCoroutine(DeathPlayer(foo));
sly wasp
#

Will
deathPlayer = StartCoroutine(DeathPlayer(""));
work because I have no errors

north kiln
#

sure, that is an empty string

summer stump
summer stump
# sly wasp yes

Ok then sure. Not sure why you would want that, but have at it

sly wasp
#

k ill try it

#

here is previous code
StartCoroutine(DeathPlayer("stumble_lower"));
how would I use that new cached coroutine tto use it like this
stumble_lower is an animation

north kiln
#

... literally the same way

sly wasp
#

ohh wait i think i get it

rich adder
#

you're just storing it in that object to be able to stop it later

violet topaz
north kiln
#

!code

eternal falconBOT
north kiln
#

Please link to large codeblocks

violet topaz
#

ok

ivory bobcat
robust condor
#

I have a script I want to have on all my NPCs, do I really need to add it to all prefabs? Imagine if I make a new script and have 200 prefabs I need to attach this script to

timber tide
#

1 prefab 200 SOs (or 1 prefab 0 SOs and 200 serializedReferences)

verbal dome
teal viper
#

Or what Mao suggested.

verbal dome
#

I believe theres even a way to make an existing prefab a variant of another?

teal viper
#

Ideally, you don't want to configure every single npc by hand. They should be generated at runtime from data.

robust condor
#

I tried to attach a script a game start to all tags "NPC" but it seems that is not supported when I googled

#

On spawn of the NPC I mean, instantiating

verbal dome
#

That's possible. But not ideal since the newly added NPC component will have default values

ivory bobcat
verbal dome
robust condor
#

How do I reference my other c# script?

ivory bobcat
#

Inspector field of the manager doing the instantiations

teal viper
#

You wouldn't need to reassign references if you have a "placeholder npc prefab" that has all the required references set. You just need to setup it's visuals, stats and whatever other data that is unique to the character.

robust condor
#

@ivory bobcatI can't drag my C# script into a SerializedField

verbal dome
#

Are you dragging in the script file itself? Drag the object that has the component instead

robust condor
#

So I need to have a gameobject in the scene just sitting there with the script attached?

verbal dome
#

I fell off the tracks, what is this other script?

ivory bobcat
#

Is it not serialized, not a reference type or?

robust condor
#

So I have my NPCManager, and NPCSpawner GO, they are two different scripts, in the NPCManager I have a Speech script, now it is a GO child of NPCManager and Speech is the only script on it. Then I want to add to every new spawned NPC by NPCSpawner so I can call .SayText()

sly wasp
robust condor
#

I was able to put the GO with my script as reference in the inspector, not a raw C# script itself

teal viper
#

If you just need to add a component to a gameObject, use AddComponent.

verbal dome
#

Script file I assume?

robust condor
#

From the Project folders

rich adder
#

like a monobehavior or a poco

verbal dome
#

Anyway, as dlich said you just need AddComponent with the correct type as parameter

rich maple
#

using UnityEngine;

public class SimpleFloating : MonoBehaviour
{
    public static bool animPos = true;
    public Vector3 posAmplitude = Vector3.one;
    public Vector3 posSpeed = Vector3.one;

    private Vector3 origPos;

    private float startAnimOffset;

    void Awake()
    {
        origPos = transform.position;

        startAnimOffset = Random.Range(0f, 540f);
    }

    void Update()
    {
        /* position */
        if (animPos)
        {
            Vector3 pos;
            pos.x = origPos.x + posAmplitude.x * Mathf.Sin(posSpeed.x * Time.time + startAnimOffset);
            pos.y = origPos.y + posAmplitude.y * Mathf.Sin(posSpeed.y * Time.time + startAnimOffset);
            pos.z = origPos.z + posAmplitude.z * Mathf.Sin(posSpeed.z * Time.time + startAnimOffset);
            transform.position = pos;
        }
    }
}

So, I have this code.. i reference this script in another script and whenever i want to pause game, i put animPos = false (because i dont want to pause some animations)... But whenever i resume game by making animPos = true the gameObject position is reset... How do i stop the resetting ?

robust condor
#

Okay now it added the component but the default values are broken, should I set them in the spawner script where I do addcomponent or can I use another gameobject for the settings, or should I use a SO?

robust condor
#

I need to reference a canvas and a tag

robust condor
#

Okay will try that then

verbal dome
#

SO assets or prefabs can't reference scene objects

#

The spawner script could hold the reference to the canvas, I guess

#

If it's a shared canvas and not instantiated for each NPC, that is

robust condor
#

Oh okay

#

Is it better to add an empty class to a GO just to reference it and find it by type or should I use the GO name?

rich adder
#

don't ever use strings like that

north kiln
#

Why do you want to reference it?

#

If you just want to use SetActive then referring to it via a GameObject reference is fine

#

never use names, but you can just refer to the object just fine

frigid sequoia
#

Maybe I am dumb, but why is my player capsule getting significantly slowed when in a moving platform?

rich adder
frigid sequoia
#

I have an script to parent the player to the platform when on top of it, so it keeps it on it and another one that moves the platform with transform.Translate

eternal needle
frigid sequoia
#

I literally just copy pasted that from a tutorial; it worked perfectly before XD

eternal needle
rich adder
#

true not for nothin many tutorials do use CC parented to platforms

eternal needle
#

beginner tutorials are mostly shit

#

most of them are copied off each other, doesnt matter the quality of the content. for youtubers it is a matter of publishing work first and screaming to be seen

rich adder
#

yeah kinematic rigidbody would be best bet prob

frigid sequoia
#

I changed the code of the parenting of the platform so it also works with some stuff that needs to be dragged around; but since it did some weird things with the scale; I had to change the whole hierarchy attaching all the scripts and the platform itself to an empty object with 1 as scale

#

I think is cause the player doesn't like to be moved with a translate from the parent and a AddForce from the player controller

#

Don't really know how to work around that

eternal needle
#

idk why that message link isnt shortening 🤔

frigid sequoia
#

Yeah, I read that, still now idea of how to do that

#

Vector are complex XD

eternal needle
verbal dome
#

You use CharacterController? Or rb?

verbal dome
eternal needle
frigid sequoia
#

The basic movement script is no more than rb.AddForce on the input vector; nothing more

#

I can share if you think it might help

rich adder
#

why not just make platform kinematic rigidbody ?

#

and use MovePosition

eternal needle
#

I think with addForce it might be a little more difficult because you arent directly in control of what the current movement vector should be. Like if you addForce once, it can technically just keep going forever.
You might have to change a lot to get proper platform movement

summer stump
eternal needle
#

What I do is just assign directly to the .velocity what the current movement should be, so this would be easy to add platform movement. A platform would just add to some vector on the player script. then in the player script it'd be as simple as
rb.velocity = movement + externalForces every frame

eternal needle
frigid sequoia
#

Could it work if I set the player velocity to be its own velocity + the vector of the moving platform translate though?

eternal needle
verbal dome
#

Could also do normal movement + rb.MovePosition with the platform's movement

frigid sequoia
#

So we just don't move players with addForce then?

timber tide
#

If I were to have projectiles that used rigidbodies for continuous collision checking, how would this this apply to objects using character controller movement?

minor vault
#

my console keeps spamming this error, can someone help me?

timber tide
#

^ try resetting the error otherwise sounds like maybe a material broke

timber tide
#

that requires precise testing :(

verbal dome
#

Maybe speculative is the best option here?

rich adder
#

Works well on netcode at least, idk how fast yours are tho

verbal dome
timber tide
#

I cant manage making my own interpolation checking it's just bad

#

was trying some raycasts and a spherecast but there's a lot more math to it I feel

#

and ive no clue how to sync that all up

rich adder
#

raycast backwards from back of bullet?

robust condor
#

So I have a trigger collider, when an NPC enters this collider I want to call a function on my NPC using Collider other.SayText("..:") but the trigger doesn't know of this function.Should I use events or should I check what type of entity enters the collider and search for my Speech script on other? Or perhaps the logic is best reversed, have the NPC do the SayText when it enters the collider?

verbal dome
#

Tunneling is the term for this if you didnt know @timber tide

#

Or anti-tunneling

#

If you wanna search for some resources

#

Should be engine agnostic

rich adder
timber tide
robust condor
#

@rich adderI have a SpeechHandler on my NPC, but if I have two different trigger colliders, how do I know which one it entered?

verbal dome
summer stump
rich adder
#

truth

timber tide
#

it's a special CC though for A* project that I've been appending upon

#

helps with avoidance than just bumping into crap

rich adder
#

they don't give you like the path / direction between each node?

robust condor
#

@summer stumpI have two prefabs, one is house and one is a mine with box collider trigger, NPC walks into one of them and it triggers the OnTriggerEnter script on the house. Should my trigger script use TryGetComponent<SpeechHandler> on the "other"?

summer stump
timber tide
summer stump
#

I was imagining you had multiple trigger colliders on one object

robust condor
#

I am also doing if (other.tag == "NPC") {

timber tide
#

it's interesting but it helps from enemies getting stuck together

summer stump
rich adder
robust condor
#

So best practices is to make the trigger say the NPC text, instead of the NPC itself?

rich adder
#

SpeechHandler should ideally only Get that text from the triggers

robust condor
#

if (other.TryGetComponent<SpeechHandler>(out SpeechHandler hit)) {
hit.SayText("I am relaxing at home!");
}

rich adder
#

No the npc just is a "client" of speech aka it only plays back the speech

#

grab the speech from the trigger

#

since they all vary by locations

north kiln
robust condor
#

Alright

rich adder
#

but you should store the text in a variable, so each trigger can contain different strings to grab

north kiln
#

With interfaces you can make it even more generic

rich adder
#

public class NPC : MonoBehaviour, ISpeechHandler { }

robust condor
#

I get Tag is not defined with CompareTag, despite it actually having a tag check I click on it in the scene... when I spawn the NPC gameObject.tag = "NPC"

north kiln
#

Is the tag defined in the tag manager?

robust condor
#

Yeah

north kiln
robust condor
#

Hehe oops 😄

minor vault
#

console keeps spamming this error when entering play mode, can someone help?

timber tide
#

I can only assume you've some material with unassigned / null properties on one of your gameobjects

#

maybe a texture

#

or rather the material reference is bad

north kiln
#

If restarting doesn't fix it, I would guess that if you're using a render pipeline, the asset/renderer is busted somehow.

#

There are a lot of warnings (disabled/hidden), presumably they would also help to figure it out

fringe plover
#

!code

eternal falconBOT
fringe plover
subtle canyon
manic zinc
#

i want to create character controller
so i should use character controller or rigidbody to move character?

subtle canyon
manic zinc
#

dani use rigidbody in muck
and i want to make a game like muck
so should i use rigidbody?

subtle canyon
timber tide
#

for the most part, rigidbody moveposition and other methods would be implemented similarly to how you just do general direct transformation movement but instead of delta time we'd use fixedDeltaTime, right? How about rotational methods like quaternion.rotatetowards/vector3.movetowards and similar methods?

fringe plover
verbal dome
#

Oh youre asking whether to use deltatime there?

subtle canyon
timber tide
manic zinc
eternal needle
verbal dome
#

Moverotation just sets the rotation while using interpolation

timber tide
#

I'm just trying to move a lot of projectile logic to RB to try out the collisional checking

nimble scaffold
#

By mistake I have done factory reset of my pc which has all unity projects so would I be able to backup them???

rich adder
#

hard lesson on !vc

#

!vc

eternal needle
eternal falconBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

nimble scaffold
verbal dome
rich adder
nimble scaffold
#

Today my crush also told me to use unity and my pc is full of trash so I done factory reset 😭😭

rich adder
#

are you sure files are deleted and just only apps refreshed

nimble scaffold
rich adder
#

did you check off to delete all files?

nimble scaffold
#

Ye

fringe plover
eternal needle
#

Hm does the memory still get cleared by a factory reset? maybe you can hire someone to go through and restore from your drive

timber tide
eternal needle
#

but if you're a very beginner and didnt have much, you might honestly just wanna start again. as you dont wanna fuck up ur computer and it might take time to do this

rich adder
#

tehcnically your files don't delete from HDD unless the space gets overwritten

verbal dome
nimble scaffold
rich adder
eternal needle
#

You would likely have to hire someone to go through it for you though

nimble scaffold
#

Ok

#

Ill restart

subtle canyon
#

@fringe plover So what you are basically trying to do is rotate the character in the direction of where we are going so if I press "A" for eg it should rotate left? Is that right?

robust condor
#

I gave a prefab with a rect transform, but the position of it gets reset everytime I instantiate the prefab as a child. Why does it not say at 0,2,0?

verbal dome
subtle canyon
fringe plover
verbal dome
#

@timber tide I raycast the projectile forward each FixedUpdate and have a visual object that is interpolated in Update

#

Not saying you have to do this - its just what I settled on

timber tide
#

What are the parameters of your raycast though? I can't seem to formulate mine to make sense for how long this raycast should be.

verbal dome
#

You set velocity to the shot direction when shooting ofc

subtle canyon
#

Wait let me refactor your code @fringe plover

verbal dome
#

@timber tide if projectile hits nothing after ray, move it to its current position + velocity

fringe plover
timber tide
verbal dome
nimble scaffold
#

So clean

subtle canyon
verbal dome
#

If your frames drop, the physics sim will still (try to) run as many times as needed to catch up @timber tide

fringe plover
#

illl make zip and send in dms

subtle canyon
timber tide
#

I would think update is more precise though if it's checking more than fixed, but perhaps my assumptions are wrong for how update is working with my transformation movements

verbal dome
#

Also remember... fixedupdate can run more than update if your frames are under 50

#

(At default setting)

timber tide
#

Yeah, I know but why does a lot of tutorials and even the documentations show a lot of general transformation movement without fixedupdate

#

there's very little reason to do it out of fixedupdate if you're dependent on collider information

verbal dome
eternal needle
#

I think fixedupdate makes more sense for this if you have rigidbody movement

verbal dome
#

For me it works like a charm

timber tide
#

it makes sense if you're using rigidbody methods, but even for collider checking

eternal needle
#

its still a physics function though, would it have up to date information if colliders move every frame?

verbal dome
#

I dont like it to be frame dependent so just ditch update

timber tide
#

if collider info is updated via physics updates then I guess I should just shift all my code over to it

verbal dome
nimble scaffold
#

Which is best hrurp or urp???

timber tide
#

because my very fast projectiles do eventually clip through walls and even with some determination through raycasts, any framedip makes it obsolete.

nimble scaffold
#

Okay I'll ask my crush

eternal needle
#

i pretty much just do this in fixed update. I think I might have to add a overlap check at the start because i realize this might have a rare case where it can miss

        bool didRayHit = Physics.Raycast(
            transform.position, direction, out RaycastHit hit, speed, damageableLayers);

        lengthTravelled += speed;
        transform.position += direction * speed;
verbal dome
#

Yeah thats my basic idea too

nimble scaffold
eternal needle
nimble scaffold
#

No no just asking

#

Next time I'll choose from urp or hdurp that's why

eternal needle
#

yes, so just ask in the right channel id:browse

nimble scaffold
#

But pls tell me

#

Is there much difference?

eternal needle
nimble scaffold
#

Whatt

#

Fine

eternal needle
# verbal dome Yeah thats my basic idea too

do you also overlap check? not entirely sure if i need to but my thought process is:
it may raycast, not see anything, moves the position
something else moves into that position at the same time
the start position is overlapping an enemy, so 3d raycast ignores the collider and it misses.

timber tide
#

I'll probably give kinematic w/ moveposition a try eventually, but for now I'll probably just shift it all over to fixedupdate

verbal dome
#

But I think I get what you mean, I need to do some testing

timber tide
#

even the forums there's a bunch of mixed opinions on the best way to handle this stuff

eternal needle
#

at high speeds i can imagine its a very rare bug if it does exist

verbal dome
#

Could be noticeable on moving targets from distance though

#

Might be solvable with execution order too

#

Move all players before moving projectiles?

eternal needle
robust condor
#

_RectTransform.anchoredPosition = new Vector3(0, 2, 0); does not set the Z to 0, it spawns at -900 something, what gives?

verbal dome
#

@eternal needle I could do a second raycast back to the previous projectile position at the end of fixedupdate 🤔

#

In case something moved there in the meantime

eternal needle
#

its probably not worth worrying about, if it happens then visually it'll probably look more like the projectile just missed the enemy. The enemy would have to move its entire collider worth of distance every fixed update, for it to be an actual noticeable issue

verbal dome
#

I think it would just make sniping moving targets etc. more forgiving (which I want in my case)

timber tide
#

If there was quite a radius to the projectile, I guess you'd sphere cast many times ahead or perhaps just use a few more raycasts to cover the area

#

hmm I think the raycasts would probably be more performative because otherwise I'm looking at 8-10 spherecast to cover the area hah

verbal dome
#

Spherecasts are a bit costly yeah

eternal needle
eternal needle
verbal dome
timber tide
#

yeah that makes sense

rich maple
#

what is the best way to pause a math function?

timber tide
#

wat

verbal dome
#

Dont cross post

robust condor
#

I have been trying to get tmp text to look at the cam for an hour now, but it is tilted:

#
private void LateUpdate()
    {
        transform.LookAt(_Camera.transform);
        transform.RotateAround(transform.position, transform.up, 180f);
    }
timber tide
#

I think there's a component that does that for you

eternal needle
robust condor
#

Because otherwise it is mirrored

eternal needle
#

then that is something you should fix in the inspector

timber tide
#

I don't really understand the rotating, shouldn't lookat suffice here?

robust condor
#

@eternal needleI instantiate it dynamically

eternal needle
#

yes LookAt alone should be fine, thats all i use for doing the same thing

eternal needle
robust condor
#

The prefab doesnt remember the pos

#

It is a child of another prefab

eternal needle
#

what does the position have to do with the rotation, your text is just backwards in the prefab

robust condor
#

The prefab rotation is 0 0 0

verbal dome
#

Is the script on the same object that has the text?

robust condor
#

I tried flipping all values

verbal dome
#

Oh thats a recttransform

#

Thats for UI

robust condor
#

TMP added it

verbal dome
#

Are you using the UI version of TMP?

robust condor
#

No

verbal dome
#

Theres a world space version too

eternal needle
#

I think this would have to be in world space yea

robust condor
verbal dome
#

Did you put it in a canvas?

#

Why would it give it a recttransform

robust condor
#

No it's on the character

verbal dome
#

Try removing the recttransform, it should have a normal transform

#

Right?

robust condor
#

That is all it adds by default

rare basin
#

I don't understand why do you have everything under one objct

verbal dome
#

Oh apparently it uses recttransform now okay

rare basin
#

rect transform + mesh renderer?

#

is it for the 3d text mesh?

eternal needle
# eternal needle I was thinking just still raycast but do an overlap sphere to check before if it...

@timber tide @verbal dome incase you were interested, i tested this on my navmesh agent running directly towards me. I think about 1/30 of the projectiles didnt hit without the overlap check. All of them seem to hit with the overlap check, but its somewhat awkward on what size to use (since raycasts dont have width). With overlap sphere and a radius of 0.1f, 1/5th of my projectiles were hitting through the overlap instead of the raycast.

robust condor
#

I can't remove the rect transform

robust condor
#

This is for 3D world space above characters head

verbal dome
timber tide
#

I'll probably fool around with a larger spherecast than needed and do some positional calculations to fine-tune some of the stuff.

eternal needle
#

i might change that first part so it checks if it moved more than 0.1f, which is the radius i used

verbal dome
#

Im a bit unsure still what problem the overlap solves

#

But Im also sleepy

#

So theres that

#

Maybe it'll click for me later today/tomorrow 😄

eternal needle
verbal dome
#

Oh yeah that totally makes sense

#

Now that you visualized it i get it

eternal needle
#

in the first part i meant it doesnt reach the enemy, not misses but i cant edit text in paint lol

verbal dome
#

Could also just use Physics.queriesHitBackfaces = true, right?

verbal dome
eternal needle
verbal dome
#

Gotta set it to false after because it is static yeah

#

No biggie

#

Thanks for pointing this out, I was thinking of something slightly different before

#

Didnt think of this edge case

eternal needle
#

np, i only thought about it because of your past conversation with mao, and was working on my ability system

royal ledge
#
mr.materials[2] = cardFront; // This line does nothing
Debug.Log(mr.materials[2]); //Returns same material as before

Anyone have any clue why this might not work? I can change material on the mesh in the inspector just fine, just can't manage to do it in runtime, can there be something wrong with the mesh? Import settings? Throws 0 errors btw

verbal dome
#

So you need to get it, then modify it and then assign it back

royal ledge
#

@verbal dome yuuup. Thank you

robust condor
#

If I want 1000 combinations of my character models, should I load all possible clothing, hair etc. in one prefab and then randomize the selections on spawn and hide the rest on every character spawned?

rare basin
#

each having 1000 combinations

#

each combination contains X different objects

#

result = milion object

vocal thorn
#

Can someone look over my Code? I feel like somethings wrong and I can't put my finger on it.

robust condor
#

@rare basinSo what to do, delete all the children that are not selected?

rare basin
#

spawn only the neccesary objects for instance

wild cargo
ivory bobcat
wild cargo
timber tide
wild cargo
vocal thorn
# ivory bobcat The more information, the better. Other than that, just ask/provide the question...

Sorry yeah. Basically, I'm making a small Whack-a-Mole game, the function is meant to be that once the player goes to the table they have to press E to Interact. So far so good, I feel like I'm processing the code completely wrong and having a form of Overflow because my Game crashes imediately after I press E. Something I'd like to mention is that I can't open my game anymore since I changed my Code slightly...

Game Object (1) is my Trigger and Box-Collider.

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

public class WhackaMoleStartUpdater : MonoBehaviour
{
    public GameObject otterTop;
    public GameObject otterMiddle;
    public GameObject otterBottom;

    public int counter = 0;
    
    void Start(){

        otterTop = transform.Find("topotter").gameObject;
        otterMiddle = transform.Find("middleotter").gameObject;
        otterBottom = transform.Find("lastotter").gameObject;
        if (otterTop != null && otterMiddle != null && otterBottom != null){
            if(otterTop.activeSelf || otterMiddle.activeSelf || otterBottom.activeSelf){
                otterTop.SetActive(false);
                otterMiddle.SetActive(false);
                otterBottom.SetActive(false);
            }
        }
    }

    public void WhackaMoleGameStart(){
        while(counter < 30){
            randomappearance(otterTop);
            randomappearance(otterMiddle);
            randomappearance(otterBottom);
            counter++;
        }
    }

    void randomappearance(GameObject otter){
        if(otter != null){
            otter.SetActive(false);
            
            var hInput = Input.GetAxis("Horizontal");
            var vInput = Input.GetAxis("Vertical");
            int xlocation = Random.Range(1,3);
            Vector3 newx = new Vector3(2.5f,hInput,vInput);

            System.Threading.Thread.Sleep(Random.Range(0,6)*1000);

            if(xlocation == 1){
                newx = new Vector3(0f,hInput,vInput);
            }
            else if(xlocation == 2){
                newx = new Vector3(-2f,hInput,vInput);
            }

            otter.transform.position = newx;
            otter.SetActive(true);
        }
    }
}

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

public class PopupScript : MonoBehaviour
{
    [SerializeField] private Image popupImage;
    public KeyCode interactKey;
    public UnityEvent interactAction;
    public bool range = false;
    public bool interacted = false;

    private void Start(){
        if (popupImage != null){
            popupImage.gameObject.SetActive(false);
            }
    }

    void Update(){
        if(range == true){
            if(Input.GetKeyDown(interactKey)){
                interactAction.Invoke();
                interacted = true;
            }
        }
    }

    private void OnTriggerEnter(Collider other){
        while(interacted == false){
            if (other.CompareTag("Player")){
                range = true;
                popupImage.gameObject.SetActive(true);
                print("Entered");
            }
        }
    }

    private void OnTriggerExit(Collider other){
        if (other.CompareTag("Player")){
            popupImage.gameObject.SetActive(false);
            print("Exited");
        }
    }
}
#

Okay... That was larger than expected sorry.

ivory bobcat
#

The first thing I see that throws a red flag is counter and the possibility that it doesn't reset in time before the next call to the function - have not checked the entire code yet.

keen dew
#

System.Threading.Thread.Sleep(Random.Range(0,6)*1000) <- this is called 90 times, it sleeps on average 3 seconds -> game freezes for 4-5 minutes

ivory bobcat
#

When does it crash? What's the pattern?

vocal thorn
vocal thorn
teal viper
#

Why would you freeze the main thread anyways😱

keen dew
#

Yes it is. 0-5 times 1000 ms = 0-5 seconds

vocal thorn
#

ah okay... what could i put instead?

#

I basically want it to wait until it changes x axis again

keen dew
#

Look up coroutines

vocal thorn
ivory bobcat
#

So what function is fired when you press e?

#

Are there any particular details?

#

So you've got to be targeting a valid creature?

#

What about on misses?

vocal thorn
#

When I press E, it sets up the Interact Action, and the Popupimage i have shouldn't be displayed anymore, plus my WhackaMoleGameStart() function should start

eternal needle
vocal thorn
timber tide
#

rather, you don't multiply by fixedeltatime (oh maybe you do outside of that snippet of script)

fluid kiln
#

Hey everyone! Quick question: I'm working on a game with skills that can have various traits like AOE, toggle, aura, instant, delayed, or lingering. I'm trying to figure out the best way to handle these aspects in the game's code without using traditional inheritance since a skill might have only one aspect at a time. Any suggestions or ideas on how to tackle this?

timber tide
#

so you're completely dependent on the timestep

ivory bobcat
eternal needle
ivory bobcat
#

If the problem goes away, you'll need to find an alternative for delaying other than sleeping the entire thread (likely the main thread at that)

vocal thorn
ivory bobcat
#

Maybe consider a coroutine or self implement a timer

vocal thorn
ivory bobcat
#

Did you save?

#

Were there any errors?

vocal thorn
ivory bobcat
#

If you didn't save, it'll be the last working compilation which would be the thread sleep version

timber tide
#

now I need to simulate my sudden fps drops just so I can test if my logic works perfectly

vocal thorn
#

the code or the game

ivory bobcat
#

The code, assuming you're testing this from the editor play session.

vocal thorn
#

im using VSC

#

its on auto-savwe

ivory bobcat
#

Alright, just making sure.

vocal thorn
#

dw

ivory bobcat
#

Try setting the counter to 30 before the while loop to avoid any random appearance and see if the problem persists - trying to isolate it to the random appearance function.

#
counter = 30;
while(counter < 30)
{
...
}```
vocal thorn
ivory bobcat
#

Unless you're positive the sleeping is what's causing the crash, it'll not help you much - although you'd definitely want to not sleep the main thread.

#

Doing too much isn't good. Focus on how to undo the crash aka what's causing the crash.

vocal thorn
#

does the EnterPlayMode not loading count as a crash?

ivory bobcat
#

No

gaunt ice
#

no, just freeze

#

crash means the editor killed by your os

vocal thorn
#

I can't quite do anything if I can't test it in play mode...

keen dew
#

You'll have to remove the thread.sleep everywhere you've used it. My guess is that you have it somewhere that runs at game start

vocal thorn
golden otter
ivory bobcat
golden otter
ivory bobcat
#

Disabling that function shouldn't have caused the game to not be launched

keen dew
#

Try restarting the editor/computer, using it has possibly locked a thread somewhere

vocal thorn
#

okay, I just reverted all my changes.

vocal thorn
keen dew
#

Yes, that's why restarting the computer might be a good idea

ivory bobcat
#

So without thread sleeping, it's still crashing?

golden otter
vocal thorn
gaunt ice
#

Using thread.sleep is not a good idea
It stuck the whole thread and you cant do anything no matter ui or playing
And you need !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ivory bobcat
ivory bobcat
#

If so, sleeping isn't the issue.

vocal thorn
ivory bobcat
#

The only other thing that's questionable would be the lines setting the otter to inactive/active

vocal thorn
#

No, I still can't run the game

ivory bobcat
#

You've got something else going on

vocal thorn
#

A forum says this, could this be it?

ivory bobcat
#

Assuming you're referring to the play button not working and not the e interact key

vocal thorn
ivory bobcat
vocal thorn
ivory bobcat
#

This isn't a programming problem anymore. Try #💻┃unity-talk and make sure to not use that sleep function.

vocal thorn
#

Okay, thank you.. I was actually in that channel before i came here

#

I probably should have done with from the beginning, but I reset the changes to code I made before it began, I'm going to try to load it up now

#

Okay, turns out: it was a coding error

#

I accidently built a forever loop

#

I can enter again

#

2nd Update: The game doesn't crash anymore, but my "otters" aren't showing up.

ivory bobcat
#

Post your updated !code and link it here

eternal falconBOT
vocal thorn
#

I think i have an idea as to why they're not showing up

#

could it be that my function in my other script isnt running?

ivory bobcat
#

Avoid guessing by placing logs

vocal thorn
#

I just did

#

the function does start

#

I have a rough idea of whats happening.

ivory bobcat
#

The wackamole game will start and immediately finish

tawdry mirage
#

if i want to make pseudo-ballistics, where projectile flies with constant speed and changes it's angle every fixedUpdate (until it's angle is vertical), i can calculate distance of straight line trajectory easily and then apply some multiplier to compensate for trajectory's curvature. If i know max distance at which projectile's trajectory will look like halff-circle, how to calculate this multiplier?

ivory bobcat
#

Whatever you've got going on after that while loop would be what's to occur thereafter.

ivory bobcat
vocal thorn
whole isle
#

any1 know how i can make it back to 2d

#

idk what i did

#

nvm

#

how do i get rid of that

ivory bobcat
whole isle
ivory bobcat
vocal thorn
#

I think i just found my issue