#💻┃code-beginner

1 messages · Page 406 of 1

elder raptor
#

Clean and Organized code = Easier to maintain

Messy and "If it works, it works" code = Hard to maintain and if an issue comes, might be harder to solve it.

regal basalt
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class CameraSwitcher : MonoBehaviour
{
    public Camera camera1;
    public Camera camera2;

    void Start()
    {  
        camera1.enabled = true;
        camera2.enabled = false;
    }

    void Update()
    {
        //this key is not switching anything
        if (Input.GetKeyDown(KeyCode.C))
        {
            SwitchCams();
        }
    }

    void SwitchCams()
    {
        camera1.enabled = false;
        camera2.enabled = true;
    }
}```
elder raptor
#

But in the end, it depends on your coding style

languid spire
#

tbh because you said this 'for example, do i create a script for the cameras and put it in both cameras?'
which clearly demonstrates that you did NOT 'get the code shown'

regal basalt
regal basalt
elder raptor
#

There's an issue.

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


public class CameraSwitcher : MonoBehaviour
{
    public Camera camera1;
    public Camera camera2;

    void Start()
    {  
        camera1.enabled = true;
        camera2.enabled = false;
    }

    void Update()
    {
        //this key is not switching anything
        if (Input.GetKeyDown(KeyCode.C))
        {
            SwitchCams();
        }
    }

    void SwitchCams()
    {
        camera1.enabled = !camera1.enabled;
        camera2.enabled = !camera2.enabled;
    }
}
#

Try this

final kestrel
#
  public void LoadData(GameData data)
        {
            
            transform.position = data.PlayerPosition.ToVector3();
        }

        public void SaveData(GameData data)
        {
   this line -->         data.PlayerPosition = new SerializableVector3(this.transform.position);
        }

I am getting null reference exception on Save data.



[System.Serializable]
public class GameData 
{
    // public List<InventoryItem> inventoryItems;
    public int PlayerId;
    public SerializableVector3 PlayerPosition;
    public List<Slot> Container;
    public ItemDatabaseObject database;
    

    public GameData(){
        // this.inventoryItems = new List<InventoryItem>();
        this.PlayerPosition = new SerializableVector3(0,0,0);
    }
}

Why is that?

#

the first script is on my player

regal basalt
elder raptor
languid spire
proper cloud
#

I got a problem that should be trivial:

   [SerializeField] private Transform InventoryHolder;
   private int maxItems = 24;
   //stores items as (name, count)
   public Dictionary<string, int> storedItems = new Dictionary<string, int>();

   // Start is called before the first frame update
   void Start()
   {
       
   }

   // Update is called once per frame
   void Update()
   {
       //pressing "e" opens the inventory display
       if (Input.GetKeyDown(KeyCode.E)) toggleInventory();
   }

   private void toggleInventory()
   {
       Debug.Log("pressed E");
       InventoryHolder.SetActive(true);
       //if(InventoryHolder.GetActive) InventoryHolder.SetActive(false);
       //else InventoryHolder.SetActive(true);
   }

i assigned an object to the InventoryHolder inside the editor, it is a recttransform with 2 images attached, one also containing a gridLayoutGroup.
However, i get the following error-message:

error CS1061: 'Transform' does not contain a definition for 'SetActive' and no accessible extension method 'SetActive' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?)

trim gyro
#

is there anyone here who could help me with a local hosting issue I have? Im very new to unity and cant figure out why stuff isnt working. I had it all working before I went to sleep, I get back on in the morning, make a few changes to something that shouldnt affect the networking and suddenly clients cant connect 😭 pls help

late burrow
#

if i string.split(new string[] {"ab", "a" }) it first tries to split by longer string right?

proper cloud
languid spire
late burrow
#

sigh

#

"exampleab".split(new string[] {"ab", "a" })

languid spire
late burrow
#

so it will split by the first string rather than second

languid spire
short hazel
#

Starting from the first entry in the array, not the longest, like how a regular loop would iterate through an array

#

"abcdef".Split(new string[] { "c", "cd" }) yields ["ab", "def"]

shy zodiac
#

Hello community. I have 2 scripts: Progress and ProgressBar. I need to update progress bar without an Update method.
ProgressBar

using UnityEngine.UI;

public class ProgressBar : MonoBehaviour
{
    [SerializeField] private float _currentProgress; // Current progress amount
    [SerializeField] private Image _barImage;
    private float _maxProgress; // Link to Health in Threat class
    [SerializeField] private Progress _progress;
    private void Start()
    {
        _currentProgress = _progress.CurrentProgress;
        _maxProgress = _progress.MaxProgress;
    }
    private void OnEnable()
    {
        _progress.Changed += ChangeProgress;
    }
    private void OnDisable()
    {
        _progress.Changed -= ChangeProgress;
    }
    public void ChangeProgress()
    {
        float fillAmount = _currentProgress / _maxProgress;
        _barImage.fillAmount = fillAmount;
    }
}```
Progress
```using System;
using UnityEngine;

public class Progress : MonoBehaviour
{
    [SerializeField] private float _maxProgress = 5000;
    [SerializeField] private float _currentProgress = 0f;
    public float CurrentProgress => _currentProgress;
    public float MaxProgress => _maxProgress;
    public event Action Changed;
    private void Start()
    {
        
    }
    public void IncreaseProgress()
    {
        _currentProgress += Global.damage;
        Changed?.Invoke();
    }
}```
Thx for help 🙏
languid spire
short hazel
#

Is there anything wrong with this?

languid spire
#

which you do not fill so it does nothing

#

Sorry you do, so whats the problem?

shy zodiac
short hazel
#

The fill is made, you just don't pass the new progress value to the bar. You can do that with the event

languid spire
#

This looks totally overgineered for something so simple

short hazel
#

Yeah agreed, this could just be a progress.ChangeProgress(newValue)

#

No need for events and cross-references and whatnot

short hazel
#

Describe the issue

languid spire
shy zodiac
shy zodiac
languid spire
short hazel
# shy zodiac I call the method ```IncreaseProgress()``` and want to see ProgressBar is changi...

When you do _currentProgress = _progress.CurrentProgress in Start, this copies the value. _currentProgress will not change when _progress.CurrentProgress changes in the future.
Sure, you use an event to catch when the progress changes, but you're not passing the new progress value anywhere, so the value of _currentProgress stays the same.

But yes this can be simplified, it does not need to be that complex for it to work. Keep it simple. No events are required for this to work

shy zodiac
#

So, one or 2 scripts?
Do you mean links between scripts without events?

shy zodiac
short hazel
#

The values are changing in your Progress script, not in ProgressBar.

#

For the reasons mentioned above

languid spire
# shy zodiac So, one or 2 scripts? Do you mean links between scripts without events?

man, it's so simple

public class Progress : MonoBehaviour
{
    [SerializeField] private float _maxProgress = 5000;
    [SerializeField] private float _currentProgress = 0f;
[SerializeField] private Image _barImage;
    
    public void IncreaseProgress()
    {
        _currentProgress += Global.damage;
         float fillAmount = _currentProgress / _maxProgress;
        _barImage.fillAmount = fillAmount;}
     }
}
#

interesting how do you fill barImage?

shy zodiac
#

What do u mean?

languid spire
#

_barImage will always be null

#

ok, in inspector, yes?

shy zodiac
#

Yes

languid spire
#

tbh I see little point in there being 2 scrips for this

shy zodiac
languid spire
#

which will actually work

shy zodiac
#

Not beautiful structure x)

languid spire
#

Beauty is in the eye of the beholder and I like to make thing beautiful for the compiler

shy zodiac
#

I meant only one SerializeField)

languid spire
#

lol

shy zodiac
#

Actually I wanted to make something like MVC pattern. Separate logic and visual.

languid spire
#

Then 2 scripts, but no need for all the cross referencing. ProgressBar should know nothing about Progress if you adhere to strict MVC principles

#

