#💻┃code-beginner

1 messages · Page 110 of 1

rich adder
#

Link above has pretty much the guide through

golden otter
#

doesn't he want to set velocity to zero?

slender nymph
#

yes but that code you shared won't work for two reasons, the first being a compile error since rigidbody2d does not have an isKinematic property

slender nymph
#

where

sage mirage
#

Hey, guys! Is there a way to save my graphics quality settings on my game?

slender nymph
#

still though your code won't work for them

sage mirage
#

I know player prefs but only to use them for volume

native seal
#

So say im making an item system in my game, would it be better to use "composition over inheritance?" Thats what i'm seeing when I google it but I'm not entirely sure how that works. My idea is I have a base "Item" class (would I inherit this from MonoBehavior?) and then for example a Weapon : Item, and further Sword : Weapon, or Potion : Item. Is that the wrong way to go about it?

sage mirage
#

How?

rich adder
#

( make a struct/class for settings )

golden otter
rich adder
#

also it puts file wherever it feels like it and no consistent
so also hard to find if someone wants to maybe change setting pre-gaming

timber tide
rich adder
#

temp storage n such

native seal
timber tide
#

I'd start by deciding what the behaviors of each class should have. An example with Item is that I only need a target to Use() it so that itself applies to many different scenarios. Use(Entity target) would be a better idea of implementation if you want to say use the potion on something else, or perhaps that item was instead some type of misc item then in this case the Use(Entity target) would do nothing which isn't incorrect.

native seal
sage mirage
# rich adder JsonUtility

Hey! Can I use PlayerPrefs instead of JSonUtility you say because I don't know yet how to use that JsonUtility?

golden otter
rich adder
#

and just serialize that

timber tide
#

structuring stuff in discord stinks

#

Having a single type for many assets to derive is nice for stuff like Names, IDs, serialization

#

There's ways about just using interfaces too, but keeping it more centralize like this is a fine idea too.

eternal needle
sage mirage
rich adder
#

the File.WriteAlltext is what creates a file (better than playerprefs)

shrewd swift
#

hello
i cant find why i got 5 materials (first is "playerhit" and the 4 others are none) in my "Materials" list in the MeshRenderer when the followed code is executed

List<Material> materials = new List<Material>
        {
            hitMaterial
        };
        
        Debug.Log(materials.Count);
        _meshRenderer.SetMaterials(materials);

as you can see, the debug.Log is called only once and the list has only 1 item

any ideas ?

eternal needle
# golden otter is using PlayerPrefs for just storing a few values a bad practice?

Honestly I'd say it's bad practice, because it's not gonna be nice for the future version of you. Let's say you use playerprefs then suddenly want to store a whole class/struct and need to do json. Using both systems is just gonna be annoying. What if someone has an issue with their save file as well, how would they send you their playerprefs compared to a file in a predetermined location. If you want to sync settings across computers too (like if your game is on steam) then it's also a hassle

sage mirage
#

@rich adder You use inside this method with json utility and player prefs why?

rich adder
#

JsonUtility or if you get JSON.NET is what makes your data into a string (json formatted)

sage mirage
#

You say even better with File.WriteAllText(Application.persistentDataPath, stringData); so this is actually the same thing with the other you wrote but it is shorter or something?

rich adder
#

one creates the file with that data, and the other saves it to PlayerPrefs

sage mirage
#

So, for the second one we make a file right? For the first one what we make?

rich adder
#

PlayerPrefs.SetString("settingsData", stringData); ?

#

this saves it to whatever it is on OS. In windows it saved in Registry (which is not ideal)

sage mirage
#
public class SomeSettings
{
    public string xyz;
    public int someInt;
    public float someFloat;
}
public class Test : MonoBehaviour
{
    private void Method()
    {
        var someSettings = new SomeSettings()
        {
            xyz = "something",
            someInt = 69,
            someFloat = 666
        };
        var stringData = JsonUtility.ToJson(someSettings);
        PlayerPrefs.SetString("settingsData", stringData);
        //or even better
        File.WriteAllText(Application.persistentDataPath , stringData);
    }
}```
eternal needle
#

I think setting the json string in player prefs is especially bad. The docs say you arent supposed to use it for large strings

sage mirage
#

We have here the code you sent. I mean before the comment

eternal needle
#

And json can get quite large

rich adder
#

yea exactly why i avoid it lol for small jsons is ok

sage mirage
#

everything before the comment

rich adder
#

i think limit is 2kb

#

or whatever string limit is

rich adder
sage mirage
#

No, I just want to know you said the second one with the path makes a file but before that do we make something like a file?

rich adder
#

but its veryyy limited so should not used, hence why i said save to file exclusively

#

I'm just showing you it can be done w/ PlayerPrefs too

#

the benefit is creating a settings object instead of doing each setting SetString or SetInt or SetFloat

sage mirage
#

I am using right now player prefs, what do you think do i have to change everything in player prefs that I have made already and store everything to that new file with json you said?

rich adder
#

save the object

#

You can store them in the same object too

sage mirage
rich adder
sage mirage
#

Oh, ok!

rich adder
#

like volume float etc

safe carbon
#

!code

eternal falconBOT
safe carbon
#
void Update()

{
    if (Input.GetMouseButtonUp(0))
    {
        Vector3 mouseP = Input.mousePosition;
        //Debug.Log(mouseP.x + " " + mouseP.y);

        Ray ray = Camera.main.ScreenPointToRay(mouseP);
        RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);



        if (hit.collider != null)
        {

            Vector2 direction = (hit.collider.transform.position - transform.position);
                //Camera.main.ScreenToWorldPoint(mouseP) - transform.position;
           

            transform.up = direction;

            rb.velocity = direction;



            void OnCollisionEnter2D(Collision2D coll)
            {
                Debug.Log(coll.collider.name);

            }

            Debug.Log("CLICKED " + hit.collider.name);


        }



    }


}
#

it says Oncollisionenter2d is declared but never used

polar acorn
safe carbon
#

the oncollision being inside the update?

slender nymph
#

yes, don't do that

safe carbon
#

oh ok ig i could probably do all i need outside of the update with collision

thorn holly
#

Say I have this prefab, and that prefab has a script, and in another script I instantiate the prefab want to modify something in the prefabs script. How would I do that?

eternal needle
wintry quarry
thorn holly
#

Makes sense, thx

summer stump
safe carbon
#

good to know

summer stump
safe carbon
#

ic

timber tide
#

wait what the compiler doesn't tell you off for that

summer stump
timber tide
#

interesting

summer stump
#

Local functions are able to be made

rich adder
swift crag
#

They are not members, and can't be accessed given an instance of the class/struct/whatever their enclosing method is contained in

safe carbon
#

so if u try calling the local function in a different class while using the class it is in

#

it just wont work?

swift crag
#

you can't "try"

#

it does not exist

safe carbon
#

lol

swift crag
#

access modifiers are for members

safe carbon
#

i dont really know what access modifiers are but i get the point ur making

swift crag
#

public, private, protected, etc.

eternal needle
tiny hawk
#

How do you guys get notifications about pushing to Unity Versioning Control system?

#

Is there a way I can send the nofification to a Discord channel and email?

safe carbon
#

also not a coding question but the way i am tryna learn unity rn is trying to make my own game and learn things i need to complete it instead of just watching bunch of tutorials u think its good way of learning.

summer stump
eternal falconBOT
#

:teacher: Unity Learn ↗

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

summer stump
#

Others may have other opinions on the best resource, but I doubt anyone is gonna say winging it is best

rich adder
safe carbon
#

i mean i already know basics of coding i learned python and ik syntax of c# mostly just unity functions and game engine tools

#

are things i need to learn

summer stump
rich adder
#

learning how to read an API is also part of learning c#

safe carbon
#

ic so then should i occasional make simple games with knowledge i gained then. I know that there is like a lot of things to learn in unity and it could feel endless

rich adder
#

simple games is good

#

doesn't need to be complete game either, just learn something then practice it

timber tide
#

it can be pretty endless but the reason we're using the engine is so we don't need to develop every single thing, otherwise you'd be spending 99% of your time building your own renderer support ;)

safe carbon
#

valid

timber tide
#

if you got the money you can pretty much build your game from the ground up using the unity asset store

#

but there's no fun in that

polar acorn
#

And if you don't have the money you can probably still do it anyway

rich adder
summer stump
safe carbon
timber tide
#

just knowing the concepts cuts down a lot of time learning the APIs

#

but of course you run into dreaded reflection that unity like to use then it's back to the docs

safe carbon
meager gust
safe carbon
#

time and money

delicate venture
#

Hey guys, so i´ve been having this problem and cant figure it out, i was wondering if someone could help me, so i have this code the DialogueTrigger, that is suppose to well, trigger the dialogue
everything is set up properly but when i enter the play mode even when im triggering the collider of the npc, the json file and the text bubble dont show up
the ui is created but not setup yet because im just testing
appreciate any help

queen adder
#

Is it a 2D game?

slender nymph
eternal falconBOT
delicate venture
stuck palm
#

why is the cube detecting the player so far away from the collider?

rich adder
stuck palm
# rich adder 🤷‍♂️ need to see code
 private void Update()
    {
        maxPlayer = pim.playerCount;
        Collider[] colliders = Physics.OverlapBox(transform.position, transform.localScale, Quaternion.identity, _layerMask);
        playersInZone = colliders.Length;
        
    }
rich adder
stuck palm
rich adder
#

btw it should be /2

#

transform.localScale/2

stuck palm
rich adder
#

yeah gizmos needs to be full sized not /2

#

wait which one is gizmo

rich adder
stuck palm
rich adder
#

the ide is also suggesting it, its an optimization benefit

stuck palm
rich adder
hoary karma
#

is there a way to trigger something only for one frame?

rich adder
stuck palm
hoary karma
#

like triggering something only for one frame in the update method

polar acorn
rich adder
summer stump
hoary karma
polar acorn
summer stump
#

As digi said, it's just way cleaner

rich adder
# stuck palm yeah but like what does that differ from alloc
private Collider[] playerCols = new  Collider[5] ; //maxPlayers to start with- it autofills if there are more.
private void Method()
{
    var hits = Physics.OverlapBoxNonAlloc(transform.position, transform.localScale / 2, playerCols);
    for (int i = 0; i < hits; i++)
    {
        var playerCol = playerCols[i];
        Debug.Log(playerCol.name);
    }
}```
polar acorn
#