and, this is game dev. My advice, keep all the app patterns where they belong, in app dev

frosty lion
#

Any way to morph a square into a rectangle without messing up the sides line width? 2D

shy zodiac
languid spire
shy zodiac
languid spire
shy zodiac
#

Now I know it. A year later, I returned to the project and realized that I did not understand what was written х) And then I bagan to separate megaclass to modules.

shy zodiac
languid spire
shy zodiac
frosty lion
languid spire
shy zodiac
shy zodiac
languid spire
shy zodiac
languid spire
#

very, very senior

umbral rock
#

im having a problem with 3d coding, im following brackeys tutorial to make movement with the camera and i have this code
The error that im getting is weird because i have asigned the player to the variable...

#

this is the inspector of the camera

solar arrow
#

GameObject starEffectObject = Instantiate(starEffect, this.transform.position, new Quaternion(-90, 0, 0, 0));

how to make the x rotation to -90?
this code doesnt seems to work

languid spire
shy zodiac
languid spire
vast vessel
#

hey guys.
is there a way for me to calculate a force, that when applied to a rigidbody with a weight of float weight, will have the rigidbody be thrown towards Vector3 target?
i want my AI to calculate this force, to throw its grenade prefab at its target. weight needs to be taken into account to make sure the grenade lands on the target position.

wintry quarry
solar arrow
cosmic quail
languid spire
vast vessel
umbral rock
#

anybody that knows where my issue lies?

wintry quarry
wintry quarry
#

(you also have two copies of the script on the object)

umbral rock
wintry quarry
#

Yes it still clearly shows it not assigned

shy zodiac
umbral rock
swift crag
#

if i make a "tutorial series", it sure as hell isn't going to be video-based

languid spire
wintry quarry
wintry quarry
shy zodiac
languid spire
swift crag
wintry quarry
#

But I love pandas

languid spire
#

Can't Read? Won't Read? Don't do Dev. Go and get a job at McD's

wintry quarry
languid spire
#

Gotta be education above all else

swift crag
#

creating educational content (insert scare quotes as needed) solely for engagement is probably what makes so many tutorials so terrible

umbral rock
swift crag
languid spire
queen adder
swift crag
#

stop pinging random people for help

languid spire
wintry quarry
queen adder
#

aight mb

wintry quarry
#

The code is only one part
The setup in the scene is also important and must be correct

brave compass
# shy zodiac We need seniors on Youtube

It's easy to point at popular video tutorials and say they should have better code. And there are definitely many cases where they have bad code for no good reason. But I disagree with the idea that writing bad code as a beginner is "the wrong way" to learn and you should be learning to write code the way experienced seniors do. Those senior programmers didn't learn code that way. They made stupid mistakes, many of them, and learned from them. They understand why it's so important to write "good" code, because they've experienced what bad code does to productivity.

swift crag
#

God knows most people would completely ignore it, but a series on "bad code" and its consequences would be very useful

#

demonstrating how poor design decisions lead directly to bad outcomes

brave compass
#

Learning from mistakes is the best way to learn. I don't think you can avoid that part by having someone tell you their experience. It's not going to stick. Did you learn that way?

languid spire
queen adder
#

how about if i add the buttons that i am trying to program to the prefab itself will that work?

swift crag
#

But I suppose you can nudge people out of bad practices.

#