It's a whole lot easier to think "Thing happened, call function" than "Thing happened, set boolean, run update, check boolean, run function, unset boolean"

hoary karma
#

got it, thanks!

stuck palm
#

array i mean

rich adder
stuck palm
rich adder
#

yea that is the min amount of the array

stuck palm
#

okay, thank you!

#

it works

rich adder
#
 private Collider[] playerCols = new Collider[5]; 
 private int GetPlayersCount()
 {
     return Physics.OverlapBoxNonAlloc(transform.position, transform.localScale / 2, playerCols);
 }``` 😮
stuck palm
#

could be good

#

idk if its necessary to make it a method, though

rich adder
#

yeah its just aesthetic

hoary karma
#

should i ignore this or no?

polar acorn
hoary karma
#

nope

polar acorn
#

The IDE seems to have just lost a reference to some DLLs in the project

hoary karma
#

thanks

stiff stump
#

quick question about interfaces
var savables = FindObjectsOfType<MonoBehaviour>().OfType<ISavable>();
im trying to get every gameobject with the ISavable interface but
my interface simplely looks like this

public interface ISavable<T>
{
    public void Save();
    public void Load(T data);
}

but i need in that OfType method the ISavable requires 1 argument and im not sure what to put to get all ISavables regardless of T

rich adder
#

object?

stiff stump
stuck palm
#

is scene not a serialisable field?

eternal needle
rich adder
eternal needle
#

SceneAsset is, in the editor

eternal needle
stuck palm
#

for a DDOL object, how can i run something that happens every scene change? is there a way to do that? like a start but

#

not start

rich adder
#

you'd probably answer your question :p

rich adder
stuck palm
#

would that be a good alternative to the start?

woven crater
#

should i use scriptable object to store different kind of enemies?

rich adder
#

if you mean their different stats yeah sure

woven crater
#

work with sprite too?

#

and maybe some have different method on movement and attack

frosty hound
#

Sure

woven crater
stuck palm
#

is the return going to exit the entire method?

rich adder
rich adder
#

SO and prefabs can go hand in hand

woven crater
#

Neat. Thank

stuck palm
#

im getting an NRE once in update and then never again. why is this?

swift crag
#

we can rarely tell you what's wrong without seeing the code, yes.

#

probably a timing issue where another component assigns a value in its own Update method

#

(or in its Start method after getting instantiated on the first frame)

stuck palm
#

highlighted line is the error

swift crag
#

pim is null.

stuck palm
#

yeah i now pim is null but like

#

it happens once

#

and then never again

#

so pim is set after that frame

swift crag
#

well, then it's clearly being assigned later

#

or the object/component is being destroyed or deactivated or disabled

hoary karma
#

is there any way i can check if a gameobject has been destroyed ?

swift crag
#

sure. if you have a reference to the object, obj == null will be true

#

also, if (obj) will fail; obj will implicitly convert to false

#

(This is true for any unity object)

swift crag
#

i might be able to answer your question with that

stuck palm
# swift crag share the rest of the script
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;

public class LoadZone : MonoBehaviour
{
    public string scenetoLoad;
    public BoxCollider bc;
    private TextMeshPro text;
    private PlayerInputManager pim;
    private int progress;

    public int Progress
    {
        get => progress;
        set => progress = Mathf.Clamp(value, 0, 120);
    }
    private MeshRenderer mr;
    public Material unready;
    public Material ready;
    public int maxPlayer;
    public int playersInZone;
    public LayerMask _layerMask;
    private Collider[] results = new Collider[4];

    private void Start()
    {
        Progress = 0;
        mr = GetComponent<MeshRenderer>();
        text = GetComponent<TextMeshPro>();
        pim = FindObjectOfType<PlayerInputManager>();
        bc = GetComponent<BoxCollider>();
    }

    private void FixedUpdate()
    {
        if (maxPlayer == 0) {return;}   
        if (playersInZone == maxPlayer)
        {
            Progress++;
        }
        else
        {
            Progress--;
        }

        if (Progress == 120)
        {
            SceneManager.LoadScene(scenetoLoad);
        }
    }

    private void Update()
    {
        maxPlayer = pim.playerCount;
        var size = Physics.OverlapBoxNonAlloc(transform.position, transform.localScale/2, results, Quaternion.identity, _layerMask);
        playersInZone = size;
        mr.material = playersInZone == maxPlayer ? ready : unready;
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireCube(transform.position, transform.localScale);
    }
    
}
swift crag
#

remember that large scripts should go in a !code paste site

eternal falconBOT
verbal dome
#

Side note, use proper names instead of obscure abbreviations everywhere

swift crag
#

one thing...do you have Collapse enabled in the console?

#

oh, no, it is just a single error

#

I'd make sure the LoadZone component isn't being disabled by something else.

novel sorrel
#

in my game every time i click i generate a new ball and i want to be able to reference each ball individually in the script

#

what's the best way to do this?

slender nymph
#

add them to a list when you instantiate them

novel sorrel
#

i'll try that tyty!

queen adder
#

transform.rotation = Quaternion.Lerp(initial_rotation, target_rotation, progress);can i nudge a quaternion a little at random z-euler so the spinning effect of this go randomly cw or ccw?

#

oh

ivory bobcat
queen adder
#

will negative quaternion make it look behind?

#

or should i negative identity?

ivory bobcat
#

I'm not sure what you're saying but it's simply the rotation

#

Quaternion is just the data type

queen adder
#

quat * -identity

#

actually imma just experiment hehe

ivory bobcat
#

I'm still not sure what you're asking. You'd need to rotate 180 in one or more Euler axis to invert an axis.

teal viper
#

I don't think that works like that. Quaternions are not Euler angles. Negating them would probably lead to unexpected results.

queen adder
#

isnt identity special?

verbal dome
#

There's Quaternion.Inverse(..) but I have no clue how that would work with Quaternion.identity

teal viper
verbal dome
#

You could just multiply it with a Quaternion.AngleAxis or Quaternion.Euler with a very small value

#

Or just use your own floats as axis angles from the beginning

#

And work with those floats

teal viper
#

If I understand quaternions correctly, negating it, would actually result in the same rotation.

ivory bobcat
#

If your goal is to invert the direction, just do a * b where b is Euler(180, 180, 180) or lookup a built in function, if any.

unreal imp
#

Guys, how can I detect when an object has a certain material?

nimble apex
#

i have issues on referencing universial cam data, its URP stuff right?

i converted the project to URP , but still cant refer to that

tough lagoon
nimble apex
#

lol damn

#

i can now , ty

tough lagoon
#

Or go the other way (more performant) and whenever you change the material, send an event or tell the script that cares about it

queen adder
#

actually, realized my q.lerp wont work as i want lol

lavish terrace
#
if (lootSystemScript.ItemID[Reward.ItemId] == false && lootSystemScript.ItemID[0])
#

how do i do the != 0 on the right side

#

like i need everything but 0

summer stump
#

Literally just put that before the last parenthesis

lavish terrace
timber tide
#

not inside

#

that's your indexer

summer stump
#

See how that is in the square bracket?

#

And I said parenthesis?

lavish terrace
#

i know u dont need to say it out loud

summer stump
#

Maybe use variable and just set it to not zero

And no, you still need an indexer

timber tide
#

you probably want to get an idea why you've a 0 in those brackets in the first place

summer stump
#

Are you trying to loop an array?

lavish terrace
#

a dictionary

#

its new to me so

#
void Rewarding()
    {
        RewardUI.SetActive(true);

        int RewardNum = 0;
        foreach (RewardScriptableObjects Reward in Rewards)
        {
            int GoldAmount = Random.Range(MinGold, MaxGold);
            
            if (lootSystemScript.ItemID[Reward.ItemId] == false && lootSystemScript.ItemID[0])
            {
                int RewardRNG = Random.Range(1, 101);

                Debug.Log(RewardRNG);

                if (Rewards[RewardNum].RNG >= RewardRNG)
                {
                    lootSystemScript.ItemID[Reward.ItemId] = true;
                    AfterRewardsUI[RewardNum].ItemImage.sprite = Rewards[RewardNum].RewardIcon;

                    if (Rewards[RewardNum].Countable == false)
                    {
                        AfterRewardsUI[RewardNum].ItemQuantity.text = "";
                    }

                    RewardNum += 1;
                }
                else
                {
                    AfterRewardsUI[RewardNum].ItemImage.sprite = GoldSprite;
                    AfterRewardsUI[RewardNum].ItemQuantity.text = "+ " + GoldAmount;
                    RewardNum += 1;
                }

                Debug.Log(Reward.DisplayName + "/" + lootSystemScript.ItemID[Reward.ItemId]);
            }
            else if (lootSystemScript.ItemID[Reward.ItemId] == true)
            {

                AfterRewardsUI[RewardNum].ItemImage.sprite = GoldSprite;
                AfterRewardsUI[RewardNum].ItemQuantity.text = "+ " + GoldAmount;
            }
            else if(lootSystemScript.ItemID[0])
            {
                AfterRewardsUI[RewardNum].ItemImage.sprite = GoldSprite;
                AfterRewardsUI[RewardNum].ItemQuantity.text = "+ " + GoldAmount;
            }
        }

        Rewarded = true;
    }
#

its still under construction so

#

there is probably a better way than this if nesting

#

i think imma rewrite the whole thing

timber tide
#

what is your key, value, and the idea for this dictionary

lavish terrace
#

int itemid, bool obtained

#

where itemid is the itemid and obtained is it obtained so it get switched to gold

#

while having gold with itemid 0

timber tide
#

so a quest progression/reward dictionary?

lavish terrace
#

ye

#

reward dictionary

summer stump
#

Instead of a foreach loop, I would do a for loop and start the index at 1

#

So you just skip over the 0 itemId. No need to check

lavish terrace
#

the thing is i have my rewards as a list

#

and im going for a public script so it is used for all types of bosses thats why

summer stump
#

@lavish terrace Yeah sorry, misread. I see that the foreach is for something else.
I'm not quite sure what you want.
You want to iterate the dictionary and skip itemId 0?

if (Reward.ItemId != 0 && lootSystemScript.ItemID[Reward.ItemId] == false)
uneven path
#

Hi hii does anyone know any tutorials on like how to make a button do different things for every click?

#

Since I'm trying to do a thing where click once, image appears in one location on the screen, click again a different image appears on a different part on the screen, though the previous image is still there.

summer stump
#

Oh, for that, you could just iterate a list of positions

#

That would probably be easier

lavish terrace
uneven path
summer stump
# uneven path Hmm not sure what you mean by that. But I'll try something

Ah, kinda misread your most recent message. I thought you meant one image in multiple places. But each one is unique
You could do a list of structs or Scriptable Objects, and then have an int called currentClickIndex and when you click it gets the struct or SO at that index and increases the index by one
The struct or SO would hold an image and a position, and probably that would be it

uneven path
#

I was thinking maybe they could all be hidden for their initial animation then after clicking they like fade in

#

Sort of thing

summer stump
unreal imp
unreal imp
#

thanka

#

you earn a friend (nah just kidding)

novel sorrel
#

can 3d colliders interact with 2d colliders?

wintry quarry
novel sorrel
#

is there a way to rotate a 2d box collider on the z axis?

#

i tried making it a child of another game object and rotating that but it still bugs the box collider

#

and makes it fail to generate

unreal imp
#

one last thing for today: how i can modify the speed of play of an audio clip through script? using AudioSource.PlayClipAtPoint()?

wintry quarry
novel sorrel
#

sorry i meant x axis

wintry quarry
#

no

#

2d colliders only exist on the x/y plane

#

and can only rotate on the z axis

novel sorrel
uneven path
# summer stump Ok, that works too. Then just same thing, but list of the instances existing in ...

Hii sorry for the delay was trying to figure out how to write it but is it something like this?

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

public class AdvanceButton : MonoBehavior 
{

    int i;
     
    public Animation FadeIn;
    public GameObject Image1;
    public GameObject Image2;
    public GameObject Image3;
     
    i = 1;

    public void OnClick() 
    {
        Image[i],GetComponent<Animator>().Play(FadeIn);
        i = i + 1
    }

}
wintry quarry
#

not 3 separate variables

uneven path
#

Ahhh an array

#

Unsure how to use that

#

🥹

summer stump
#

GameObject[]

summer stump
#

Or List<GameObject> if you want to add and remove things dynamically

uneven path
wintry quarry
summer stump
#
public class AdvanceButton : MonoBehavior 
{
    int currentIndex = 0;
    public Animation FadeIn;
    public Animator[] images;

    public void OnClick() 
    {
        images[currentIndex++].Play(FadeIn);
    }
}

I would consider something like this, trying to stick with what you have.

You would have to keep the order specific to know which you are getting

uneven path
wintry quarry
#

not sure what you mean by "put in the script thing"

uneven path
wintry quarry
#

the names are irrelevant

#

you need to use an array, as mentioned

uneven path
summer stump
#

It will make sense once you see that

uneven path
#

Hmmm an array in a script

uneven path
#

Alright I'll try it out

#

I'll probably come back tomorrow tho I realize now it is 4am

#

Ahhhhhh

#

🥲

summer stump
#

I recommend the course navarone posted btw.
It's gonna kill ya if you just try to force your way through without learning c# basics (which an array is)

uneven path
#

Thanks again btw

uneven path
#

It's been like a couple of years since I last used c#

#

Oh this one feels like it would be useful I should sleep tho ahhh
https://youtu.be/UQ7FjIwbJsA?si=PWhv9uHBAEuptfyy

In this video, I will show you a simple way to Switch UI Image Array with button in unity

In this video, we create an easy Script that will Switch your UI image every time by clicking on Next or Previous button. Step by step, you are going to learn How to change image from array with button in your unity game. Also, you will learn the feature o...

▶ Play video
patent compass
#

Hello, why am i getting this conversion error.

timber tide
#

Probably want to fix the Vector2 error up there first

queen adder
#

how to make a library that is accessible to all my projects? so that when i edit the codes inside, all projects are affected?

static cedar
# patent compass Hello, why am i getting this conversion error.

That means that Unity didn't add a way to cast Vector2Int to Vector3.
U can do Vector2Int > Vector2 > Vector3 but i'd just do new Vector3(powerUpPosition.x, powerUpPosition.y, 0).

Also u have an error above. You're trying to make a Vector2, not a Vector2Int and you didn't do any explicit casting so the variable that's meant to recieve it isn't compatible.

static cedar
subtle canyon
static cedar
#

How did u react with two emotes so quickly. UnityChanPanicWork

subtle canyon
#

Well but you would still need to import that library into every single project

#

but if you have git then then you import the library as a submodule so whenever you make any changes to the library you can save them in the git repo and that way the library would be in sync with all your other projects.

subtle canyon
queen adder
#

that's great, lemme try

sly wasp
#

Thank you, this helped me actually.

#

I fixed it

split dragon
#

Hi. How do I activate an action via if through movement? If the player moves, an action is triggered. I tried to do it through transform.position and nothing worked. How to do it right?

weak talon
#
        if (checkGroundTile == waterGround && checkCropTile != carrotCrop1)
        {
            StartCoroutine(WaterFade());
        }
    }
    IEnumerator WaterFade()
    {
        yield return new WaitForSeconds(5);
        if (checkGroundTile == waterGround && checkCropTile != carrotCrop1)
        {
            groundTileMap.SetTile(position, tilledGround);
            Debug.Log("Water Deleted");
            yield break;
        }
    }

why isnt this working, i am trying to make it if the tile is water and there is no crop on top then change the water tile to ground tile, but when it happens it doesnt let me water the tile again and keeps debugging "water deleted"

teal viper
teal viper
static cedar
weak talon
#

fixed it, the function got called lots of times because it was in void update so i just made a bool that made it only happen once

minor vault
#

can someone help me fix this error? i can't enter playmode because of it

teal viper
timber tide
#

surprised you've got 1000+ lines of code in that script before encountering that error

#

I'd say post the script if you need help, but try to chop it down a bit. You sure you've got the references on the editor correctly as well?

static cedar
#

If that script ever contains tons of classes, better split them apart to multiple files.

#

If it is just one class and ur method is just a massive if statements that stretch far and wide that pretty much does everything, i'd like you to reconsider it and use more classes.

hoary karma
#

is there a way to store information about a scene? like for example i'm trying to create a checkpoint here. but i don't only want to respawn the player, i also want to respawn the enemies that i've killed. so how can i store some information about enemies that i've killed previously etc

timber tide
#

make a script to store it to

#

Consider a gamemanager script if there's only one of these scripts you need to update

late kite
#

anybody able to help me out

#

i have a code that picks up an onject based on user interaaction

#

and i want to make it so the player can use the scrollwheel to vary the distance that the object is away from them

#

im thinking using a raycast and setting that as the axis the object slides along that way the user can rotate the camera and still have the object move according to their pov

abstract finch
#

Is there a way to make RandomUnitInsideSphere have a minimum value or is it better to just do random range for each parameter in a Vectro3?

timber tide
#

I remember reading that the random point isn't quite random anyway

silver heron
#

guys do you now how to fix that problem? I already installed .NET SDK and reinstalled vsc

abstract finch
abstract finch
eternal needle
timber tide
#

it's specific to that method

#

was a large forum post on it

eternal needle
eternal needle
timber tide
#

can't find the one im referencing but that seems related

north kiln
#

Instead of x and y being generated using the angle, you can use UnityEngine.Random.onUnitSphere and scale it by r

#

@abstract finch

robust condor
#

I have an NPC spawner, when it spawns NPC I add a child prefab to it with a component on it, but that component itself needs a prefab reference, which will be empty on creation. How can I tell this component what the reference is? I can have a reference to the prefab on the spawner itself, but then need a way to pass this info down to my component. So: NPC Spawner > Instantiate Prefab 1 > Instantiate Prefab 2 as child for Prefab 1 with component that needs the reference to Prefab 3

timber tide
#

how about clarifying what you're trying to do instead of the implementation

#

are you just trying to set data such that these are different types of enemies

near cargo
#

I am trying to clone a template for an UI. the template looks like this, it has the scale set to 1,1,1

#

but all of my clones have some weird number as their scale

#
            var newGameObject = Instantiate(carouselTemplateCard);
            newGameObject.SetActive(true);

            newGameObject.transform.SetParent(GamemodeCarousel.transform);
            listsGameObjectCards.Add(newGameObject);
#

this is how i create these objects

queen adder
#

I tried to build and run ( android ) but it shows me that error

languid spire
languid spire
near cargo
queen adder
languid spire
near cargo
# near cargo

@languid spire could the horizontal layout group cause the issue?

languid spire
near cargo
#

the horizontal layout group is in a vertical layout group

#

but that shouldnt affect i guess?

#

i put the horizontal group in a separate game object and it still behaves the same

#

this is my template (set to active) compared to the clones

#

i also tried setting the localscale of my recttransform using code and that didnt work

#

for some reason it doesnt update the scale unless i set it manually during play in the editor

#
            newGameObject.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
timber tide
#

Do you have it anchored correctly because it may be resizing

near cargo
#

this is how i tried doing it

#

my template is anchored yes

languid spire
#

If you look at the width and height of the cloned object you will see that they have changed from the prefab and the scale has been altered to compensate

#

so it is the Horizontal Layout Group that is doing this

near cargo
#

actually its not anchored

#

because otherwise the horizontal layout group wont do its just properly

#

@languid spire actually i dont know why but now they are the same width and height

languid spire
#

you've changed the template?

near cargo
#

i messed around with the anchor when you mentioned but it changed back because of the layout group

#

and then restarted

#

but other than that no

languid spire
#

so how come Template is now controlled by a Horiz LayoutGroup?

near cargo
#

ah seems like when its disabled it doesnt show that message

#

but the moment you enable it the message appears

#

but it doesnt matter if its enabled or not, the clones are still scaled up

languid spire
#

yes, so the HLG is reducing the size and increasing the scale

near cargo
#

but why?

#

they're clearly out of the container

languid spire
#

don't know

near cargo
#

okay so i made another for loop and set their scale AFTER i have created all of the cards

#

and it seems to work fine now

queen adder
#

im trying to write a dps calculation method and heres what i came up with cs newDmg += damageDealt / fps; count += dt; //deltatime if (count >= 1.0) { double dps = (newDmg - oldDmg); Debug.Log(dps.ToString() + $", {newDmg} - {oldDmg}"); oldDmg = newDmg; newDmg = count = 0; } it works when the fps stays constant but otherwise is wildly inaccurate is there a goto method for calulation

#

new damage is the damage this frame and oldDmg is from last frame

gaunt ice
#

why the damageDealt is divided by fps? if your fps is wrong then whole thing go wrong
shouldnt it be sum of all damage dealt in previous one second?

timber tide
#

wait why are you doing damage by frame rate

#

next level formulation

queen adder
#

oops

static cedar
gaunt ice
#

i think he is try to split damage across the frames

#

then calculate dps back?

near cargo
#
        var i = 0;
        foreach (Gamemode gm in gms)
        {
            var newGameObject = Instantiate(carouselTemplateCard);
            newGameObject.SetActive(true);

            newGameObject.transform.Find("GameModeTitle").GetComponent<FlexibleUIText>().SetText(gm.name);
            newGameObject.transform.Find("ClickButton").GetComponent<FlexibleUIButton>().onClick.AddListener(delegate {
                Debug.Log(i);
            });

            newGameObject.transform.SetParent(GamemodeCarousel.transform);
            listsGameObjectCards.Add(newGameObject);
            i++;
        }

in this case, how would i make it every time i click a card a different i would get printed?

gaunt ice
#

copy the i to local variable
or change the FlexibleUIButton script you already have

in your FlexibleUIButton script:
public int i; <--set this i when iteration
public void OnPress(){<-- add listener
  Debug.log(i);
}
near cargo
#

i tried copying the i to a local variable

#
            newGameObject.transform.Find("ClickButton").GetComponent<FlexibleUIButton>().onClick.AddListener(delegate {
                var ci = i;
                Debug.Log(ci);
            });
#

this didnt work

#

its still the same i

eternal needle
north kiln
#

Declare a new variable in the loop

#

And assign and use that, instead of the one outside the loop

near cargo
bitter oar
#

Hey! I could use some help! I'm trying to do a long jump (like super mario 64 or odyssey). Physics-wise, i'm using a rigidbody on my player with interpolate and continuous collision detection, i have also unchecked 'use gravity'. This is my 'Locomotion script'

https://hastebin.com/share/ayewebuhob.java

what happens so far when i longjump is in this video i sent, i kind of understand the first outcome, but all the ones after it i really don't.
Thanks!

golden otter
#

and then send the link

bitter oar
#

whats pastebin?

golden otter
#

its a website where you can post large blocks of code

bitter oar
spiral oak
#

Is Invoke less efficient than a coroutine with a WaitForSeconds?

old gorge
#

Hi
I want a script to expose a UnityEvent that gets invoked with a parameter from the script exposing it.
I then want to subscribe other objects methods to it using the inspector.

public class Subject : Monobehaviour {
  [SerializeField] private UnityEvent<int> _onTriggered;

  private void Update() {
    // ...
    if (someCondition) _onTriggered?.Invoke(12);
  }
}

public class Subscriber : Monobehaviour {
  public void HandleTrigger(int value) {
    // do stuff
  }
}

However, when I plug Subscriber.HandleTrigger(int) to the event in the inspector, it forces me to set a value to be used as a parameter (defaults to 0). This means that the value 12 that I invoke the event with from code is overriden by the value 0 from the inspector.

Is there a way to setup an event that enables me to plug in a bunch of subscribers (all accepting the same type of parameter) while letting the Invoke() call passing the actual value instead of using the one from the inspector ?

old gorge
#

i will look into that thanks

old gorge
lethal kestrel
#

simplest way of getting a certain text layer inside of a canvas to instantiate?

#

e.g getting itemName

raven kindle
#

Having a problem with lots of coins spawning in my game, when i have this update:

#

My max coins is set to 1, and activecoins.count is 1000s+

#

and it keeps spawning new ones

gaunt ice
#

do you see the second line?

#

the line under method name

tulip stag
#

Can anyone explain this line to me? I'm newish to C# i never seen these symbols
emptyLineCount = string.IsNullOrWhiteSpace(line) ? emptyLineCount + 1 : 0;
? and :

gaunt ice
#

X=A?B:C is equivalent to
if(A)
X=B
else
X=C

#

called ternary operator, shorthand for typing if else

tulip stag
#

Oh.

Hmmmm a bit confusing but I guess it makes sense!
Would you recommend I switch that to a simple if/else to make my code more readable to me?

static cedar
#

If the operator's a bit too confusing, better just use if else.

static cedar
#

You also have switch returns.

tulip stag
#
            StringBuilder lyricsBuilder = new StringBuilder();
            string line;
            int emptyLineCount = 0;
            while (emptyLineCount < 2 && !string.IsNullOrWhiteSpace(line = Console.ReadLine()))
            {
                lyricsBuilder.AppendLine(line);
                emptyLineCount = string.IsNullOrWhiteSpace(line) ? emptyLineCount + 1 : 0;
            }
            newSong.lyrics = lyricsBuilder.ToString();```