I see a lot of people referencing every single prefab as a GameObject, because that's what they've always done (or, god help them, that's what they saw in the tutorials)

languid spire
shy zodiac
languid spire
#

99% are click bait only, copies of copies of bad copies of bad tutorials

shy zodiac
ionic zephyr
#

how do I pass an Interface through a method?

polar acorn
ionic zephyr
#

but how do I ensure I pass this.Interface?

solar arrow
polar acorn
ionic zephyr
#

how do I pass this particular interface through a method

polar acorn
#

and then pass an instance of this

languid spire
ionic zephyr
#

yes

polar acorn
ionic zephyr
#

how do I pass this ItemContainer

short hazel
#

this

polar acorn
swift crag
short hazel
#

thing.CraftingProcessInDUDE(this)

#

Pass yourself

polar acorn
swift crag
#

This page explains what they mean

#

Read the documentation.

ionic zephyr
polar acorn
languid spire
solar arrow
languid spire
swift crag
#

The four parts of a quaternion are numbers in the[-1..1] range. They are not angles.

#
new Quaternion(-90, 0, 0, 0);

This is a nonsense value

shy zodiac
umbral rock
#

is there anything here u guys can see that makes my player look up and down instead of left and right? i want the player to turn left and right when i go with my mouse to the left or right side...

solar arrow
umbral rock
#

this is the view

languid spire
umbral rock
#

nah, player body is still looking up and down + the camera view isnt even changing

swift crag
#

Point your arm to your right.

#

Imagine rotating yourself around your arm.

#

The problem will reveal itself (:

languid spire
#

sorry, up and down is .right, you want .up for left/right

slender nymph
#

also unrelated to the issue, but don't multiply mouse input by deltaTime, it is already a delta from the previous frame so doing that multiplication ends up causing stuttery camera controls

umbral rock
#

i tried that, its still the same...

swift crag
#

you tried what?

umbral rock
#

.up

#

vector3.up

languid spire
#

what vector3 or transform

umbral rock
swift crag
#

Since you're using Rotate, you'll want to use Vector3.up anyway: Rotate works in the "self" space by default

#

However...

umbral rock
#

if i go left and right he does this.

swift crag
#

Select the object that's referenced by playerBody

#

Show me the scene view.

umbral rock
#

thats the inspector of my player

swift crag
#

Your object has been rotated.

#

Blue is supposed to be the forward axis.

#

but it's pointing straight up

#

This is probably because you've imported a model from Blender.

shy zodiac
swift crag
#

I would suggest parenting the player body to an empty object

#

You can then rotate the model however you want

umbral rock
#

so i put the model in the empty player object, then i put the empty player object in that variable of the camera called playerBody?

swift crag
#

bingo

#

no matter how weirdly the model is rotated, the parent object is nice and consistent

sonic marlin
#

Hey, me and my friend wants to start a collaboration game but we cant really get it to work. He started the project as a 2D game but when i start up the project it's in 3D, Why is that?

swift crag
#

You are using Transform.Rotate, which works in Space.Self by default. This means that it rotates from the point of view of the Transform, rather than just rotating in world space

sonic marlin
#

alright thanks, but how does the whole collaboration thing work, do i push my changes or is it automatic?

swift crag
#

Version control is generally not automatic.

#

You make changes, then commit them.

#

If you're using Unity Version Control, then read the documentation provided by Unity

#

you should have a decent handle on how your version control system (VCS) works before you start working

slender nymph
#

imagine the chaos of version control pushing changes automatically. just in the middle of doing some testing and it suddenly pushes some broken logic to the rest of the team

umbral rock
final kestrel
#

So I am following a tutorial on saving and loading. Actually 2 tutorials. I got the player position part right. I can save and load that. But the inventory part is a bit confusing.
https://hatebin.com/weqwrfakpf This the code. I pass the game data reference and just assign the list of container to the game data. https://hatebin.com/dzedeqqeis
But the container seems null on save file.

swift crag
#

Show the hierarchy and the inspector for your MouseLook component.

sonic marlin
swift crag
swift crag
#

which implies that your friend has not committed and pushed (or created change sets, I guess, in Plastic) his work

swift crag
final kestrel
swift crag
#

Set this rotation to zero.

#

Adjust the player model to compensate.

#

The point is for the Player object to not be rotated 90 degrees in some random direction

languid spire
umbral rock
#

ok, i'v done this and i see my problem, the camera is now looking around but the only problem is that the player is lying flat on the ground wich makes is seem like he is still doing weird rotations but he is actually rotating around himself like i wanted to, i just dont know how to let the player stand up so i dont have the same problem as before anymore...

swift crag
umbral rock
#

yes but then i have the same problem as before

swift crag
#

The model.

#

Not the "Player" object

sonic marlin
#

Why does it say this when im one of the 2 owners of this project

languid spire
umbral rock
swift crag
#

It needs to be rotated to [-90, 0, 0] so that it looks right.

#

This means that its transform is now rotated so that its "forward" direction points straight into the sky

#

If you try to rotate that transform around its Y axis (the green arrow), it winds up rolling from side to side

#

because the green axis now points what you'd consider to be backwards

umbral rock
#

and is there a fix to it without an empty game object?

swift crag
#

I think you can change the import settings to bake the rotation into the model?

#

you can also check "Apply Transforms" when exporting the FBX from Blender

#

(this can cause problems for models with objects parented to other objects, though)

umbral rock
swift crag
#

But the root cause of that was the model being imported with a 90 degree rotation in the first place, yes

#

I prefer to just parent the model to an empty. It lets me adjust the position/rotation/scale without messing with the rest of the entity

umbral rock
#

so because i rotate the empty game object the objects inside it rotate with it

swift crag
#

yes, that's how transforms work

final kestrel
short meadow
#

Hey I was wanting feedback on a plan for how to script a crafting system before I dig too deep into it. Is this a good channel to post for feedback since it's related to how I'll set it up in code or should I visit #archived-game-design ?

languid spire
final kestrel
#

No it does not. Why would I need one?

#

To be able to create one without filling it?

languid spire
cosmic dagger
final kestrel
#
  public void LoadData(GameData data)
    {
         this.Container = data.Container;
         this.database = data.DatabaseObject;
    }

I thought this would just copy the slot list from save data and populate it.

short meadow
# cosmic dagger this channel is fine. the question is more about code architecture. i'd start wi...

This is what I've got written down.

Objective: Have a 3x3 crafting grid the player can put alchemy ingredients that have various mana type values and take up either one or multiple slots within the crafting area.

Item Class - scriptable object that holds data regarding name, manaType, strength, reactivity and amount of the item. This also holds a craftingSize, but it's currently just a placeholder icon.

Potion Class - scriptable object that holds data regarding name, basePrice and amount of the item.

PROPOSED: Recipe class

  • contains a 3D array.
  • first checks the item manaType values against a ratio to determine which potion the cauldron should craft based on the manaType ratio.
  • then checks for a bonus if the user was able to craft that potion against it's designated shape for a bonus.
  • instances a new scriptable object to the player based on what potion was the result while subtracting the instances of all ingredients used from the player inventory.

Questions:

-Should the 3D array be an array of dictionaries that check what item is there for the key and then spits out a value that would be the product of another class that returns a manaType, strength and reactivity? Or is there another way that's simpler that sticks out to you?

-I have a 'size' property that currently only holds a Sprite as a placeholder in my Item class. This is meant to eventually hold data regarding how many squares the ingredient takes up and in what pattern they'll be in inside the crafting grid... I have no idea how I'll go about doing this but would a system like the one proposed accommodate this? I'd like to make sure that if an item gives a value of 10 manaType A and takes up 3 of the grids on the crafting square (on a 3x3 UI grid) that it only adds 10 to the crafting recipe, not 30.

languid spire
final kestrel
#

Thats why I think it messes up the serialization part.

#

There should be ID and amount

languid spire
final kestrel
#
    public ItemObject item;
    public int amount;
#

this is the slot data

languid spire
#

yes, I know but how to know what public List<Slot> Container; contains?

final kestrel
#

I see it gets added in the inspector when I add items.

#

I mean items get added

languid spire
#

that is NOT how to debug

final kestrel
#

I should extract information from the container in code then to see if it actually fills it up

languid spire
#

I would add ToString methods to both GameData and Slot so you can output what they actually contain at any given point in time

final kestrel
#

I did log the ids of the items in the container when they get added and it gives the ids on console.

languid spire
#

And that tells you what at the point you want to Serialize the data?

final kestrel
#

You mean when I save the data?

languid spire
#

yes, Serializing is what Save does

#

Deserializing is what Load does

final kestrel
#

I just call the Save and load on button clicks. When playing.

#

I add items then I save

languid spire
#

you really have no idea what I am talking about do you

final kestrel
#

stop playing. Clear the slot container on start. I press load. Player position gets loaded correctly. Slot container is still empty

#

well I am trying 😄

languid spire
#

ok. Step 1. You look at GameData in the inspector, correct?

final kestrel
#

I do not have a way of seeing it in the inspector because I dont have a monobehaviour class for it

languid spire
#

but you told me you can see slots and items being added to it

final kestrel
#

I see items being added in the Scriptable object which is my inventory.

#

sorry should've been clear

languid spire
#

so how to you KNOW what is in GameData?

final kestrel
#

Ahh. I logged the slot container's item ids on add item. Not the game data container.

languid spire
#

exactly, so you don't KNOW, you assume. That is why I said make ToString mthods for GameData and Slot then you can KNOW at the point of Save and LOad what they contain

final kestrel
#

I must look up ToString methods and what they mean.

#

or cant I just make a monobehaviour class to see them in the inspector?

languid spire
#

ToString methods are just simple things to help you visualize data, like a Vector3 prints nice in the console. that is a ToString method

#

Alternatively you could go and learn how to use the VS debugger and save yourself a lot of grief

cosmic dagger
# short meadow This is what I've got written down. Objective: Have a 3x3 crafting grid the pla...

The item SO shouldn't have a quantity field as that value will change. I'm not sure the difference between the Potion and Item class

The Resident Evil-style (grid-based) inventory is more difficult to code but there should be tutorials on how to check available grid space for items, though it would be a 2D array. Also, the size is probably stored as a 2D array.

I'm unsure what you mean by, "check what item is there for they key and then spit out a value that would be the product of another class." You'd already have the item recipe that is created ,no? Unless you're creating procedural items?

umbral rock
#

i'v made a movement script but when i move the player teleports a few meters up and is moving above the ground, just floating, is this bcs the player model is created in blender?

white wind
final kestrel
white wind
#

i did a game where i connected both of the players with a line but now i need a damage system for the line i did this script but I don't have a collider that shortens and just scales according to the line.

rich adder
#

please write in full sentences

white wind
#

Oh i'm sorry

rich adder
#

show the setup and code involved.

rich adder
white wind
#

simply a damage system that whenever the enemy walks in the line it takes damage.

rich adder
#

oh okay, I dont see any lines. are you talking about trigger?

languid spire
rich adder
#

whats the current issue and what is happening instead

white wind
languid spire
white wind
white wind
#

i will thank you guys!

rich adder
#

are they set to trigger?

white wind
#

yes so right now i have a box collider with is trigger on it but it doesn't follow the line

white wind
#

i mean the collider scales down or lengthens whenever it needs to like the line is following the player so it will move and every thing but the collider doesn't move with the line.

rich adder
# umbral rock

you're mixing two different physics controllers , rigidbody and character controller should not go together

#

also configure your !ide

eternal falconBOT
rich adder
umbral rock
open gull
#

I don't know how I can do to push objects, I tried using rigidbody 2d for the pushed object, but because it's topdown the gravity is 0, so when I push it, it doesn't stop until it collides with something else XD

Could anyone tell me any method to make this work?

white wind
#

not the trigger the collider overall

umbral rock
rich adder
umbral rock
#

when i press a movement key it teleports me up in the sky

rich adder
short meadow
#

The item SO shouldn't have a quantity

umbral rock
rich adder
rich adder
umbral rock
rich adder
#

press F..aso why is the scale 10..

umbral rock
rich adder
#

jesus christ

rich adder
# umbral rock

select the player press F and show me the arrows of the player

umbral rock
#

jesus christ, i can see the problem 😄

ionic zephyr
#

someone knows what to do with this?

silent stream
#

why it's showing "Hello, World!"

rich adder
rich adder
rich adder
summer stump
eternal falconBOT
slender nymph
rich adder
#

^^ use for loop

warm condor
#

Hey guys, i'm having this weird problem with my if statement executing the first condition when it is false. Here i'll show you the code:

Debug.Log(CurrentMovementDirection + " " + (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D)));//This is a debug
if (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D)) CurrentMovementDirection = 0;
else{
      if (Input.GetKeyDown(KeyCode.A)) CurrentMovementDirection = -1;
      else if (Input.GetKeyDown(KeyCode.D)) CurrentMovementDirection = 1;
}