This is what the codeblock looks like
static cedar
tulip stag
#

(it says console because I'm still gonna bring the code to a unity project I have, I'm just testing out to see if it works as a console app first)

neon fractal
gaunt ice
#

have you logged the value?
is the rectDmgScreen rect transform?

neon fractal
#

first X - second Y, but Y always ~50

gaunt ice
#

the floating texts will rise up, are there anything control their y position?

neon fractal
neon ivy
#

I have this system I made after hearing about it on a GDC talk about an alternative way of doing quests which they called the encounter system.
basically an encounter has an ID string like "IntroductionNPC1" and a list of ID strings for what state that encounter is in like "HeardOfNPC1" , "SeenNPC1" , "MetNPC1". the player would store the most up-to-date state ID string and that ID would indicate that the previous states have occurred as well.
though in the GDC talk this was a completely linear system (encounter just has state 1 - 2 - 3 - 4 - etc.) but I'm trying to think of a way to expand on this.
a branching structure should still work but I'm getting lost when I try to merge them back, at that point the ID won't indicate what branch was taken to get there. does anyone have any idea on how to best handle this using the least amount of data?
I was also wondering if there's a way to have these strings behave like enums (without actually being enums since they wouldn't really work) so I can for instance in my code do SetState(IntroductionNPC1.MetNPC1); instead of having to look up the strings in the Encounter Dictionary.