Now, when I press A and D at the same time, the CurrentMovementDirection is equal to zero, which makes sense. But then when I proceeded to moving either A or D, the condition Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D) truns true and I can confirm this with the debug. The issue is that the CurrentMovementDirection variable is still equals to zero, which is still executing the first if statement instead of going to the else statement even if it is false. How is this even possible ?!?

umbral rock
ionic zephyr
rich adder
summer stump
white wind
#

sorry i was eating

ionic zephyr
#

is this what is making the problem?

rich adder
rich adder
summer stump
rich adder
#

you cant remove them while foreaching

#

use a for loop, as i said

swift crag
#

Modifying a collection will invalidate all of its iterators

#

at least, modifying a List<T> will

rich adder
#

ah yes do a backwards loop

for (int i = 0; i < collection.Count; i++)
{
    if (someCondition(collection[i]))
    {
        collection.RemoveAt(i);
        i--; 
    }
}```
swift crag
#

you can totally write a collection class whose iterators can handle removal

rich adder
#

type forr inside your IDE you should get snippet for backwards loop

open gull
umbral rock
rocky canyon
rocky canyon
#

att he top on transform thers scale

rich adder
#

cause they got their own scales and offset

rocky canyon
#

on the bottom on the collider theres size

warm condor
rocky canyon
#

make ur scale 1:1:1 change the siz of hte collider instead

umbral rock
rich adder
umbral rock
#

i dont know where the capsule collider is located

rich adder
#

again.. you have scale at 10

#

it should be 1..

#

adjust the size on the Character Controller, which is a physics body with a collider already

#

what is that box collider there for, get rid of it or make it trigger

umbral rock
#

waitt what, the transform on the player empty object is just the hitbox??? wow, im so dumb

rich adder
#

Character Controller is a physics controller component not a hitbox

umbral rock
#

yeah sorry i meant that

#

lmao

white wind
#

Think of it a top down game 2D

#

And i have a laser connected to both of my players but it doesn't damage enemies when enemies go through it.

#

@rich adder

rich adder
white wind
#

no why should it?

rich adder
#

because triggers are physics messages?

white wind
#

i see let me see what will happen

rich adder
#

you need a at least 1 rigidbody between the two colliders

white wind
#

No no let me tell you something. When I move the line the collider doesn't move with the line.

white wind
#

A LINE RENDERER

#

with this script:

using UnityEngine;

public class LineConnector : MonoBehaviour
{
public Transform player1;
public Transform player2;
private LineRenderer lineRenderer;

void Start()
{
    lineRenderer = GetComponent<LineRenderer>();
    if (lineRenderer != null)
    {
        // Set the number of positions to 2
        lineRenderer.positionCount = 2;
    }
}

void Update()
{
    if (lineRenderer != null && player1 != null && player2 != null)
    {
        // Update the positions of the line
        lineRenderer.SetPosition(0, player1.position);
        lineRenderer.SetPosition(1, player2.position);
    }
}

}

eternal falconBOT
rich adder
#

also show where you put this script on gameobject

white wind
#

i put it on a a gameobject with a transform, a line renderer, and a script which is line connector

summer stump
#

Why would a collider move with it then?

white wind
#

it does

#

i forgot

summer stump
#

Ok, well you did not list that. I wasn't sure

#

Gotcha

white wind
#

yea yea mb

summer stump
#

The collider will not match the linerenderer component

white wind
#

MB

#

didnt mean to type that

white wind
#

should i use a edge collider ???

summer stump
#

You would have to move rhe collider or gameobject

white wind
#

wdym?

final kestrel
# languid spire A LineRenderer has a bounds property so you can use that to create your collider...
private List<IDataPersistence> FindAllDataPersistenceObjects()
    {
        IEnumerable<IDataPersistence> dataPersistenceObjects = FindObjectsOfType<MonoBehaviour>().OfType<IDataPersistence>();
        return new List<IDataPersistence>(dataPersistenceObjects);
    }

I have found it. This looks for Monobehaviour derived classes.

public class InventoryObject : ScriptableObject, ISerializationCallbackReceiver, IDataPersistence

This one here is not a monobehaviour so the LoadData never gets called!

summer stump
# white wind wdym?

I mean that the collider is not affected by the line renderer, it will be affected by the transform and its own properties 🤷‍♂️

white wind
#

i seeee

#

OHH

#

i can make it work if my mind is not lying to me

final kestrel
#
private List<IDataPersistence> FindAllDataPersistenceObjects()
    {
        IEnumerable<IDataPersistence> dataPersistenceObjects = FindObjectsOfType<MonoBehaviour>().OfType<IDataPersistence>();
        return new List<IDataPersistence>(dataPersistenceObjects);
    }

Can I extend the findObjectsOfType to look for both monobehaviour and scriptable objects?

languid spire
#

not good practice though

split dragon
#

Hi. I have a question: How can I prohibit writing more than the required number in the Input Field (in the text)? For example, I want to limit the number to 10 (11 and more won't help). There is, of course, a character limit, but it is based on the number of characters.

languid spire
#

if you only want to accept 0 thru 10 why use an input field and not a slider?

languid spire
#

then tryparse the input data to an int and test the result

atomic pendant
#

hey

#

how can I get the forward direction of a gameobject?

#

transform.forward is world coordinates

swift crag
#

If you want a local space forward, that's just Vector3.forward

#

or if you want to be really roundabout, transform.InverseTransformDirection(transform.forward) (:

#

(which will always spit out Vector3.forward)

atomic pendant
#

so I have this

#
            shuriken.transform.position =
                Vector3.MoveTowards(
                    shuriken.transform.position,
                    ownerPlayer.transform.forward,
                    speed * Time.deltaTime);
swift crag
#

this doesn't make sense

#

MoveTowards takes two positions and moves between them

#

you're giving it a direction

atomic pendant
#

I basically want to move the shuriken forward in the direction facing the player

swift crag
#
shuriken.transform.position += ownerPlayer.transform.forward * speed * Time.deltaTime;

This will move the shruiken in the direction the player is facing

#

Note that this will probably misbehave if you have a Rigidbody on the shuriken

atomic pendant
#

well I just want collision detection

#

so I guess I'll need a rigid body

swift crag
#

You'll need a rigidbody on the shruiken, yes.

#

You will also need to either set its position or velocity

#

You don't want to set the position or rotation of an object that has a rigidbody on it

atomic pendant
#

it works

atomic pendant
#

I'd like to avoid physics if possible for the shuriken itself

#

is there a way to detect collision without rigid body?

swift crag
#

you can use a kinematic rigidbody; however, the other object will need a non-kinematic rigidbody on it

atomic pendant
#

let me read that

#

ty

#

so with a kinematic body I can rotate and move it as I wish right?

swift crag
#

I'd suggest setting its position with rb.position, and doing the spinning normally

#

You can set it up like this:

#
  • Shuriken <-- Rigidbody, trigger collider
    • Visual <-- Mesh renderer
#

Spin the Visual and move the Shuriken

atomic pendant
#

so the mesh gotta rotate independently from the rb?

#

and the mesh should be a child of the rb

swift crag
#

Right.

#

The spinning will have nothing to do with the rigidbody

atomic pendant
#

got it

urban dirge
#

I'm having some issues with visual studio and getting some features to work properly and after checking both online and in the #854851968446365696 section on the IDE configuration, I still haven't been able to find an answer. Is this the right place to ask?

rich adder
#

show external tools page and VS

urban dirge
rich adder
# urban dirge

ok try closing vs, click regen project files button. open script from unity and wait a few moments

urban dirge
#

Should I adjust any of the settings for the generate .csproj files?

rich adder
#

no

#

if it doesn't work, in your solution explorer window inside VS. If it says (missing ) on the assembly file right click it, reload with dependencies or something like that

swift crag
#

it can get "stuck", yes

urban dirge
#

My issue is that while vs is working, I'm not getting the highlighting on a lot of my code and the suggestions that I see other people have under their code is not appearing for me like theirs, only small suggestions as well as not showing me the parameters and I've tried following what microsoft said to do with intellisense but that didn't work, so I figured it's probably an issue with vs code itself

rich adder
#

so now its vscode ?

#

I'm confused here, your externaltools is set to visual studio visualstudio

#

are you trying to use vscode instead? vscode

urban dirge
#

sorry I didn't mean to say vscode, it is Visual Studio visualstudio

final kestrel
#

https://hatebin.com/anemqeapqw So I managed to save the Id and amount to a file by ignoring the scriptable object in my Slot data. Now In my DisplayInventory script. Its having trouble instantiating the scriptable object prefab. Saying its null reference exception. https://hatebin.com/nnqqgzrwau Is this related with not being able to create gameobjects from json?

frank zodiac
#

talkPanel.transform.Find("Frame1").Find("Text").gameObject.GetComponent<TextMeshProUGUI>().text = "lmao you have a receding hairline"; giving me a nullreferenceexception

#

is this code even correct?

rich adder
rich adder
frank zodiac
#

🤨

rich adder
#

find a better way to link your component

#

serialize the field in the inspector

frank zodiac
rich adder
#

just like link it in the inspector

frank zodiac
final kestrel
#

I did not get it sorry

rich adder
frank zodiac
#

like this?

rich adder
#

you will literally spent half your time doing that, at some point you have tolearn it

final kestrel
#

Like I meant I will check what to see if its null or not

rich adder
frank zodiac
rich adder
#

Debug them, put breakpoints, or just print values. narrow down

final kestrel
#

Well I go learn debugging then. I was using debug.logs

#

😄

final kestrel
#

thanks

frank zodiac
#

i know this is unrelated but im curious, is there a place or website where i can pay someone to re format and design my code and make it readable and concise?

swift crag
#

maybe upwork or something

#

i suspect it'd be a lot more work to have someone else fix it than to just improve it on your own, though

quasi sparrow
#

i need help with a third person camera script

#

hello guys , i need help with a third person camera script

spare mountain
#

ask the question

rich adder
#

yeah you said that

quasi sparrow
#

my third person camera doesnt follow the player

#

this is the script

#

using UnityEngine;

public class ThirdPersonCamera : MonoBehaviour
{
public Transform target; // The target (player) the camera will follow
public Vector3 offset = new Vector3(0, 2, -5); // The initial offset from the target
public float smoothSpeed = 0.125f; // The speed at which the camera smooths its movement
public float rotationSpeed = 1.5f; // The speed at which the camera orbits around the target
public float pitchMin = -20f; // Minimum pitch angle
public float pitchMax = 60f; // Maximum pitch angle

private float currentYaw = 0f; // The current yaw rotation of the camera
private float currentPitch = 0f; // The current pitch rotation of the camera

void LateUpdate()
{
    if (target == null)
    {
        Debug.LogWarning("No target assigned to ThirdPersonCamera");
        return;
    }

    // Get the mouse input for camera rotation
    float mouseX = Input.GetAxis("Mouse X") * rotationSpeed;
    float mouseY = Input.GetAxis("Mouse Y") * rotationSpeed;

    // Update yaw and pitch based on mouse input
    currentYaw += mouseX;
    currentPitch -= mouseY;
    currentPitch = Mathf.Clamp(currentPitch, pitchMin, pitchMax); // Clamp pitch angle

    // Calculate the rotation quaternion
    Quaternion rotation = Quaternion.Euler(currentPitch, currentYaw, 0);

    // Calculate the desired position based on the target position and offset
    Vector3 desiredPosition = target.position + rotation * offset;
    Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);

    // Update camera position and rotation
    transform.position = smoothedPosition;
    transform.LookAt(target.position + Vector3.up * offset.y); // Make camera look at the target
}

}

spare mountain
#

!code

eternal falconBOT
quasi sparrow
#

can you guys help

spare mountain
quasi sparrow
#

i use mirror for multyplayer

#

the multyplayer works but the camera doesnt follow the player

rich adder
#

no offense but you probably should not be doing multiplayer

quasi sparrow
#

but can you fix the code

#

please

rich adder
#

I know nothing about mirror

quasi sparrow
#

i mean the third person camera script

#

it doesnt work

rich adder
#

what about it ?

quasi sparrow
#

the camera doesnt follow the player

swift crag
#

have you done anything whatsoever to debug it?

rich adder
#

use cinemachine but since you mentioned multiplayer its probably more complex than that

quasi sparrow
#

i tried chatgpt 40

swift crag
quasi sparrow
#

yeah , thast why i went here

rich adder
#

again no offsense but you're using GPT aint no way you're making a multiplayer worth anything functional

swift crag
quasi sparrow
#

bro do you know how to fix it or

swift crag
#

you just tell it to follow whoever the player is

quasi sparrow
#

i tried

#

but look

rich adder
swift crag
rich adder
quasi sparrow
#

look what happends

#

no errors appear in the console

#

@rich adder

rich adder
#

the console tab is not even shown, also where is the script?

quasi sparrow
#

this is the third person camera script using UnityEngine;

public class ThirdPersonCamera : MonoBehaviour
{
public Transform target; // The target (player) the camera will follow
public Vector3 offset = new Vector3(0, 2, -5); // The initial offset from the target
public float smoothSpeed = 0.125f; // The speed at which the camera smooths its movement
public float rotationSpeed = 1.5f; // The speed at which the camera orbits around the target
public float pitchMin = -20f; // Minimum pitch angle
public float pitchMax = 60f; // Maximum pitch angle

private float currentYaw = 0f; // The current yaw rotation of the camera
private float currentPitch = 0f; // The current pitch rotation of the camera

void LateUpdate()
{
    if (target == null)
    {
        Debug.LogWarning("No target assigned to ThirdPersonCamera");
        return;
    }

    // Get the mouse input for camera rotation
    float mouseX = Input.GetAxis("Mouse X") * rotationSpeed;
    float mouseY = Input.GetAxis("Mouse Y") * rotationSpeed;

    // Update yaw and pitch based on mouse input
    currentYaw += mouseX;
    currentPitch -= mouseY;
    currentPitch = Mathf.Clamp(currentPitch, pitchMin, pitchMax); // Clamp pitch angle

    // Calculate the rotation quaternion
    Quaternion rotation = Quaternion.Euler(currentPitch, currentYaw, 0);

    // Calculate the desired position based on the target position and offset
    Vector3 desiredPosition = target.position + rotation * offset;
    Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);

    // Update camera position and rotation
    transform.position = smoothedPosition;
    transform.LookAt(target.position + Vector3.up * offset.y); // Make camera look at the target
}

}

rich adder
#

can you at least post the code properly with a link

quasi sparrow
#

where

rich adder
quasi sparrow
#

we are in code begginer

rich adder
#

doesn't mean you shouldn't be able to follow simple instructions unrelated to code..

quasi sparrow
#

and here is the code

#

using UnityEngine;

public class ThirdPersonCamera : MonoBehaviour
{
public Transform target; // The target (player) the camera will follow
public Vector3 offset = new Vector3(0, 2, -5); // The initial offset from the target
public float smoothSpeed = 0.125f; // The speed at which the camera smooths its movement
public float rotationSpeed = 1.5f; // The speed at which the camera orbits around the target
public float pitchMin = -20f; // Minimum pitch angle
public float pitchMax = 60f; // Maximum pitch angle

private float currentYaw = 0f; // The current yaw rotation of the camera
private float currentPitch = 0f; // The current pitch rotation of the camera

void LateUpdate()
{
    if (target == null)
    {
        Debug.LogWarning("No target assigned to ThirdPersonCamera");
        return;
    }

    // Get the mouse input for camera rotation
    float mouseX = Input.GetAxis("Mouse X") * rotationSpeed;
    float mouseY = Input.GetAxis("Mouse Y") * rotationSpeed;

    // Update yaw and pitch based on mouse input
    currentYaw += mouseX;
    currentPitch -= mouseY;
    currentPitch = Mathf.Clamp(currentPitch, pitchMin, pitchMax); // Clamp pitch angle

    // Calculate the rotation quaternion
    Quaternion rotation = Quaternion.Euler(currentPitch, currentYaw, 0);

    // Calculate the desired position based on the target position and offset
    Vector3 desiredPosition = target.position + rotation * offset;
    Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);

    // Update camera position and rotation
    transform.position = smoothedPosition;
    transform.LookAt(target.position + Vector3.up * offset.y); // Make camera look at the target
}

}

swift crag
#

Jesus christ

rich adder
#

holy hel

swift crag
#

You've spammed the same giant blob of code three times

quasi sparrow
#

can you fix it

#

or help me fix it

rich adder
#

idk is it possible to fix your attitude

spare mountain
#

💀

rich adder
#

you keep ignoring our instructions to post code properly

quasi sparrow
#

what instructions

spare mountain
#

!code

eternal falconBOT
swift crag
#

Please read the bot message instead of completely ignoring it.

rich adder
quasi sparrow
#

i told you there are no errors in the console

rich adder
#

so why are you sending the code/

swift crag
#

That has absolutely nothing to do with anything I have said.

quasi sparrow
#

cause it doesnt work

swift crag
#

If no errors appear, that just means that no exceptions are being thrown. It is still possible that:

  • The code isn't even running at all
  • The code isn't doing anything
  • The code is doing something, but it's not what you want it to do
eternal needle
#

It looks like you guys are having completely different conversations 😅

quasi sparrow
swift crag
#

You should not be attempting to develop a networked multiplayer game if this is your current level of understanding

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

swift crag
#

Multiplayer is non-trivial.

quasi sparrow
#

CAN YOU JUST FIX IT IF YOU CANT THEN SAY SO

rich adder
#

we can, but you cant understand the fix even if we tell you

quasi sparrow
rich adder
#

stop spamming dude

#

fr

swift crag
#

You've posted the same link four times now

#

This is unbelievable.

rich adder
#

how to easily cut yourself of any help 101

quasi sparrow
#

bro i will stop when someone actualy helps me

rich adder
#

blocked, and im moving on.. gooday

swift crag
quasi sparrow
#

can you help me or not

#

isnt that what this discord is for?

slender nymph
quasi sparrow
#

i tried

swift crag
#

I already told you what to do, but you ignored it.

quasi sparrow
#

ok

swift crag
quasi sparrow
#

thanks for noone helping me

swift crag
#

You have nobody to blame but yourself right now. Your attitude is unbearable.

strong wren
#

@quasi sparrow Keep your usage of this server constructive.

quasi sparrow
#

bro this is the first time i used this server in a 100 years

slender nymph
#

you need to figure out which object on that line is null. there are at least 3 that could be

final kestrel
#

also the itemObject is null

eager spindle
#

to solve coding problems take a few steps:

  • research on the problems you have. if theres an error code, google that.
  • rubber ducky: grab any object or person near you and explain your code to them line by line
    with sufficient effort, the above two methods will already solve 95% of problems.
    for any remaining problems, paste the code thats causing you problems on gdl.space, describe your problem concisely.
quasi sparrow
eager spindle
#

we will try to help you but if you havent bothered to solve your problem no one can help you. we spent 2 hours the other day trying to teach someone how types in coding worked. nightmare stuff

quasi sparrow
#

The camera doesnt work , i mean follow the player object

final kestrel
#

I mean the obj that is trying to get instantiated is null because inventory.Container[i}.item is null

quasi sparrow
#

thats all i know how to explain

final kestrel
#

so it cannot grab its prefab

eager spindle
#

like the Inspector panel

quasi sparrow
#

the player prefab or the camera?

slender nymph
eager spindle
quasi sparrow
#

ok

#

here

final kestrel
#

Thats probably why

eager spindle
#

oh youre jumping into networking already?

final kestrel
#

Which leads back to me not being able to store the scriptable objects T_T

eager spindle
#

in that case, is your player instantiated by the network controller?

quasi sparrow
eager spindle
#

whats a mirror

quasi sparrow
quasi sparrow
#

which is free

slender nymph
quasi sparrow
#

look this happens when i spawn the player

eager spindle
#

confused right now. your player is instantiated by the network controller, so why is the target transform set before you spawn the player in?

#

is there a part where you change the target transform of the camera when the player is spawned in?

swift crag
#

perhaps they are referencing the player prefab

eager spindle
#

yea

swift crag
#

none of these images show a game object with a ThirdPersonCamera component on it

final kestrel
knotty hull
#

Is it allowed to send code files or does it have to be links?

eager spindle
#

send links

slender nymph
eternal falconBOT
swift crag
#

use these instructions

quasi sparrow
#

look at the inspector

eager spindle
#

@quasi sparrow what's happening here is that you dragged the prefab into the slot and expecting it to work. however, the player is not the same as the prefab at runtime.

  • go to the code where the player is instantiated
  • get the camera controller
  • set the camera's controller target to the instantiated player's transform
eager spindle
#

look at the editor

#

where are you setting the target?

final kestrel
quasi sparrow
#

i first created the game object capsule player and then dragged it into the prefab

final kestrel
quasi sparrow
#

and added all the components

slender nymph
slender nymph
#

does it need to be a scriptable object?

quasi sparrow
final kestrel
#
using UnityEngine;


public enum ItemType
{
    Equipment,
    Key,
    Misc,
    Default
}
public abstract class ItemObject : ScriptableObject
{
    public GameObject prefab;
    public ItemType type;
    [TextArea(15,20)]
    public string description;

}

Yes

quasi sparrow
#

@eager spindle

final kestrel
#

I created items based on this.

eager spindle
quasi sparrow
#

ok ill try

slender nymph
final kestrel
#

with keys and items so i can access them either way

slender nymph
#

so if you are already doing that, why are you just not assigning to the item variable using that information?

quasi sparrow
#

is it supposed to look like this @eager spindle

eager spindle
#

no

#

transform is missing

eager spindle
#

drag in the player now

#

do this

#

start the scene, drag the player into the slot

final kestrel
quasi sparrow
#

do i add unity version controll so you can see it in the game better @eager spindle

eager spindle
#

and check if it works

#

no

quasi sparrow
#

@eager spindle

eager spindle
#

im not downloading your project

#

and executing foreign code on my device

slender nymph
quasi sparrow
#

its not large

#

neither has viruses

#

@eager spindle

eager spindle
#

learn to solve your problems without having other people download your project

final kestrel
quasi sparrow
#

ok

final kestrel
#

How do I get the items from database back then

eager spindle
#

to conclude this, your code looks correct but you need to set your target correctly

final kestrel
#

In load and save I believe

slender nymph
eager spindle
#

you dont want the camera to follow your prefab. you want it to follow the instantiated player.

quasi sparrow
final kestrel
eager spindle
#

you dont want the camera to follow your prefab. you want it to follow the instantiated player.

#

where are you setting the camera target.

quasi sparrow
eager spindle
#

i am looking

#

it says Type Mismatch

#

so youre setting it incorrectly

halcyon hearth
#

Hello, if I use this, when the scene is closed and some scripts unsubscribe to an event that has the Game Manager in its own On Disable, sometimes the Game Manager is already destroyed and a new Game Manager is instantiated. So it gives an error, new objects have been created, is it possible that you created them in the on destroy?...

How do I solve this

quasi sparrow
#

yeah and what you said to drag the player object there and that doesnt work

slender nymph
quasi sparrow
#

it doesnt let me

final kestrel
quasi sparrow
#

@eager spindle

slender nymph
final kestrel
#

I should use the database

slender nymph
#

so do that

final kestrel
#

Uhh man this is complicated

slender nymph
#

it's really not

eager spindle
# quasi sparrow <@819432500920188938>

click the Target slot to make sure its highlighted, then click Delete. this clears the reference in the slot. you should be able to drag your player in afterwards

final kestrel
#
public void LoadData(GameData data)
    {
        Debug.Log("Loaded");
        Container = data.Container;
        for (int i = 0; i < data.Container.Count; i++)
        {
            Container[i].item = database.GetItem[Container[i].ID];
        }
    }

I did this

slender nymph
#

and does that do what you want it to?

final kestrel
#

It does work

quasi sparrow
#

@eager spindle

eager spindle
#

i can only help you so far

final kestrel
#

give me 10 minutes and ima break it again. Thanks for the help

final kestrel
quasi sparrow
#

@eager spindle

final kestrel
#

Not really. wdym

quasi sparrow
#

thats why i want you too look better at the project in unity version control

eager spindle
#

no

quasi sparrow
#

@eager spindle

eager spindle
#

we already told you to help yourself

final kestrel
#

I learn c# by developing games

quasi sparrow
#

well i dont know how

eager spindle
#

this is something that everyone solves within a couple minutes

#

literally unlink the reference and double check it

quasi sparrow
#

i tried but it doesnt work

eager spindle
#

the only other way you get blocked from dragging in a reference is if the gameobject doesn't have a transform, which is impossible

#

you are doing something wrong and we can only help you so far

final kestrel
#

Did someone delete their message? or am I tripping

quasi sparrow
#

well

queen adder
#

im miserable at designing pixel art for my dream game, is it then even worth to learn coding c# and unity?
I feel like even when i could climb this wall of learning how to code a game properly, there would be the design aspect
Theres no financial resources id have to invest LOL

quasi sparrow
#

i dont know how to fix it

knotty hull
raw token
eager spindle
queen adder
eager spindle
eager spindle
#

in their late 30s

#

you can get pretty far on free assets too

#

my entire game at the moment is made on kenney assets

#

i have no knowledge on environmental design but this is what im on right now

#

look into Kenney's assets, a collection of 2D and 3D assets

raw token
eager spindle
#

its more important to plan out on what you want for the game and using free assets that you might swap out later rather than not starting at all

#

you miss all the shots you dont take, and this is definitely a shot you want to take because its gonna be super rewarding

knotty hull
queen adder
fading seal
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class lawydScript : MonoBehaviour
{
    public GameObject inticon, teddy, teddyText, lawydText, findoutText;

    public AudioSource audioSource;
    
    
    void OnTriggerStay(Collider other){
        if(other.CompareTag("MainCamera")){
            inticon.SetActive(true);
            if(Input.GetKey(KeyCode.E)){
                lawydText.SetActive(true);
                findoutText.SetActive(false);
                teddyText.SetActive(true);
                teddy.SetActive(true);
                inticon.SetActive(false);
                audioSource.Play();
            }
        }
    }
    void OnTriggerExit(Collider other){
        if(other.CompareTag("MainCamera")){
            teddyText.SetActive(false);
            inticon.SetActive(false);
        }
    }
}``` in my game whenever you interact with the "teddy" gameobject its supposed to play a sound and if you hold e it plays it over and over. i dont want that is there anyway to fix it? (ik my interaction system isnt the best this is my first game)
raw token
eager spindle
#