stark sonnet
#

https://codeshare.io/6p638g

can someone explain to me what would cause Physics to not exist in the current context in line 67? i've never had this issue with using physics before

keen dew
night raptor
stark sonnet
#

i literally feel like an idiot now

gaunt ice
#

your ide should remind you

visual hedge
raven kindle
#

Im using this parallax backround, however i cant find the exact size of the prefabs, is there a way to do this or use a getsize function ?

#

i have gotten the size roughly however it still has a little skip when it changes

swift crag
#

You should make a Tooltip component that has serialized references to the components you need.

#
public class Tooltip : MonoBehaviour {
  [SerializedField] TMP_Text nameText;
  [SerializedField] TMP_Text amountText;
  [SerializedField] TMP_Text descriptionText;
  
  public void Show(Item item) {
    nameText.text = item.name;
    amountText.text = item.amount.ToString();
    descriptionText.text = item.description;
  }
}
#

Nobody who uses the tooltip should have to know about those three text components. They should just tell the tooltip "here, display this"

tulip stag
#

How to do that thing in Visual Studio where you select a snippet of code, do some magic (I think its a command?) and it isolates the code you selected into its own method?

swift crag
#

It's going to be called something like "extract"

#

This might be it.

#

So those are two different options.

tulip stag
#

Thanks!