by doing fun projects youll be more motivated to create more stuff and consequently learn more

knotty hull
slender nymph
# fading seal ```cs using System.Collections; using System.Collections.Generic; using UnityEng...

the best thing to do would be to start with redesigning your interaction system. because the normal advice would be to use GetKeyDown however that is likely not going to work in OnTriggerStay on account of that method only returning true for the first frame the button is pressed which is most likely not going to be a physics frame.
Look into using raycasts to interact with objects instead of copy/pasting this same interaction code on a shit load of different objects. you would instead have one object controlling interacting with objects and those interactable objects can then just do their own thing when interacted with instead of having the objects themselves check for interactions

raw token
knotty hull
#

yes. I dont know how to assign a click method to an button

frank zodiac
vital cave
#

hello guys! Sorry for interupting, do you know why i keep getting this error when i want to create a 2D game?

swift crag
frank zodiac
#

the code is really messy i should be paying him extra i cant lie

raw token
# knotty hull yes. I dont know how to assign a click method to an button

Gotchya 👌

Assuming you're using UI Buttons that are children of some Canvas, you have two options:

  • In the Inspector for the button, there will be an OnClick section. You can add callbacks there, and drag the GameObject with the TicScript component from your hierarchy to the new field, then select your TicScript and the appropriate method from the dropdowns. Here's a video of that in action
  • In code, you can subscribe the method to the event. Something like