swift crag
#

it's more clear if i don't just screenshot the google result lol

#

generally, you'll want to look for "extract X" if you want to grab some existing code and make it into a new thing

#

np!

raven kindle
#

Whenever i collect my coins, this error happens.

swift crag
#

Which line is the exception coming from?

swift crag
raven kindle
#

From 37 and 89

swift crag
#
    void DeleteCoins()
    {
        float deleteXPos = player.position.x - coinWidth * coinFallback;
        for (int i = 0; i < activeCoins.Count; i++)
        {
            if (activeCoins[i].position.x + coinWidth < deleteXPos) // line 89 
            {
                Destroy(activeCoins[i].gameObject);
                activeCoins.RemoveAt(i);
                i--;
            }
        }
    }
raven kindle
#

This is my second script for player ^

swift crag
#

sounds like activeCoins[i] references a destroyed game object to me

raven kindle
#

How would i fix it?

#

Would i need the trigger inside the coins script instead of player?

swift crag
#

You could do something like this before checking the position

#
if (activeCoins[i] == null) {
  activeCoins.RemoveAt(i);
  --i;
  continue;
}
#

continue skips to the next iteration of the loop

raven kindle
#

ah

swift crag
#

Alternatively, you can use RemoveAll

#

actionCoins.RemoveAll(coin => coin == null);