void Start() {
  btnA01.onClick.AddListener(btnA01_clicked);
}

See the docs for reference - switch to the docs for your specific Unity version as things have changed a bit.

knotty hull
raw token
knotty hull
#

No I use legacy

raw token
knotty hull
#

What does that mean?

wanton kraken
#

hey guys, i'm trying to move my 2d sprite slightly left per frame- instead it goes flying. any ideas on how i could require a longer input to fully turn it? it just goes flying atm lmao, which makes sense because it's 60 degrees per second

#

if(Input.GetKey(KeyCode.A) == true) { //MOVE LEFT
Player.transform.Rotate (0, 0, 1); }

wintry quarry
#

Also this isn't moving anything, it's rotating

wanton kraken
#

oh, i completley forgot about that command! thank you :)

wanton kraken
frank zodiac
#
private IEnumerator SpriteBlink()
{
    for (int i = 0; i < 4; i++)
    {
        attackButton.GetComponent<Image>().enabled = false;
        yield return new WaitForSeconds(0.1f);
        attackButton.GetComponent<Image>().enabled = true;
    }
}

this thing wont work for some reason it only blinks once for like 1 second then comes back, not 0.25f every time

keen dew
#

You need two WaitForSeconds, one after setting enabled to false and one after setting it to true

frank zodiac
#