#

RemoveAll takes a method.

#

The method takes an element from the list and returns true or false

#

So this method returns true for every coin that equals null

#

This will remove every destroyed coin from the list. It also avoids the off-by-one error I almost made up there (I forgot --i) 😛

raven kindle
#

would i put it in the update method ?

swift crag
#

I'd do it in DeleteCoins, but as long as you do it before trying to check the position of each coin, it'll be fine

raven kindle
#

oke ty

swift crag
#

Actually, yeah, put it in Update.

#

you might write other methods that also work with coins

#

so do it like this

#
void Update() {
  // clean up your data

  // use your data
}
#

get rid of destroyed coins, then do whatever you need to with the remaining valid coins

raven kindle
#

what is i?

#

do i just stick it in a for loop for count of the list ?

tulip stag
#

let me see your loop. i think you might not have set it up right

raven kindle
rich adder
#

you should probably save

raven kindle
#

it seems to work now

#

however my coins are in 3s, the first one gets deleted fine, and then when the player collides with the second coin, both the second and third coin gets deleted

#

however if i only collide with the 3rd one, just the third one gets deleted

#

something with the second one

#

deleting them all

#

maybe because they are children from the middle one?

polar acorn
#

Million dollar question: Why are you manually comparing the position of the player against every coin in a list to determine if they should be deleted instead of just using a collision event of some sort

raven kindle
#

like this?

polar acorn
#

To delete the coins that fall off the screen just have another collider behind the screen that wipes them too

raven kindle
#

i have that

#

its just when i try to collect all 3 coins, i get an error

polar acorn
# raven kindle i have that

So why are you doing a bunch of math on positions to determine if they should be deleted instead of just letting the colliders do it

raven kindle
#

idk how to do that

#

the trigger is in a different script

#

inside the player

polar acorn
# raven kindle

Probably because your code that checks positions is still looking for coins deleted by your collision event

raven kindle
#

yes, but idk how to take them out of the list after collision

polar acorn
#

It looks like it exists just to loop through to check positions of, which you shouldn't be doing anyway

raven kindle
#

this script is basically a copy from my generateplatforms one

#

which i used a list for each platform

#

Would i not need it for this?

willow scroll
raven kindle
#

how would i do it instead?

willow scroll
#

are you trying to detect a collision between the player and a coin?

raven kindle
#

yes

raven kindle
willow scroll
#

Do you have a 2D game?

raven kindle
#

yep

willow scroll
#

Then all you need is OnCollisionEnter2D / OnTriggerEnter2D

raven kindle
#

i have this

willow scroll
raven kindle
#

Yes, that is for spawning the coins

willow scroll
#

when does it spawn the coins?

raven kindle
#

it only spawns when it passes other coins

#

soo there is not too many coins at once, lagging the game

willow scroll
#

Define "passes"?

raven kindle
#

player x coord > last coin x coord

willow scroll
#

I see, so it's 1 axis movement?

raven kindle
#

yes, the player is always moving horizontally

willow scroll
#

Do you move your game automatically?

#

So is your environment constantly moving?

raven kindle
#

the player is always moving

#

and the background too

polar acorn
# raven kindle

Two ways to do this:

  1. Have the coin itself check its own position and if it's past a boundary, spawn another coin
  2. Have a collider that detects coins that pass through it and spawns another coin
willow scroll
raven kindle
#

no coins dont move

willow scroll
#

I see. So the coin has to be destroyed when the player's x position is greater?

raven kindle
#

no, the coin gets destroyed when the player collides with it

#

however, if the coin goes too far behind the player it also gets deleted, as it goes off the screen

willow scroll
#

I am sorry, I meant "spawned"

raven kindle
#

a new coin gets spawned after the player has passed a previous one

willow scroll
#

this may, setting a fixed offset won't work properly

raven kindle
#

im just doing it for default screen size, i have variables i can change

#

overhead and fallback

willow scroll
#

So can the player go backwards?

raven kindle
#

no

#

its always moving forwards

willow scroll
#

I see, then yes. You can check the distance between the player and the coin.

#