thanks!

amber nimbus
#

Hey guys, I was wondering how to actually learn clean code, I think I have the basics of C# down, but I cant figure out OOP. I just cant seem to figure out when to use Inheritance or Intrefaces or any stuff like that, how could I learn this?

queen adder
#

since i dont want to learn stuff i dont want to learn yet id like to learn stuff i would like to know

So with unity i want to create a 2d open world survival craft game. Id like to know how to create a procedural generated world thats basically infinite by generating new tiles every time.

It should contain: Biomes, chunks, have a seed (so its random and choosable)

what would the technical stuff look like? like i would need to create a class for chunks, a class for biomes and an int/float for seeds?
What is the child of what?

What c# stuff i would need to know to make this possible
like i guess classes
else and if functions?
What more?

wanton kraken
#

thats a super heavy project, this is the beginner channel lol

#

i'd reccomend finding a procedural generation addon and spending time learning it

#

that's pretty complex

summer stump
lethal swallow
#

Hi, took a break from unity but coming back I still haven't managed to solve the problem of what is happening to the Ai animation, please help :)

Problem: Enemy is jittering and not running / playing running animation smoothly
Expected: Enemy smoothly runs to the Player.

Thanks :))

Code: https://pastebin.com/saNRbhgB

rocky canyon
#

this is the only thing being sent to the animator?

#

animator.SetFloat("Speed", 5f);

#

what happens if u lock it in place?

rocky canyon
#

then its not the code

#

im awful at blend tree's sooo idk if i can help

#

@swift crag i had him set the float to 5... too see if it was the fluctations that caused the problem

#

as u can see in his video it still glides along the ground..

#

so im thinkin its something with the animation. or the blend tree.. but idk