I don't think making it in the Coin.cs script will be bad for performance.

#

You can also implement this logic in another scripts

raven kindle
#

The game is working fine, the only problem is that when the middle coin is collected, all coins get deleted

willow scroll
#
if (Vector2.Distance(transform.position, player.transform.position) > maxDistance)
    DoStuff();
#

please, have a look on that

raven kindle
#

but i guess thats because the left and right coins are children of the middle one

willow scroll
willow scroll
#

Maybe I don't get something?

raven kindle
#

the only problem is that when the middle coin is collected, all coins get deleted

willow scroll
raven kindle
#

yea but how would i fix it

willow scroll
raven kindle
#

but i want them to spawn in threes

willow scroll
raven kindle
#

just bcause

#

it looks cleaner

willow scroll
#

Well, then you're gonna have this issues. Just because.

raven kindle
#

ok...

willow scroll
#

Anyway, spawning them in the middle coin doesn't make them spawn in "threes"

#

Don't know what you're thinking bout

raven kindle
willow scroll
raven kindle
#

yes

willow scroll
raven kindle
willow scroll
#

not grandchildren

raven kindle
#

but then they wont spawn in threes

willow scroll
#

You spawn the parent GameObject

#

Coin

  • Left
  • Middle
  • Right
#

and you spawn coins

wintry quarry
raven kindle
#

How do you unparent themselves after spawning?

wintry quarry
#

transform.parent = null;

raven kindle
#

inside the spawn method?

raven kindle
willow scroll
#

Let me break it all down for you.

#

You told us that you want to spawn them in "threes"

#

But the way you spawn them, surely, has some issues. Because you make left and right coins the children of the middle coin.

#

This way, deleting the middle coin also means deleting other two

#

So now I have suggested you to spawn them in "threes", as you wanted, without having the previously described issue.

#

This method does work.

#

If you don't want to have them in "threes" anymore, you can spawn 3 GameObjects at once too.

tender stag
#

if i wanna do a sphere cast or check sphere, how can i find the lowest point of any collider it hit

#

because at the moment im just sending a raycast above the players head

#

to check how much he can uncrouch

#

so he doesnt hit the ceiling

#

but i wanna do it with a sphere instead of ray

#

but im now even sure if you can do like .hit with a sphere cast

hallow acorn
#

hey there i wanted to use mathf.movetowards and there are 3 floats needed: current, target and maxDelta. what does the maxdelta mean?

queen adder
#

how far the float will move

#

from start to target

#

(1, 2, 0.3) will give 1.3
(1, 5, 0.3) will also give 1.3
(1, 1.1, 0.3) will give 1.1

swift crag
#

Control the speed of movement with the maxDistanceDelta parameter. If the current position is already closer to the target than maxDistanceDelta, the value returned is equal to target; the new position does not overshoot target.

queen adder
#

Hi all.
Im trying to spawn enemies at random positions. But they are all just spawning from 1 point.
I made a list of spawn points and im using random range to choose a random spawn point but its not working.
Any advice will be appreciated

swift crag
#

well, show us your code

#

i can't see your screen!

#

!code

eternal falconBOT
abstract finch
#

How come this isnt working?
CS1955: Non-invocable member 'Monster.GetSize' cannot be used like a method.
GetSize() returns a float

gaunt ice
#

what is the declaration of GetSize
getter/setter?

abstract finch
#

oh my

#

wait onesec

#

ok fixed the typo but another issue like before

#

Cannot implicitly convert type 'System.Linq.IOrderedEnumerable<Monster>' to 'System.Collections.Generic.List<Monster>'. An explicit conversion exists (are you missing a cast

wintry quarry
#

Note that this creates a new list

abstract finch
gaunt ice
#

i prefer list.sort anyway

abstract finch
#
    {
        List<Monster> monstersToSpawn = new List<Monster>();
        foreach (Monster i in _monsterPool)
        {
            monstersToSpawn.Add(i);
        }
        monstersToSpawn = monstersToSpawn.OrderBy(x => x.GetSize()).ToList();

    }```
crisp meteor
#

I write this simple third person camera script, Working fine but the offset distance keep increaing decreasing while the player moving. (visually)

wintry quarry
#

List.Sort will sort the existing list in place yeah

abstract finch
#

Is it the same thing but remove order by?

wintry quarry
wintry quarry
abstract finch
wintry quarry
#

Doesn't matter, there's no point in the intermediate list.

#

Or the foreach loop

abstract finch
#

What if I add something like a max value where I can only pick up to a certain number of monster size

#

i.e. 5

#

i will implement this later like a token system

gaunt ice
#

linear scan/binary search to find the lower bound

hardy mist
#

for C# newbie, are async/await Task methods thread-safe?

amber spruce
#

so im using a character controller does that give a rigid body

gaunt ice
#

no
and async/await in unity runs on main thread

amber spruce
gaunt ice
#

the way that how you create a thread implies nothing for thread safe

amber spruce
#

why when i add a rigidbody and collider to my player with the character controller does it break

hardy mist
amber spruce
eternal needle
gaunt ice
#

why cant?
context switching is controlled by your os

amber spruce
hardy mist
#

or are there multiple threads actually?

gaunt ice
#

yes there is no context switching, btw talking thread safe on single thread program sounds meaningless

eternal needle
hardy mist
#

I just wanted to clarify if this is actually single threaded, thanks

amber spruce
hardy mist
#

because I was not sure

gaunt ice
#

always thread safe since there is only one thread.....

eternal needle
amber spruce
#

ok

#

whats a good way of doing jumps with a character controller

#
controller.Move(Vector3.up * m_JumpForce * Time.deltaTime);

this is how i tried to do it

polar acorn
#

You will need to track your velocity over multiple frames and modify it based on gravity. You can't just call a function one time and expect it to work with a CharacterController

#

.Move is a one-and-done thing, it has no momentum or acceleration

eternal needle
thorn holly
amber spruce
wintry quarry
eternal needle
thorn holly
#

Agreed, I always do rigidbody controllers

#

More freedom

swift crag
#

It does nothing else.

polar acorn
rocky birch
#

hey am i able to ask for help with "why tf does this code not work"

#

here

swift crag
#

yes, but

#

have a look here for advice on asking such a question

polar acorn
#

Because no one here knows what you want the code to do or what it's actually doing but you

cosmic quail
#

which do u guys prefer for rigidbody character controller, rigibody.addforce or rigidbody.moveposition?

thorn holly
#

I just do velocity+=

polar acorn
rocky birch
#

Im following a tutorial and trying to mirror exactly what they're doing.

https://www.youtube.com/watch?v=XtQMytORBmM

Im at 35:04

GMTK is powered by Patreon - https://www.patreon.com/GameMakersToolkit

Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then give you some goals to learn ...

▶ Play video
swift crag
#

Did you move a file recently?

rocky birch
#

I have no idea why im getting these errors

rocky canyon
swift crag
#

you probably hit Save in your code editor, re-creating the old file

cosmic quail
#

the script is called LogicScript.cs but the class inside it is LogicManager

rocky birch
# polar acorn Duplicate script

yeah i noticed one of the files was named LogicManager and that I couldnt find a logic script so i assumed i mislabled and renamed LogicManager to LogicScript

thorn holly
#

Something I’ve never really understood the inside out of is how components relate to game objects. In the gameobject class, are components fields within it or something else?

rocky birch
#

but ig there was one i couldnt see and made two, how do i fix that?

amber spruce
#

is there a reason why it doesnt work

cosmic quail
thorn holly
amber spruce
#

i know what some of it means

polar acorn
amber spruce
thorn holly
amber spruce
#

well problem is i have only made 2d games before

polar acorn
#

As long as it doesn't end up passing through the colliders, since MovePosition cannot be made continuous like velocity can

rocky birch
polar acorn
cosmic quail
thorn holly
rocky birch
#

Im trying to, this is the literal first time ive used unity

thorn holly
cosmic quail
polar acorn
rocky canyon
polar acorn
#

Like, do you know how to tell what line its on?

rocky canyon
#

u cant expect to learn it all in one day..

rocky birch
rocky canyon
#

logic must not be assigned

rocky birch
thorn holly
#

I wouldn’t reccomend YouTube tutorials, because it’s kind of hard to learn anything, bc you’re just copying what the YouTuber does. Unity learn had a great beginner tutorial that doesn’t take too long but is super helpful for beginners, I’d reccomend that.

slender nymph
eternal falconBOT
rocky birch
polar acorn
# rocky birch

So, logic is null. Have you dragged in the reference to your LogicScript in the inspector

rocky canyon
#

^ yea but have u assigned it into the slot of that script u just took a screenshot of?

rocky birch
rocky canyon
#

PipeMiddleScript

polar acorn
slender nymph
polar acorn
#

so you can get error highlighting and autocomplete

swift crag
#

IDE is an acronym for "Integrated Development Environment"

#

it's a text editor, plus tools to help you write code

rocky birch
#

How do i configure it?

swift crag
rocky birch
#

Ah! i missed that message!

#

Thank you!

cerulean kestrel
#

my door wont open whenever i pres play but i dont see a problem, does this look ok?

cerulean kestrel
#

C#

#

i made sure of it

polar acorn
#

That's a language

cerulean kestrel
#

oh

#

wait whats an ide

cerulean kestrel
#

oh i see

#

oh ok

#

OH visual studio

rocky birch
#

Do the settings auto save?

polar acorn
eternal falconBOT
cerulean kestrel
#

it DID have syntax highlighting

polar acorn
cerulean kestrel
#

i fixed it

#

door still dont work though

polar acorn
cerulean kestrel
#

ok ty

#

yeah everything works with vs

polar acorn
cerulean kestrel
#

i think...?

#

smthn changed

polar acorn
cerulean kestrel
#

i did

polar acorn
summer stump
cerulean kestrel
#

no

#

but everythings good with vs

polar acorn
# cerulean kestrel no

Then you have not. Go back through the configuration guide and make sure to follow all of it

rocky birch
#

How do i find what directory its in ive been searching visual studio in OS and i cant find it

summer stump
# cerulean kestrel but everythings good with vs

There are 3 main steps. One, the workload in vs. 2 setting vs as the external tool. 3 making sure you have the right package in Unity.

Secret 4th step is you might need to click "regenerate project files" in external tools.

cerulean kestrel
#

ok

summer stump
polar acorn
cerulean kestrel
#

i think i found the problem...

summer stump
cerulean kestrel
#

ill redo the door

summer stump
cerulean kestrel
#

i just did

amber spruce
#

how do i stop my character from falling over when moving

summer stump
rocky birch
summer stump
amber spruce
#

i have my character controller kinda working it moves the player now i gotta figure out the rotating part

 void Move()
 {
     float horizontalMove = Input.GetAxisRaw("Horizontal") * m_Speed;
     float verticalMove = Input.GetAxisRaw("Vertical") * m_Speed;
     Vector3 targetVelocity = new Vector3(horizontalMove, m_Rigidbody.velocity.y, verticalMove);
     m_Rigidbody.velocity = Vector3.SmoothDamp(m_Rigidbody.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);

 }
summer stump
rocky birch
#

No worries!

#

I found itt

#

so i pressed open and im greeted with this

summer stump
rocky birch
#

it doesnt show up after i double clicked it

cerulean kestrel
#

it shows that its moving but its not wtf

swift crag
merry spade
#

I want to get the Text of the InputField but I get an error

swift crag
#

your wrote a function that accepts zero arguments

summer stump
merry spade
#
    public void EnteringJoinCode(string code)
    {
        string JoinCode = code;
    }
swift crag
#

notice that the entire anonymous function is underlined

short hazel
swift crag
#

the entire function is wrong

wintry quarry
merry spade
rocky birch
#

do i like ... remake all the ones i already have here or?

swift crag
#

(foo) => ... takes one argument

summer stump
short hazel
polar acorn
#

OnValueChanged(EnteringJoinCode)

swift crag
#

indeed

merry spade
#

Ah ok i see thank you

swift crag
#

unless you really need the null filtering

#

But I don't think that'll ever happen

polar acorn
#

The text of an input field can't be null, the input field itself will return "" if it's empty

rocky birch
#

still getting the "logic can't be found" error

polar acorn
summer stump
polar acorn
#

Also your other errors show that you seem to have installed the Collab package which is depracated, you can remove it

polar acorn
rocky birch
polar acorn
#

If you don't have a script named Logic, that's an error

summer stump
#

I see you have a LogicManager

#

Maybe you need to rename Logic to LogicManager in your PipeMiddleScript script

queen adder
#

i cant change my terrain size anyone know a solution

rocky birch
summer stump
summer stump
queen adder
#

ok tysm

summer stump
#

This tutorial looks really bad too. I would look for a different one

rocky birch
summer stump
polar acorn
# rocky birch
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 140
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2023-12-22
rocky birch
polar acorn
#

Compare the thing that's underlined in red

#

to the tutorial

summer stump
#

The part that is underlined red in your code is not what they wrote in the tutorial

rocky birch
#

Got that fixed

rocky birch
#

another error what is a null and where is it in that line?

polar acorn
#

Meaning that there is likely an object tagged Logic that doesn't have a LogicScript on it

eager elm
rocky birch
#

this is the only one tagged logic

polar acorn
#

So that'd be your error

rocky birch
#

wait huh?

#

how do i put the logic script on it then

summer stump
polar acorn
summer stump
#

You can also click that "add component" button and type in "logicscript"

polar acorn
#

I do wonder why you have a LogicScript and a LogicManager. I don't think the tutorial had both

rocky birch
#

what is even happeninggg

polar acorn
#

See what that line has that could be null

summer stump
robust condor
#

Something has happened to my scene I can no longer do Camera.main:

summer stump
robust condor
#

Neither

#

Didn't know it had a tag

polar acorn
polar acorn
rocky birch
polar acorn
rocky birch
summer stump
# rocky birch

Those are called "Declarations"
You need an "Assignment"
You can assign via the inspector where digi showed. Or using the = sign

polar acorn
#

that shows that you have not assigned a value to that variable in LogicScript

rocky birch
#

oh then its the display thats not working

polar acorn
#

That I pulled the image above from

polar acorn
summer stump
#

What score text is the compiler supposed to be modifying?
It has no idea. You haven't told it

polar acorn
#

And looking at your inspector, you can see that there is no value for scoreText:

severe drum
#

does anyone know to to solve this?

#

i was working on camera and i think i broke soemthing

wintry quarry
severe drum
#

the visuals are repeting

rocky birch
wintry quarry
#

Well what are "the visuals" made of

severe drum
#

texture