swift crag
#

Do all of your walk animations line up?

rocky canyon
#

@lethal swallow ^

swift crag
#

by "line up" I mean that the left and right feet are doing the same things at the same normalized time

#

All animations should have the left foot hit the ground at, say, 25% time

rocky canyon
#

his rig isn't broken b/c its above the ground. lmao

#

thats all i know

swift crag
#

It shouldn't matter if you're at a speed that exactly matches one of the blend tree values

#

so perhaps one of your animation clips isn't looping

rocky canyon
#

^ could be.. id check ur clips @lethal swallow and make sure ur blends are set up w/ looping animations

swift crag
#

(also, go fix your dang animation names!)

#

they're all mixamo.com

rocky canyon
#

mixamo..

#

i hate that

swift crag
#

you can change the names of animations in the Animation tab of the model importer

rocky canyon
#

imagine its just b/c the animations aren't set to looping..

#

cuz ive seen him working on this for a whiile now

swift crag
#

Yes, that's exactly what this looks like

#

When the speed is changing over time, you'll see it wobble between the last frame of the different animations

vapid vector
#

can anyone point me a video or blog to maybe explain how I could achieve this with my camera? I've worked with cinemachine on a topdown isometric view but ive been trying to achieve this for a while now and cant 🤦‍♂️

half egret
#

Dolly track? focus on center?

swift crag
rocky canyon
lethal swallow
#

sorry for going afk for a few mins I will try these things and let yall know. Thanks :)

swift crag
#

you can tell it to spherically interpolate between two cameras

rocky canyon
swift crag
#

This will give you that effect for free, even if your cameras aren't actually both looking at a central point

#

And it's actually necessary, too, if you want to be able to transition between two cinemachine cameras

vapid vector
#

does it have to be cinemachine or can i do this with regular camera? I was trying to get 2 cinemachine in the right place and swap between them, but i seriouslt cant get the cinemachine in the exact spot i want since theyre like smart and whatever and calculate position alone

half egret
#

Yeah two virtual cameras is actually easier

swift crag
half egret
#

Use a dolly track if you want more precise movement from point to point

swift crag
swift crag
#

Give the Blend Hint property a look.

#

"Cylindrical Position" would be the most fitting here

#

It moves circularly on the XZ plane and vertically on the Y axis

rocky canyon
#

the camera tracks a pivot point in the center.. and can rotate around it

#

but (2) 📷 are much better idea

swift crag
# swift crag

You set the Blend Hint on the camera you are blending from

half egret
rocky canyon
#

wait wat did he say?

swift crag
#

But since you're going back and forth, you'll want to put it on both

rocky canyon
#

ohh yea Fen's smart guy lol

swift crag
#

Cylindrical lerping is really handy

half egret
#

They're just suggesting to mess with blend hints between the interpolation

swift crag
#

I wound up re-implementing as a function that works much like Slerp

rocky canyon
#

ahh yea.. that'd work

rocky canyon
swift crag
#

Spherical interpolation on two axes and linear interpolation on a third

rocky canyon
#

i have some rotations and i lerp them.. it seems fine..

#

but i never use Slerp.. and i think i should refactor

swift crag
lethal swallow
swift crag
#

I am less clear on Quaternion.Lerp vs. Quaternion.Slerp

rocky canyon
#

soo more accurate than lerp

#

for rotations

swift crag
#

I'm guessing it's similar to how they differ for Vector3

swift crag
rocky canyon
#

ahh okay.. i gotcha..

#

imma look into it more

swift crag
lethal swallow
rocky canyon
#

double click the blend pieces on the right..

#

you'll see the animations

#

or click the animation.. and in the inspector.. set looping

swift crag
#

Looping is not configured in the animator controller, mind you. You need to change how the animation clips are getting imported.

rocky canyon
#

^ this.. in the inspector

swift crag
#

I presume you've downloaded some FBX files from Mixamo

swift crag
#

Click on one and go to the "Animation" tab in the inspector

#

here, you can configure how the FBX gets turned into animation clips

#

You can create multiple animation clips from one file, set when they start, configure root motion, and, vitally, decide if they loop

rocky canyon
#

|| the weren't looping the entire time ||

vapid vector
#

its just that cinemachine has been a little overwhelming for me, im never sure what to use but I'll give your advice a shot thanks @swift crag !

swift crag
rocky canyon
#

yea.. they're all basically the same.. w/ different setups and components..

lethal swallow
swift crag
#

No position or rotation controls at all.

rocky canyon
#

but u can make any do like any other

swift crag
#

Try turning them on and off in play mode

#

Change the Blend Hint settings and see how they affect the blending process

rocky canyon
#

ya, its not as complicated as u think it is @vapid vector

swift crag
#

(don't tell anyone that I have no idea what this does though)

lethal swallow
rocky canyon
#

the cinemachine camera.. just takes the real camera.. and plops it in its place...

swift crag
#

"Freeze When Blending Out" is really handy for jumping away from a camera that's moving around a ton

swift crag
#

You can also enable "loop pose" to try to make the start and end match if they don't already line up

#

but Mixamo animations already loop perfectly

half egret
rocky canyon
#

even if i dont use it.. i want it to be a cinemachine camera.. just in case

swift crag
#

I use a very large number of virtual cameras in my game

half egret
#

Yeah, Vcams make scene cameras and game cameras a breeze

#

You can do loads of cool things with an extremely reduced amount of scripting

swift crag
#

I do want to modify the package a bit to give me more control over how long blends take

rocky canyon
#

it might.. but i dont see it in the window drop down anymire

half egret
#

They don't?

swift crag
#

yeah, they're just "cinemachine cameras" in 3.0

rocky canyon
#

just cinemachine camera

swift crag
#

it is a bit less concise

half egret
#

I'm still on 5

lethal swallow
#

Fen and Spawn tysm 💚
It finally works 🎉

swift crag
rocky canyon
half egret
#

LOL

lethal swallow
swift crag
rocky canyon
swift crag
#
public void SetFloat(int id, float value, float dampTime, float deltaTime);
#

It looks like you can have it do a smooth-damp for you

half egret
#

Guess I'll have to update my cinemachine... not for this project though lest it breaks everything

rocky canyon
#

thers a Dampen!?

rocky canyon
#

holy crap..

swift crag
#
animator.SetFloat("Foo", agent.velocity.magnitude, 0.3f, Time.deltaTime);
rocky canyon
swift crag
#

In theory, this would be equivalent to using Mathf.SmoothDamp to smooth out the magnitude yourself

rocky canyon
#

stick to the version u used

swift crag
#

One big change is that the "free look camera" is no longer a completely unique class

#

you can create it with standard position and rotation control components now

half egret
rocky canyon
#

you've been investigating it seems Fen

swift crag
#

I use 3.0 by default now

#

or 3.1 or whatever it's up to

rocky canyon
#

imma restart real quick.. compile times are getting bad

#

brb

half egret
#

So future Mr!

swift crag
#

It's got some nice new stuff (including a few things I asked for, haha)

half egret
#

Me* shall remember!

rocky canyon
#

bak

half egret
#

I'll have to check the changelog

swift crag
#

CinemachineDeoccluder has the option to resolve towards the Follow target instead of the LookAt target.

#

I was using it for a Dark Souls-y game

half egret
#

Ahyep, I'm on 2.9.7

swift crag
#

but I had a problem: when locked onto an enemy, the look-at point was positioned between the player and the enemy

half egret
#

I'm missing a major release

swift crag
#

and if that point went into a wall, the camera went bonkers

#

now you can just have it keep the follow target in view

swift crag
#

but maybe give it a try on a branch

rocky canyon
#

cinemachine obstacle avoidance.. is subpar imo

half egret
rocky canyon
#

stay away from the rabbit hole..

half egret
#

I'm okay with Cinemachine's implementation for the most part

rocky canyon
#

@swift crag i got a question for u since ur right here... how do u have ur scenes collected? how do u call upon them?