#💻┃code-beginner

1 messages · Page 469 of 1

solemn fractal
#

Thank you

waxen adder
#

Trying to think of a way to do a "box cast" but one not beholden to physics.

The reason for it is to see what a 1x1x1 cube/box passes through on a grid between two points.

cosmic dagger
# solemn fractal Thank you

np, it's much nicer to install the NaughtyAttributes package. it's free and they have a ton of useful custom attributes for the inspector . . .

indigo mirage
#

Sorry was busy, but ive implemented this, and am running into an issue with the angle checker, And it mis declaring the angle

solemn fractal
#

Insteresting. I will check this out.. ty

indigo mirage
#
if(CustomIsGrounded && Physics.SphereCast(transform.position, groundCheckRadius, Vector3.down, out RaycastHit slopeHit, 2f))
            {
                hitPointNormal = slopeHit.normal;
                angle = Vector3.Angle(hitPointNormal, Vector3.up);

heres the angle code again

cosmic dagger
waxen adder
#

Imagine a graph paper, and you got two, cells(?). One's the start, one's the end. I want to project the start square in a straight line to the end square and record what other squares are hit along the way

cosmic dagger
#

i believe pathfinding will do that for you . . .

waxen adder
#

Navmesh pathfinding? This is a turn based game that uses a grid

grand badger
#

Navmesh isn't the only pathfinding solution. I opt to A* unless there's freeform movement

cosmic dagger
#

more like A* or dijkstra's . . .

grand badger
#

and before you even think about it, Imma go ahead and say that I didn't like this asset and ended up writing my own solution within a few days when I needed it

waxen adder
#

My goal is XCOM 2 style movement, which is "go exactly to location, unless there's an obstacle in the way. Otherwise, A* pathfind around it until there's no obstacle in the way"

At least, that's what I've got through messing around with it

#

Here's a variety of examples for what it's like and what I'm aiming for atm.

teal viper
waxen adder
rich adder
teal viper
waxen adder
#

In what context for each I wonder? Navmesh until there's something in the way?

teal viper
#

A* could be used to make sure there's a path to the point. And the navmesh to get the shortest path towards it.

waxen adder
teal viper
#

This is just a guess though, they probably have a system that integrates both the grid and direct path finding in one system.

#

Apparently Xcom2 is built on UE3.5. But Unreal engine is way more lenient with source code access compared to Unity, so I wouldn't be surprised if they have their own system or modified heavily one of the ue systems.

waxen adder
#

Sadly I think the actual pathfinding stuff is native to unreal, so can't access it just from the modding resources as far as I can tell

teal viper
#

I'm not sure how modding is related here at all. Modding depends on how much the developer decides to expose via modding.

waxen adder
#

True

waxen adder
#

Oh wow, that asset seems to do things very closely aligned with what I want

hallow sun
#

sliced SpritedRender changes in width/height when changing from Empty to containing a Sprite, is this normal behaviour?
i've currently solved this by adding an invisible 1 pixel Sprite, instead of letting it start empty.

abstract flicker
#

how can i smoothly rotate the camera while it is being moved? i tried a couple of things and it just doesnt work

teal viper
willow scroll
abstract flicker
# willow scroll Where `Vector3.up` should be changed according to where it should be rotated ```...
private void LateUpdate()
{
    transform.position = Vector3.SmoothDamp(
        transform.position,
        target.position + offset,
        ref currentVelocity,
        positionSmoothTime
        );

    transform.rotation = Quaternion.Lerp(transform.rotation, currentRotation, rotationSmoothTime * Time.deltaTime);
}

private void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        ToggleGamemode();
    }
}

public void ToggleGamemode()
{
    if (toggle)
    {
        offset = new Vector3(0, 12, -30);
        currentRotation = Quaternion.Euler(16, 0, 0);
    }
    else
    {
        offset = new Vector3(0, 0, -30);
        currentRotation = Quaternion.Euler(-8, 0, 0);
    }

    toggle = !toggle;
}
```That also works?
#

yeah

#

i think it does

muted wadi
#

I have two arrow buttons that I want to cycle forwards and backwards through a list of materials that are applied to an object. Is there a way to check in the method which button has been pressed?

{

}```
willow scroll
willow scroll
#

And put it inside of a Coroutine

solemn fractal
#

Hi.. Is there a way to give more than 1 tag to an object or other identifiers ? like give a tag and also another identifier I can use to refer to that object?

teal viper
summer stump
summer stump
teal viper
solemn fractal
#

Because I have a situation. where I want that the bullet will always be deleted when it hit an enemy so I would use enemy tag in all enemies.. But i need something else to distinguish them for other things. But all my enemies or most of them will have same scripts attached. They will just have dif variable values in general. Maybe is there a way to put script on all my enemies and inside that script I create IDs? and somehow I use it or something like that?

teal viper
#

if(enemy.SomeProperty == theValue)

solemn fractal
#

hmmmm ok makes sense

eternal needle
#

kinda just like assigning them a team

solemn fractal
#

that is what I was thinking

#

thank you guys

short hazel
muted wadi
muted wadi
#

why exactly am I getting an error here?

#
            {
                wheel.GetComponent<MeshRenderer>().material = currentWheelMaterial;
            }```
ivory bobcat
muted wadi
#

bunch of gibberish

ivory bobcat
#

Where did you copy this code from? If not, what exactly are you trying to do?

muted wadi
#

i didn't copy it. I'm trying to change the materials on a prefab so that when the prefab is spawned, all the changes the player made in the customisation screen are saved

ivory bobcat
#

Your for each statement looks like it's expecting a collection of mesh renderers

muted wadi
#

it partly works

#
            mesh.material = currentCarMaterial;```
specifically, this works. The singular mesh renderer on the prefab gets the new material applied when the save button is pressed. It just wont work for the wheels, and I'm not gonna do one for each because thats jarring
#

there has to be a way to do a foreach, and also find all of the wheels

ivory bobcat
#

Yeah, looks like you simply inserted invalid code into a foreach statement tbh
To use the foreach statement, you've got to provide it a collection to iterate.

muted wadi
#

if i do getcomponentsinchildren then i can't use Find

ivory bobcat
#

Well, logically you'll need to find all of your wanted objects first then iterate them using the foreach. You're missing the first step, providing a collection of your wanted objects.

ivory bobcat
# muted wadi if i do getcomponentsinchildren then i can't use Find

Basically something like... (convoluted solution relative to your specifications - precaching is preferred and avoidance of Find)cs var children = ...GetComponentsInChildren<Transform>(); foreach(var child in children) { var found = child.Find(...); if(found != null) { ... } }

muted wadi
#

yeah i'll have to see what i can do with that

ivory bobcat
#

Where you original code called Find on one child whereas you've now got a collection of children

muted wadi
#

i think i got it, but i need to finish my menu script now

#

cant test until thats finished

digital cave
#

How can I add cameras to here within code? URP.

hollow zenith
#

I've got an issue with instantiated text not positioning properly, in some rare cases.

    textVnMode = Instantiate(textPrefab);
    textVnMode.transform.SetParent(floatingTextContent.transform, false);

It's basically 50% off on y axis, it's inside a vertical layout.
Is it possible that the layout doesn't update in some cases?
Is there a way to force layout to update?

teal viper
hollow zenith
#

It didnt help, but it happens only in certain cases, I think it might be due to a coroutine?
In that 1 case a coroutine is running I think

#

reenabling it at runtime fixes the issue tho, but thats not a solution

teal viper
hollow zenith
#

Alright thanks

#

That didnt work, I tried few things.
What worked is adding Layout Element to the Verical Layout group and setting Min Height to a higher value, to match the text.

dire shadow
#

Hey, is this the right place to ask questions? 🙂

eternal falconBOT
dire shadow
#

I was wondering if I could make my sprite look sharp, I think I messed somehting up

languid spire
#

So you did not bother to read the bot message I just gave you

dire shadow
#

Ah, I understood that as ask! lol sorry

errant flower
#

where is the hdrp material thing in unity 2022

#

and i dont see a package for it

#

nvm found i t

steep rose
#

Does the angle code work on a normal slope then?

#

You caught me at a time where I was sleeping 😅

marble hemlock
#

im not exactly sure where to look in documentation exactly but say i have two colliders, and i want it to do a specific thing if the thing its colliding with has a specific tag, how would i go about that, and what's the correct function?

#

is it OnTriggerEnter?

deft grail
#

or you can use other things that are part of Physics.

#

specifically the Overlap and Raycast or similar

marble hemlock
#

i didnt expect this bit to be as complicated as it ended up being

#

i cant escape raycast notlikethis

deft grail
#

you dont have to do a raycast

rich adder
marble hemlock
rich adder
#

Sadly even these old videos don't point out that LayerMask is not to be confused with the Layer number on a gameobject, even if they said so

marble hemlock
#

So I just can't see the raycast itself?

rich adder
steep pier
#

Does anyone know what I should learn about when it comes to turn based combat systems?

steep pier
#

i dont really understand what i should do, im kinda lost

late burrow
#

how i loop through jobject storing more jobjects

rich adder
#

learn arrays

#

etc.

rich adder
late burrow
#

not nested

#

just it gives me jtokens not jobjects

#

and i cant seem make use of them

#

i saved entirety of my json with jobjects

late burrow
#

no like literally everything is jobjects

#

i have jobjects inside jobjects inside jobjects

#

i vant to make single loop that will get me one step down

steep walrus
#

I have a bunch of objects moving towards the player and I want to reset them to their starting place when the player dies. In the awake method I assign my Vector3 array of positions to the Vector3 of the GameObject array but I am having trouble setting the Vector3 when the trigger is entered

public GameObject[] tracks;
    Vector3[] startPos;

    void Awake()
    {
        startPos = new Vector3[tracks.Length];
    }

   void OnTriggerEnter(Collider player)
   {
        tracks = new Vector3[startPos.Length];
   }
rich adder
# late burrow i have jobjects inside jobjects inside jobjects
    JObject outerObject = JObject.Parse(json);
    foreach (var property in outerObject.Properties())
    {
        Debug.Log($"Key: {property.Name}");
        if (property.Value is JObject innerObject)
        {
            foreach (var innerProperty in innerObject.Properties())
            {
                Debug.Log($"  {innerProperty.Name}: {innerProperty.Value}");
            }
        }
    }
}```
try it
steep walrus
#

should I make 6 variables?

rich adder
#

oh this is some type of object manager?

steep walrus
#

ugh not really I dont think but I could eb wron

#

im basically making subway surfers and when the player dies I want the tracks to reset to their original position

#

and there are 6 different tracks

languid spire
rich adder
#

could use a dictionary

steep walrus
rich adder
#

yeah also, how did you write an array without knowing what you need array for lol

languid spire
steep walrus
#

alright

steep walrus
steep walrus
rich adder
#

have the objects register themselves to a dictionary stored in on 1 script

#

or have each object track their own original pos

steep walrus
#

okay, I havent used a dictionary before but Ill look it up

steep walrus
rich adder
#

you dont need dictionary for that one, just store a Vector3 on each object

languid spire
#
startPos = new Vector3[tracks.Length];

initialize the startPos array to an array of Vector3.zeros the same length as the tracks array

tracks = new Vector3[startPos.Length];

try to set the tracks array (which are GameObjects) to a new Vector3 array, which it cannot do

rich adder
steep walrus
steep walrus
rich adder
#

each object has their own script ?

steep walrus
#

oh okay I see

#

is that effecient? like there isnt an issue with having a different script on each object?

rich adder
#

Vector3 originalPosition
Awake() { originalPoisition = transform.position; }

rich adder
rocky canyon
#

same logic... different data

#

but yea, while ur learning nothing wrong w/ doing it the way ur most comfortable.. and then later on you'll adapt, less is more

magic panther
#

Can someone please tell me a better way to do this?
I need a GlobalGameManager script that just exists and loads scenes, stores global variables etc.. I also place a LevelInfo object with a LevelInfo script that is supposed to have a scene selected as nextScene and load it. When I tried to do this I found out that you can't serialize Scenes in unity, so I switched to strings. After that, it turned out these scripts have something massively wrong with them. I don't know how to do this, and google isn't helping.

GlobalGameManager script -> https://gdl.space/iweyatajog.cs
LevelInfo script -> https://gdl.space/voduyacosi.cs

lapis frigate
#

yo any1 can hop on vc for like 2 minutes and help me with a few general stuff please?

signal cosmos
#

Guys, I want to ask a modest question about the save/load system.

The problem is that it's registered as AsSingle, which means I use it in the LoadPlayerProgressState, and as a result, I can't save data from any part of the application anymore. What should I do?

willow scroll
lapis frigate
#

ok...

willow scroll
willow scroll
eternal falconBOT
#

:teacher: Unity Learn ↗

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

willow scroll
#

GameObject does not have a definition for getComponent, since methods in C# are written in PascalCase, which means, it's called GetComponent

willow scroll
lapis frigate
willow scroll
magic panther
#

I'm fine with that, just asking

willow scroll
#

You can add existing scenes by pressing a single button, but you'll have to do that after creating every new scene, since it's not done automatically

lapis frigate
#

aight I deal with a lot of small problems like that cuz my Visual studio doesnt show that redline when there is an error do u know how to fix that by any chance?

willow scroll
eternal falconBOT
willow scroll
magic panther
#

1sec

rich adder
lapis frigate
#

!Ide

eternal falconBOT
rich adder
lapis frigate
#

I just typed it 1 more time just to see if it will be the same for me

#

but its just 1 more time its not spaming

summer stump
willow scroll
lapis frigate
#

Allright sorry

#

Im new here and to unity in general so im just trying to figure out everything

pine bone
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class PlayerData 
{
    public static int coins;
    public static int level;
    public static List<string> ownedSkins = new List<string>();
    public static string equippedSkin;

    public static void AddSkin(string SkinID)
    {
        ownedSkins.Add(SkinID);
    }
}

Hello, i have a code like this that i will use to load players skin when they start a level. How can i create an AllSkins to get any skin by just providing name? Since the code is static i cant manually add all of my skin scriptable objects to the list

pine bone
#

and i load it back when they join

#

and i want it to be usable globally

rich adder
#

ig you don't know yourself why its static

pine bone
#

i want it to be usable globally

rich adder
#

so make a singleton and make the Instance itself static.

#

then you can put whatever you want in through the inspector

pine bone
#

should i make it a prefab and copy it into every single scene

rich adder
#

nah you can use DontDestroyOnLoad and persist it through diff scenes, just make sure its on a MB script

pine bone
#

thanks

rich adder
#

so basically make the containing class static instance then have playerData be serializable

pine bone
#

should i keep the coins and levels variables static

rich adder
#

they're already public

public class PlayerManager : MonoBehaviour
{
    public static PlayerManager Instance { get; private set; }
    [SerializeField] private PlayerData playerData;
    public PlayerData PlayerDataInstance => playerData;
    [Serializable]
    public  class PlayerData
    {
        public int Coins;
        public int Level;
        public List<string> OwnedSkins = new List<string>();
        public string EquippedSkin;
        public void AddSkin(string SkinID)
        {
            OwnedSkins.Add(SkinID);
        }
    }
}```
pine bone
#

what does => mean

slender nymph
#

expression body syntax. that is creating a get-only property

pine bone
#

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

public class PlayerDataManager : MonoBehaviour
{
    public static PlayerDataManager instance;


    [SerializeField] private PlayerData playerData;
    public PlayerData PlayerDataInstance => playerData;


    public List<string> AllSkins = new List<string>();

    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
        instance = this;
    }

    public void AddSkin(string SkinID)
    {
        playerData.ownedSkins.Add(SkinID);
    }
}

[System.Serializable]
public class PlayerData
{
    public int coins;
    public int level;
    public List<string> ownedSkins = new List<string>();
    public string equippedSkin;
}```

How does this look
rich adder
#

use a get only property with a instance check for any copies, just incase

rich adder
pine bone
#

i will

#

i accidentaly wrote string

#

why do i get this even though they have the same name

rich adder
pine bone
#

oh it was because of another script

#

thanks

#

@rich adder by the way why did you do something like this instead of making it public

thorny junco
#

my bro jumping twice :(((((((

rich adder
pine bone
#

whats the difference

timber galleon
#

How does one add knockback when an enemy attack is 2d

rich adder
# pine bone whats the difference

its mainly for self-protecting yourself or whoever writes code with you. Prevents mishaps, if you want to learn more read about "Encapsulation"

pine bone
rich adder
pine bone
#

i can still edit it

rich adder
#

wdym outside "the code"

#

its all code lol

#

are you talking about outside its own class?

pine bone
timber galleon
timber galleon
thorny junco
rich adder
# pine bone

make a method, make the PlayerData class modify the coins

pine bone
rich adder
rich adder
pine bone
thorny junco
rich adder
#

I was talking about the PlayerData itself
if you want whats Inside the PlayerData to have the same thing you would also use properties there (but you wont be able to use inspector so no reason to)

thorny junco
pine bone
#

doesnt this code edit the player data

rich adder
rich adder
thorny junco
rich adder
# pine bone same thing as what

i shown a quick example, you could technically do

private int coins;
public int Coins => coins;```
but you dont need to worry about this in beginning
pine bone
#

what does this do

rich adder
#

it would make it so only PlayerData can change coins

#

no other script can directly, only read it

#

like I said don't worry to much about it now, later on it might make more sense

pine bone
#

is it the same thing as doing private set public get

rich adder
#

yes

#

well you have a backing field here. edit ops fixed mistake

#

so it would just be closer to

private int coins;

public int Coins
{
    get { return coins; }
}```
frank flare
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AttachableItems : MonoBehaviour
{
    List<Collider> colliders;
    float oldTime = 0f;

    void Start()
    {
        oldTime = Time.time;
        colliders = new List<Collider>();
    }

    void OnTriggerEnter(Collider collider)
    {
        if (!collider.isTrigger)
            colliders.Add(collider);
    }
    
    void OnTriggerExit(Collider collider)
    {
        if (!collider.isTrigger)
            colliders.Remove(collider);
    }

}

how can I get List<Collider> colliders from another script? or should I do it that way? (this script is attached to gameobjects and the other one to the player)

rich adder
#

make a public property or a method
public List<Collider>GetColliders(){ return colliders; }. Right now its private

rich adder
frank flare
#

gets items near that item and gets them into colliders then from other script I would get add forces to 2 items to go near each other and combine them

#

actually I think I don't need attachableitems

#

because it's too messy that I don't know what I'm doing

rich adder
#

what is the game mechanic behind this exactly?

#

there is probably a better way

frank flare
#

there's this script

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

public class AttachItems : MonoBehaviour
{
    public GameObject item1;
    public GameObject item2;
    public Camera cam;

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp("e"))
        {
            var ray = new Ray (cam.transform.position, cam.transform.forward);

            if (Physics.Raycast(ray, out var hit)) {
                if (hit.collider.gameObject.tag == "Item" && hit.collider.gameObject.GetComponent<Rigidbody>())
                {
                    if (item1 == null)
                        item1 = hit.collider.gameObject;
                    else if (item2 == null)
                        item2 = hit.collider.gameObject;
                    
                    if (item1 != null && item2 != null)
                    {
                        Debug.Log("combining 2 items");
                        Debug.Log(item1 + " " + item2);
                        item1 = null;
                        item2 = null;
                    }
                }
            }
        }
    }
}

#

these 2 cubes are item1 and item2

#

on

if (item1 != null && item2 != null)
                    {
                        Debug.Log("combining 2 items");
                        Debug.Log(item1 + " " + item2);
                        item1 = null;
                        item2 = null;
                    }

I want these cubes be pushed to each other (so they're actualy attached) and attach

#

so that there's no space field in their center

rich adder
#

what does the list of colliders factor into this

#

are you going to use Fixed Joint to attach them ?

frank flare
steep rose
#

then why did you ask for a list of colliders

rich adder
#

i still have no clue the thought process behind it and why you need it

steep rose
#

from another script

frank flare
rich adder
#

I saw the setup but you didnt explain the mechanic you wanted to achieve there lol

steep rose
#

if you are planning to use a fixed joint or smth you need the rigidbodies

rich adder
#

yea if you want to attach them use fixed joint assign the rigidbodies dynamic, change your code to use the rigidbody

steep rose
#

or you could parent one to another thinksmart

rich adder
#

parenting doesnt work with rigidbodies sadly'

steep rose
#

and turn one RB off

#

that would work wouldnt it?

rich adder
#

you could make them both kinematic and parenting should work fine

steep rose
#

parent one to another and remove/turn off the child rb

rich adder
#

but no collisions

steep rose
#

ah

#

thats rough

rich adder
# frank flare the cube has rigidbody

also would change it to cs if (Physics.Raycast(ray, out var hit)) { if (hit.collider.CompareTag("Item") && hit.collider.TryGetComponent(out Rigidbody rb)) // do whatever with rb
eg item1 = rb

Rigidbody item1, item2

steep rose
#

kinda sucks you cant parent rigidbodies but i can see why, it might cause a ton of problems

rich adder
#

yea the physics are simulated in a different place iirc

#

unity just adapts what physx already has

#

moving transform disrupts that flow

#

fixed joint works like parenting, it just sucks at high velocities

steep rose
#

yeah thats true

#

also i had no idea unity uses PhysX

#

or if i did i forgot

rich adder
#

yup for 3d

#

2d its box2d

#

rewriting a whole physics engine would be time consuming

steep rose
#

😅

rich adder
#

it also has Havok if you're a Pro member

#

which is 😍

steep rose
#

Havok is really nice

rich adder
#

imo one of the best physics engines

steep rose
#

its just expensive

rich adder
#

not by much

meager sentinel
#

So i've been trying to make an enemy and a bullet for way too long now, i've followed a tutorial and adapted it to use velocity instead of rb force, i watched the docs of unity and i thought i was ready, but there's many problems, the firerate doesn't seem to be according to what i want, and the most important part is that the bullet is shot at a direction where the player isn't, sometimes it shoots backwards and other times it shoots to the side. https://hatebin.com/hccfnqykqg (ah yeah and the variables have weird names because, well, why not.)

steep rose
#

well if you factor in that you have to pay Havok and some other company to use it

frank flare
meager sentinel
steep rose
rich adder
meager sentinel
#

what's a short vid?

rich adder
#

dont quote me on it, its been a while 😅

steep rose
#

very cool

rich adder
meager sentinel
steep rose
#

what

meager sentinel
#

am barely running discord

steep rose
#

you dont have ram?

#

then your PC shouldnt be running (like it wont run)

rich adder
meager sentinel
steep rose
#

close them

meager sentinel
#

that slow down the pc too much

meager sentinel
rich adder
#

can you screenshot maybe

#

mainly interested in seeing the gizmos and all that

#

also why did you change it from velocity to translate?

meager sentinel
steep rose
#

translate will ignore collisions

#

btw

meager sentinel
#

but both dint work

#

and well i left the project for a while

rich adder
#

yeah translate will just phase the bullets through walls,

meager sentinel
#

the player is the capsule with a camera and the enemy is the more red one

#

idk if you wanted to see something in particular

#

am not good with english

rich adder
meager sentinel
rich adder
#

top left of scene view

meager sentinel
#

if you mean this then not

rich adder
#

well if you been setting everything up with that, it could explain why your directions are not what your code is doing

meager sentinel
#

wdym?

rich adder
# meager sentinel wdym?

and the most important part is that the bullet is shot at a direction where the player isn't, sometimes it shoots backwards and other times it shoots to the side.

meager sinew
#

why does an image in my canvas for 2d scale from a weird spot and not the middle of the canvas?

meager sentinel
#

well not "not work" (i dont know how would i say this)

rich adder
#

so all your transform.forward can be wrong or any other direction

rich adder
#

blue arrow**

#

the Forward of any gameobject

marble hemlock
#

fucking hate raycasts

rich adder
#

you're missing out, they're easy and powerful

marble hemlock
#

i am losing this battle

#

i cant even tell whats wrong

rich adder
#

me neither

marble hemlock
#

hold on

summer stump
marble hemlock
rich adder
#

and what exactly is supposed to happen vs whats happening ?

summer stump
#

Do CompareTag for one thing
Also add some debug logs to see where the code actually executes

rich adder
#

this is world dir btw Vector3.forward);

#

idk if thats intentional

marble hemlock
#

okay so when i get near the thing, it activates an image that says you can click it

summer stump
#

Very important consideration. No object rotation will be relevant to Vector3.forward
Probably want transform.forward

marble hemlock
#

thats what its supposed to do
however, for as long as im holding down any movement key, that prompt will stay up

#

or sometimes it'll just decide its not going to work
if i move towards the object from the side it just doesnt show the prompt

meager sentinel
marble hemlock
#

i feel like i need to record this

meager sentinel
#

Tried with velocity before and dont really remember how it works.

rich adder
#

your ray is always pointing the same direction

rich adder
marble hemlock
#

hold on let me catch up

#

okay so it only works when im facing a specific way, because its referring to the world's direction, and not mine

meager sentinel
summer stump
marble hemlock
#

Vector3 is never the solution 😔

summer stump
rich adder
#

the long version

marble hemlock
#

my brain will not process such a thing
not today

rich adder
#

Vector3 also useful for having proper direction of the world

#

if my character flips into a roll I wouldnt want transform.down to check for ground, i would use Vector3.down

marble hemlock
#

this is very much a losing battle on my end

#

something else broke but im reaching exhaustion

rich adder
#

well thats part of the job

#

endless UnityChanBugged chase

marble hemlock
#

joy

#

i think its redoing interactPrompt.SetActive(false); or true thing every time i move

rich adder
#

be glad those are the easy bugs that can be noticed right away and not hundreds of run where you get that edge case 🥲

marble hemlock
#

if i reach that point i might just have to accept that the project is doomed

rich adder
meager sentinel
marble hemlock
#

i kinda wanna use a box collider to do this now it feels way simpler notlikethis

its at least something i would have grasped

rich adder
marble hemlock
#

this collider touched that collider which means bad

#

wait no that would be good

meager sentinel
rich adder
marble hemlock
#

can't tell if im off to a bad start or not

#

i'll use the box collider and if i ever regain enough sanity to try to understand the raycast function better i will

rich adder
meager sentinel
rich adder
#

and whats going on

meager sentinel
#

bullet

#

and it's going a complete different direction to the player

rich adder
meager sentinel
rich adder
#

i said first step was to make sure all your pivots are correct

#

including the Shoot point

meager sentinel
#

Well the shoot point is the enemy itself

rich adder
#

well you should probably have one , put the look at on that one

meager sentinel
#

I'll try

rich adder
#

regardless, show it

meager sentinel
#

So i have to make another script for the shoot point right?

rich adder
#

not necessarily, just a Reference to its Transform

frank flare
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AttachItems : MonoBehaviour
{
    public Rigidbody item1;
    public Rigidbody item2;
    public Camera cam;

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

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp("e"))
        {
            var ray = new Ray (cam.transform.position, cam.transform.forward);

            if (Physics.Raycast(ray, out var hit)) {
                if (hit.collider.CompareTag("Item") && hit.collider.TryGetComponent(out Rigidbody rb))
                {
                    if (item1 == null)
                        item1 = rb;
                    else if (item2 == null)
                        item2 = rb;
                    
                    if (item1 != null && item2 != null)
                    {
                        Debug.Log("combining 2 items");
                        Debug.Log(item1 + " " + item2);
                        Vector3 direction = item2.transform.position - (item2.transform.position - item1.transform.position) * 2f;
                        item1.velocity = item2.transform.position - direction;
                        item1 = null;
                        item2 = null;
                    }
                }
            }
        }
    }
}

(the pain never stops)

how can I disable gravity while that item1.velocity happens and when it stops check if item1 and item2 are colliding and attach them (make them move like 1 thing)?

meager sentinel
frank flare
#

the pain never stops

rich adder
rich adder
meager sentinel
#

The one selected is the shootpoint, yeah, i reused the AI script, but only for trying, maybe it's that and im dumb

#

the blue arrow shows where the player is

frank flare
meager sentinel
#

like it is not there but on that way

rich adder
meager sentinel
#

like it seems to be pointing

rich adder
#

yes

meager sentinel
#

but shoots completely on other way

rich adder
#

which direction did you pass

#

for bullet

#

also now put the script back on the enemy , make a reference to the firepoint only for the lookat

#

then do this
Rigidbody rb = Instantiate(projectile, firePoint.position, firePoint.rotation;

#

rb.velocity = rb.transform.forward * bulletSpeed

meager sentinel
#

Ahh, all this mess only to make the bullet slower on slow motion

rich adder
#

wdym. This is actually important concepts in unity you should be aware of

#

especially knowing which arrow is what direction, World Space vs Local Space

#

your old code you're spawning bullet with Quaternion.identity, which means no Rotation

meager sentinel
#

I was following a course

#

worst 14$ ever spent ngl

rich adder
#

well paid courses are usually trash money grabs

#

unity has decent ones !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

meager sentinel
#

Yeah but i mean none of them are in spanish

rich adder
#

yeah sadly they dont really have text based tutorials as much, so they can't be translated easily..

solemn fractal
#

Hey guys.. when I create a getter or a setter. Is there any convencional naming for that? Because I always want to know if that is variable that I am getting or setting. Normally I use like "" public int PlayerCurrentHealthGetSet {get{return _playerCurrentHealth;} set{ _playerCurrentHealth = value;} }
"" But i find that naming ugly.

#

Like that: PlayerCurrentHealthGetSet

rich adder
#

or PlayerCurrentHealth

solemn fractal
rich adder
solemn fractal
#

Yeah I miss typed 😛

meager sentinel
#

goddamn it

#

it seems like i fixed it but somehow it broke the player

#

if the character crouches it goes at very high speed suddenly

#

and cant move

#

but how the hell would this script affect the player movement

rich adder
meager sentinel
rich adder
#

what did you change

meager sentinel
#

literally the 2 lines of code you gave me

#

but now it's bugged

#

now i wonder

#

what did i change without noticing

rich adder
#

this wouldnt mess with anything on the player

#

unelss your bullet is collding with player and causing some other issue there

meager sentinel
#

yup

#

that's it

#

it seems that it fires so fast that it makes the movement bug

rich adder
#

on the enemy or player ?

meager sentinel
#

player

#

even though it is set to trigger

#

if i deactivate the enemy it works normally

rich adder
#

not sure how that would ever mess with player then

frank flare
#

how can I apply on a rigidbody a mega super force and make it not ricochet from a wall or whatever it collides with? there should be a setting in rigidbody

#

I just want that effect temporarily

meager sentinel
rich adder
meager sentinel
#

also what the hell

#

i realized i disabled the attack from the enemy when it started bugging

#

and it stills attacks (shoots) even with it off

#

or smth

#

why the hell is enemy ai so hard

#

even when it is only shooting

rich adder
meager sentinel
#

it is off

rich adder
#

Update does not run with Disabled GameObject

meager sentinel
#

no i mean

#

i disabled the script part that spawned the bullet

#

adding the //

rich adder
#

this ?
Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>(); ?

#

or whatever

meager sentinel
#

yes

rich adder
#

did you actually save..and compile again..

meager sentinel
#

wdym?

rich adder
#

when you added // did you save the script and did it compile ? without errors

meager sentinel
#

yes

#

though there are errors that dont seem to appear in console

meager sentinel
#

in the scripts folder

#

there is like a red line

rich adder
#

uh what?

meager sentinel
#

that one

rich adder
#

looks like some type of custom editor thing, never seen that b4

meager sentinel
#

only the enemy folder has it

summer stump
#

I have never seen that before

meager sentinel
#

or what you mean idk

frank flare
#

can I do
IEnumerator something() {}
without initializing the function and then calling it?

meager sentinel
#

Oh yeah

#

i forgo

meager sentinel
#

it's fast script reload or something

slender nymph
meager sentinel
#

it's the only one i installed

rich adder
meager sentinel
#

if not it takes like 1 minute to add a ;

rich adder
#

you're relying on a third party to keep things always updated, and that wont break at some point

frank flare
# rich adder wdym without initilizing ?

for an example there's

IEnumerator SpawnItem(float posRange = 0, float posRangeDivide = 0, float pushPower = 0, int quantity = 1, float cooldown = 0)
    {
        Debug.Log("Trying to spawn an item");
        Debug.Log(posRange + " " + posRangeDivide + " " + pushPower + " " + quantity + " " + cooldown);
        GameObject sigma;
        for (int i = 0; i < quantity; i += 1)
        {
            sigma = Instantiate(itemToSpawn, Items.transform);
            sigma.transform.position = spawner.transform.position;
            float randomX = Random.Range(-posRange, posRange) / posRangeDivide;
            float randomZ = Random.Range(-posRange, posRange) / posRangeDivide;
            sigma.GetComponent<Rigidbody>().AddForce(new Vector3(randomX, pushPower, randomZ), ForceMode.Impulse);
            if (cooldown != 0)
                yield return new WaitForSeconds(cooldown);
        }
    }
IEnumerator SpawnItem(something)

can I do it cleaner?

meager sentinel
#

it has happened before i even installed it

#

idk how i fixed it tho last time

frank flare
rich adder
#

first of all id at least use String interpolation
this is wild
Debug.Log(posRange + " " + posRangeDivide + " " + pushPower + " " + quantity + " " + cooldown);
vs
Debug.Log($"{posRange}. {posRangeDivide}. {pushPower}. {quantity}. {cooldown}.);

short hazel
#

Optional parameters allow you to omit some of them, so you'll be able to do SpawnItem(cooldown: 10) for example

#

Another option is to create overloads - methods with the same name but different parameter counts or types

frank flare
# slender nymph do *what* "cleaner"

well for an example in lua you can

task.spawn(function()
print("amogus")
end)

instead of

function amogus_printer()
print("amogus")
end

task.spawn(amogus_printer)
#

that's what I want to do here

slender nymph
#

that's not "cleaner" that's just creating a delegate instead of using a method. i don't see how that would make your code any cleaner either

#

in fact that would do the opposite of making the code cleaner because you would be declaring the logic inline when creating the delegate instead of just using a method

frank flare
slender nymph
#

and yet that changes nothing at all about what i've said

frank flare
#

how can I do it like with

task.spawn(function()
print("amogus")
end)

tho?

meager sentinel
#

why the hell it is attackin g ahhh

#

literally deactivated everything that made it shoot

slender nymph
#

it is in no way cleaner and will likely result in more allocations so in every sense of the word it is worse

meager sentinel
#

50 minutes trying to fix a problem and i get even more problems

#

ahhhhhhhhhh

frank flare
#

ok

short hazel
# meager sentinel

Right-click AttackPlayer (not the commented one, the method definition), and choose "Find All References", that will list all the call sites, make sure there are none

#

Also check strings, maybe you have a Invoke("AttackPlayer", ...) somewhere?

languid spire
rich adder
polar acorn
meager sentinel
#

Okay, sorry for making yall waste your time

#

but somehow it is not updating

#

idk how

#

like i added a variable in public to realize

rich adder
#

oh so it was like I said, it never compiled..

meager sentinel
#

and i even restarted visual studio

rich adder
#

restarting vs doesnt fix compile errors

#

check there

meager sentinel
#

there aren't compile errors

#

only debugs of jumping

slender nymph
#

are you certain your hot reloading plugin hasn't actually somehow prevented it from compiling your changes?

short hazel
#

Make sure you saved and that there's no errors across the entire project.

meager sentinel
#

let me try saving another variable

rich adder
#

yeah that asset is probably messing with autocompile

short hazel
#

Then, try moving the file to another folder and back (from Unity) to force a compiler pass

rich adder
#

^ this , can also right click project view / file hit Reimport

meager sentinel
#

doesn't seem to be caused by the error

#

like the script

#

so i think it may be needed to reimport as you said

#

Soo, Navarone, the code that you gave me is weird

#

what should firePoint be?

#

A transform or a gameobject

#

both give errors

#

Well, idk if transform gives error

#

It says cannot convert unitygameobject to rigidbody

rich adder
#

[SerializeField] Transform firePoint

#

drag n drop in the inspector

#

firePoint.LookAt(target)
etc.

meager sentinel
#

39 is the code you gave

rich adder
meager sentinel
#

but the one you made

rich adder
#

change projectile's type to Rigidbody

#

you have to drag bullet inside inspector again when you change it

#

you will get Mismatch or Missing

frank flare
#

https://gdl.space/okezinoxol.cs

IEnumerator BringAndAttach()
    {
        Debug.Log("itgwerogerjoererjgoierjgeroig");
        Vector3 direction = item2.transform.position - (item2.transform.position - item1.transform.position) * 2f;
        item1.velocity = item2.transform.position - direction;
        Debug.Log(direction);
        item1 = null;
        item2 = null;
        yield return new WaitForSeconds(0.5f);
    }

how can I predict time that will take item1 to reach item2 and put it into WaitForSeconds? (the time item1 takes to reach item2 is always the same)

slender nymph
#

that waitforseconds is 100% pointless because it waits to do literally nothing at all

slender nymph
#

okay well why not just use a loop and a yield return null instead

#

then for your loop you just check if the object has reached its desired destination or whatever condition you want

frank flare
slender nymph
#

then the statement "the time item1 takes to reach item2 is always the same" is categorically false

meager sentinel
#

So now bullets get destroyed

#

after getting created

meager sentinel
#

and the ones that dont dont move

frank flare
slender nymph
#

okay well the magnitude of the velocity is the number of units per second it will move

rich adder
warm raptor
#

Hello I'm made this script that create a new player when someone join the game we are in , but I don't know why, the script can find the bone "Bone.002" of my player and I don't know why

if(!Players.ContainsKey(newID))
            {
                var playerInfo = new PlayerInfo { Health = 100, Kills = 0, Coordinates = "0", PreviousLivingState = "1", PreviousTeamState = "0", ArmRotation = 0f};
                Players[newID] = playerInfo;
                player = Instantiate(PlayerPrefab, new Vector3(10, 10, 10), Quaternion.identity);
                player.name = newID;
                Players[newID].Player = player;
                Players[newID].BackBone = player.transform.Find("Bone.002").gameObject; //--> this is the line that don't work
                Players[newID].PlayerAnimator = player.transform.GetChild(0).GetComponent<Animator>();
                Players[newID].PlayerAnimator.enabled = true;;
            }
main karma
#

I use a RenderTexture, that has a custom shader on a 3D plane, how would I flip it horizontally after the custom shader but before displaying it? (not sure where to ask this question)

slender nymph
warm raptor
zenith cypress
frank flare
wild rampart
#

hey guys how can i fix this

main karma
# zenith cypress If you just want it horizontally, you could just invert the uv axis you need sin...

for some context, I got a custom shader from a youtube tutorial for my portals that makes sure that it only fits in the portal the part of the image that my character can see through the portal, and I either need to mirror the camera that takes the picture, or somehow include a function in the shader or in code that allows me to flip it after it does all of the fitting stuff
this is the shader, and ideas?


Shader "Unlit/ScreenCutoutShader"
{
    Properties
    {  
        _MainTex("Texture", 2D) = "white" {}

    }
        SubShader
    {
        Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
        Lighting Off
        Cull Back
        ZWrite On
        ZTest Less

        Fog{ Mode Off }

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                //float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
                float4 screenPos : TEXCOORD1;
            };

            

            v2f vert(appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.screenPos = ComputeScreenPos(o.vertex);
                return o;
            }

            sampler2D _MainTex;

            fixed4 frag(v2f i) : SV_Target
            {
                i.screenPos /= i.screenPos.w;
                fixed4 col = tex2D(_MainTex, float2(i.screenPos.x, i.screenPos.y));

                return col;
            }
            ENDCG
        }
    }
}
#

I honestly don't really get how shaders work

#

so any help would be, well... helpful

rich adder
zenith cypress
waxen adder
#

Is there some way to get a navmeshagent to calculate a path to a destination, but without actually moving to it? iirc as soon as you do SetDestination, it immediately starts going to the location

sleek gazelle
# frank flare the pain never stops

Hey, I'm not really sure of what you're trying to do here but you could:

void OnCollisionEnter(Collision collision)
{
if(this.gameObject.GetInstanceID() > collision.gameObject.GetInstanceID()){ //Makes sure the code only triggers for one of the two cubes, there might be better alternatives
   collision.gameObject.transform.SetParent(this.transform); //set the parent to be the first cube
   collision.gameObject.GetComponent<RigidBody>.isKinematic = true; //set the rigid body as kinematic

this.enabled = false; //disable this code for this cube
}
}

I'm not sure this is the exact syntax tho

runic urchin
#

hey, anyone know how to change the speed that my sprite animation is at in code? i want to do the code in my movement script but i dont exactly know how to change the speed of it from there.

sleek gazelle
runic urchin
#

i was able to figure it out lol, thank you so much!

sleek gazelle
#

No problem

surreal plover
#

Guys I have a question

#

Im trying to open my scripts from unity

waxen adder
#

Reword: how can I tell if a NavMeshAgent has reached its destination? As well as if it's still in the process of getting to the destination

surreal plover
#

But it no longer has the build option when I open it

waxen adder
#

Gotcha, ty!

frank flare
#

plus with that script I would also have to make another script and attach it to the body which will make things messier and harder...

sleek gazelle
sleek gazelle
warm raptor
#

Hello, is there a way to make a defined component run at a specific time in my code? I'd like a parent component to run at the very end of each frame, after the late update.

sleek gazelle
warm raptor
#

what is it? we never know maybe it could help me 😄

sleek gazelle
warm raptor
frank flare
#

not through a loop way (oncolliderenter is a loop way)

sleek gazelle
sleek gazelle
frosty hound
#

There is no way to know when to check if a collision happens without checking if a collision happens.

#

How are you supposed to "know" when to check otherwise?

frank flare
warm raptor
frosty hound
#

You can do an overlap cast and check, yes

frank flare
#

if ... then

frank flare
frosty hound
#

Whatever shape fits your situation

frank flare
#

hmm, overlapsphere might be better

waxen adder
#

Came up with an interesting way to use a navmesh for grid movement, bypassing a lot of coding in the process (A* and others).

Ran into a problem with the pathfinding though. In the image, the wire cubes are what is recorded as the corners for the NavMeshPath. Start position is where the capsule is and end position is on the furthest left wire cube. For some reason, the agent wants to go around through the bottom, with what seems to be a very unecessary "corner" in between the two ones that matter. ON TOP OF THAT, for some reason, it does not want to take a path on the northern part of the wall, which should be shorter. Any thoughts?

#

For additional context, the center of these corners are where the agent gets its destinations individually set to, essentially creating grid movement, but via the Unity navigation system

#

Oh, hm. Looks like messing with voxel size helped out. Set the ratio from 2.00 per agent radius to 4.00

plain garden
#

How to GetComponent the X-Position?

#

IDE is Visual Studio btw and I did try and troubleshoot with the API

frank flare
#

are there Physics.OverlapBox gizmos?

plain garden
steep rose
frank flare
plain garden
plain garden
eternal needle
steep rose
#

i suggest you use docs next time for GetComponent

rich adder
plain garden
plain garden
main karma
steep rose
fading mountain
#

Hey guys. I'm having a wierd problem where the bullets coming out of my gun are following the rotation of the player when it moves AFTER being instantiated. I've looked through all my code multiple times and I can't find the issue.
I have three scripts (relatively small):

  1. PlayerMovement (attached to the player) https://gdl.space/iliratoyin
  2. Gun (attached to the player) https://gdl.space/iropupadec.cs
  3. Bullet (attached to the bullet prefab) https://gdl.space/neqezunugo.cs
    if you need more info see the video:
deft grail
#

and bullet spawn point

#

since the player is moving, so is the bullet

fading mountain
#

wow

#

thank you so much lol

hallow sun
#

yeah just remove the last value on that instantiate which sets the parent

fading mountain
#

I think it's better to just make the bullet spawn point a seperate object

deft grail
#

so its fine and should leave it a child

fading mountain
#

I can set its position to the position of the player when ShootBullet() is called

deft grail
#

just make it a child

fading mountain
#

you know actually I think Faywilds is right

#

I dont even need the bullet spawn point to begin with

#

I deleted that and made the spawn point position the player, and removed the parent

deft grail
fading mountain
#

as of right now they are just in the hierarchy

#

which is what he said

stark summit
#

Im having a issue with my camera and my movement

flint barn
#

Hey, so I finally got a chance to work on my game. I removed the camera that was a child of the player and I now have a script that searches for the player and makes it follow them. However, this only works for the first player, for the 2nd the camera is stuck.

#
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using Unity.Netcode;
using Cinemachine;

public class CameraScript : NetworkBehaviour
{
    public GameObject cameraTarget;

    private CinemachineVirtualCamera vcam;

    

    public override void OnNetworkSpawn()
    {
        if (!IsOwner)
        {
            gameObject.SetActive(false);

        }
    }


    private void Start()
    {
        vcam = GetComponent<CinemachineVirtualCamera>();


       

    }

    private void Update()
    {
        cameraTarget = GameObject.Find("Player(Clone)");

        if (cameraTarget != null)
        {
            vcam.Follow = cameraTarget.transform;
        }
    }
plain garden
#

Another dumb question.

How do I make variables accessible through all scripts?

eternal falconBOT
plain garden
#

let me pull it up hold on

steep rose
#

!ide

eternal falconBOT
steep rose
#

public for sure exists

#

or else i am crazy

summer stump
#

Perhaps you wrote Public instead of public?

plain garden
summer stump
#

You have the method collapsed, uncollapse MovePlayer
Show line 23

steep rose
#

you didnt access your script

#

nvm

summer stump
#

Oh, this is a completelh differe script.

steep rose
#

you are not accessing movement

summer stump
#

The error is in EnemyScript
Everything you showed is completely irrelevant

rich adder
plain garden
summer stump
rich adder
#

also you have nested MB classes..

steep rose
#

so of course it wont work

summer stump
#

Oh damn. Awful screenshots on mobile. I see the script now
This is why screenshots suck

steep rose
plain garden
summer stump
#

But the issue is that you never referenced the Movement script as dec said. You need to do something like
public Movement movement;

movement.xPos

ObjectReference Dot Variable

https://unity.huh.how/references

steep rose
#

you got to it first

#

how

summer stump
steep rose
#

you have the website loaded lmao

rich adder
#

its also pinned in this channel

steep rose
#

where?

rich adder
steep rose
#

ah

#

thats nice to know, ty nav

steep walrus
#

I've been trying forever to get this to work but I just can't figure it out. No matter what I do I try to make it so when my player hits an obstacle by entering its collider box with an OnTriggerEnter method and then calling a method from another script that resets the position of certain objects in my scene.

using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design.Serialization;
using UnityEngine;
using static Track;

public class Obstacle : MonoBehaviour
{
    Track trackScript;

    void Awake()
    {
        trackScript = GetComponent<Track>();
    }

     void OnTriggerEnter(Collider other)
    {
        trackScript.ResetPosition();
    }
}
#
public void ResetPosition()
    {
        left.transform.position = startPosL;
        middle.transform.position = startPosM;
        right.transform.position = startPosR;
    }
#

Then I get an error that says "Object reference not set to an instance of an object" on the line "trackScript = GetComponent<Track>();"

#

I've tried so many things and just can't figure out how to avoid the null reference

wintry quarry
#

Anyway it seems very strange that TrackScript and Obstacle would be on the same GameObject so that code is almost certainly not correct

stark summit
#

So my character moves in the direction of the camera but eh camera is stuck where the player is facing instead of the player looking where the camera is

steep walrus
#

also I swear it says the same line number im 100% sure

wintry quarry
wintry quarry
#

Show the actual full error message

steep walrus
ivory bobcat
#

Track script was null

#

Show the inspector for that game object

#

GetComponent would return null and would assign that null to the track script if there isn't a track script component in that game object.

faint agate
#

Hello, so im trying to make player look in a certain direction on start. When I press start, my camera is reset to 0 and looking in the direction the mouse was last left at on the screen(ex. If mouse was top left of screen on start, the fps cam will be looking top left).

#

i tried getting rid of cursor lock but it didnt help

#

this script is attached to the camholder and Transform cameraPosition is on the player

wintry quarry
#

So your "100% sure" was wrong

#

Anyway it's as I mentioned, your code doesn't make sense. I would expect you to get the script from the object you collided with, not this same object

tranquil zealot
#

hey i need some help, i was making a game about combat with colours and i got stuck in a really weird technicality. so basically, what i was trying to create, was a combat system, where the longer i hold space, the bigger and slower the attack "blob" is, and the shorter i hold space, the small and faster the blob is. but what the error is, is that sometimes, the blob first comes out big and fast, and right after that, no matter how long or short i hold space, the blob comes out small and slow. here's the code -

frosty hound
#

@tranquil zealot !code on how to share code here. Don't just dump it.

eternal falconBOT
frosty hound
#

You're meant to read the message, not parrot what I wrote.

tranquil zealot
#
public class PlayerAttack : MonoBehaviour
{
    public Animator animator;
    public Transform attackPoint;
    public LayerMask enemyLayer;

    public GameObject prefabBlob;

    public BlobScript blobScript;

    bool isBlack;
    bool isWhite;
    bool isRed;
    bool isYellow;
    bool isBlue;

    GameObject instantiatedBlob;
    Renderer blobRenderer;

    float startTime;
    float endTime;
    public float totalTime;

    void Update()
    {
        ChangeBrushColor();

        if (Input.GetKeyDown(KeyCode.Space) && instantiatedBlob==null) 
        {
            animator.SetBool("isAttack", true);
            startTime = Time.time;
        }
        if (Input.GetKeyUp(KeyCode.Space) && instantiatedBlob==null)
        {
            endTime = Time.time;
            totalTime = endTime - startTime;

            if(totalTime > 0.7f)
            {
                totalTime = 0.7f;
            }
            if(totalTime < 0.1f)
            {
                totalTime = 0.1f;
            }

            Debug.Log(totalTime);

            Attack();
            startTime = 0f;
            endTime = 0f;
            totalTime = 0f;
        }
    }

    void Attack()
    {
        animator.SetBool("isAttack", false);

        instantiatedBlob = Instantiate(prefabBlob, attackPoint.position, attackPoint.rotation);
        blobRenderer = instantiatedBlob.GetComponent<Renderer>();

        blobScript.speed = (1f - totalTime) * 15;
        instantiatedBlob.transform.localScale = new Vector3(0.3f + totalTime, 0.3f + totalTime, 1f);
summer stump
#

Unless you set it to null somewhere else?

#

Why even check whether it is null in update?

faint agate
#

Hello, so im trying to make player look in a certain direction on start. When I press start, my camera is reset to 0 and looking in the direction the mouse was last left at on the screen(ex. If mouse was top left of screen on start, the fps cam will be looking top left).
https://gdl.space/etapuxitoy.cs
i tried getting rid of cursor lock but it didnt help
https://gdl.space/uxaziwezay.cs
this script is attached to the camholder and Transform cameraPosition is on the player

tranquil zealot
summer stump
steep walrus
#

and not constructive

wintry quarry
steep walrus
wintry quarry
#

Be more humble, less confident, since it's the beginner chat.

acoustic arch
#

is it a bad habit to not feel like learning and using some of unities tools like with IDragHandlers, and instead just making my own item to mouse drag

#

i just made my own for my game cause i was too lazy to look into unities and i prefer it i suppose

steep walrus
acoustic arch
#

besides it's a chat for programming why argue? just get to the facts

summer stump
steep walrus
steep walrus
acoustic arch
steep walrus
#

my point is there is a better way to get that point across

summer stump
acoustic arch
#

my teachers in school could use that lesson tho 💀

steep walrus
#

and didnt point out what I was missing and just said where I should get the script which I dont know how to do

#

I tried fixing this problemon my own and came to this server as a last resort. im not js coming here as my first resource

#

reacting to a message with an x is literally the definition of non constructive criticism

summer stump
#

Well, he is unlikely to continue helping after the insults, I will not either. He was not condescending. You could have just asked for clarification, instead of attacking people for no reason. Literally no one was anything but polite and helpful to you before whatever this was
Just gonna block.
Please watch your behaviour before mods take action

steep walrus
#

I dont want anyone helping me that is condescending so that works idrgaf if i get blocked

steep walrus
#

i hope the mods take action against me for pointing out condescension

#

you can @ them if you want

acoustic arch
steep walrus
acoustic arch
steep walrus
acoustic arch
acoustic arch
steep walrus
acoustic arch
steep walrus
simple fjord
languid spire
eternal falconBOT
simple fjord
languid spire
#

use a paste site as the bot says

simple fjord
languid spire
#

no, you post your code to the pastesite then you post the link to that here

languid spire
simple fjord
#

could you tell where

languid spire
#

Well I dont know your data or setup so no, but basically start with everywhere

marble hemlock
#

ok so it took a while and i figured out how ray works and i got it drawing the ray

#

we making progress i think 👍

#

only took me

marble hemlock
simple fjord
#

also get @timber wedge banned for this inappropriate message

marble hemlock
#

that black line coming from the camera

languid spire
marble hemlock
#

thats the only ray coming out of it right?

#

that just needs to hit something for it to detect?

languid spire
bold nova
#

Hello everyone. I tried to subscribe SessionManagers method GameOver to a unityEvent in the EnemyManager OnRechingfinishLine.

public UnityEvent OnReachingFinishLine;

Do you know why this is wrong?

FindAnyObjectByType<EnemiesManager>().OnReachingFinishLine += GameOver;
CS0019 Operator '+=' cannot be applied to operands of type 'UnityEvent' and 'method group' 

But this is just fine?

        FindAnyObjectByType<EnemiesManager>().OnReachingFinishLine.AddListener(GameOver);

aren't those the same statements?

marble hemlock
#

i actually dont know how to go forward from here

#

raycasts kinda have me cooked

eternal needle
willow scroll
languid spire
willow scroll
#

Seems like to will have to check the stack trace for each

marble hemlock
#

something is severely wrong im gonna

languid spire
marble hemlock
#

oh

simple fjord
#

i actaully tried

marble hemlock
#

did you go to unity.learn

#

or learn.unity

#

whatever the order is

languid spire
simple fjord
#

@devs can sm1 else help this guy is rachet

#

i was just curious on what variables i could displaye

marble hemlock
#

they have great resources and honestly its better than just trying at random tutorials with rough explanations because they either A) expct you to be pretty far in understanding or B) don't really explain wha they're doing and simply just tell you to follow

timber wedge
marble hemlock
#

in my attempt to record the problem
i have found the problem

i was noticing that whenever i looked down, the raycast was triggering "hey something is in the way", and i couldnt figure out why, and i thought it was the floor

#

but no the raycast was hitting the player, which i tagged an interactable for some reason

#

wait ive just reverted back to another problem fuck

simple fjord
timber wedge
#

):

marble hemlock
rich adder
# marble hemlock im not even sure whats going on here
void Update()
    {
        RaycastHit hit;
        Ray ray = new Ray(cam.transform.position, cam.transform.forward);
        Debug.DrawRay(ray.origin, ray.direction * interactRange, Color.black);
        if(Physics.Raycast(ray, out hit, interactRange))
        {
            if(hit.collider.tag == "interactBlock")
            {
                Debug.Log("Something is in the way");
                interactPrompt.SetActive(true);

            }
            else
            {
                interactPrompt.SetActive(false);
            }
        }else {
            interactPrompt.SetActive(false);
        }
    }```
marble hemlock
#

i might be doomed

#

it fixes the problem, thank you, but now its freaking out whenever i move
i mean it was doing it before but now its doing it all the time

#

raycasts are hard

simple fjord
#

@timber wedge apologize

#

now

timber wedge
#

im sorry ):

simple fjord
#

good boy

willow scroll
strong wren
#

@timber wedge @simple fjord Both of you can stop this sort of stuff. This really isn't the server for this.

marble hemlock
#

whenever i move it just

#

idk

timber wedge
marble hemlock
#

the raycast is still colliding with the interactBlock but whenever i move the player's position, it just bleh

#

well

willow scroll
#

Could you, perhaps, describe the issue?

marble hemlock
#

i have a debug log that whenever the ray cast is hitting the thing tagged interactBlock, which is the white rectangle thing over there, it'll say that something is in the way

#

and if something is in the way, it will show an image prompt

#

the problem is that whenever i start moving, even if the raycast is colliding, it starts to just spaz out

#

im not even sure what exactly is the problem

#

moving the camera seems to have no issue

willow scroll
marble hemlock
#

the problem seems inconsistent

#

the problem seems most notably whenever i get close to the object hold on

short hazel
#

From the video, it only seems to detect the white object when you're not moving

marble hemlock
#

yeah

#

i dont know why

#

it notably gets worse whenever i get close to the object

short hazel
#

Which could mean the raycast hits the player first
I would debug the raycast position and direction using the physics debugger

willow scroll
#

Yeah, your player also has the tag "interactBlock"

marble hemlock
#

that was causing a problem earlier but i did fix that

#

whenever i looked down it would cause it to immediately trigger

willow scroll
marble hemlock
#

Ray ray = new Ray(cam.transform.position, cam.transform.forward);

Well the raycast positionand direction is based on the camera, which i named cam, and whichever way "forward" is for the camera

#

this is rough

short hazel
#

Show the code that executes the raycast

marble hemlock
#

oop wait

#

was slightly redone

marble hemlock
willow scroll
#

Here, under this condition

if(Physics.Raycast(ray, out hit, interactRange))

print

$"name: {hit.collider.name}; tag: {hit.collider.tag}"
marble hemlock
#

something had to be changed because earlier whenever the player looked away it kept it on screen until they looked around

short hazel
#

And you already have a Debug.DrawRay, good

marble hemlock
#

i dont know what that means notlikethis

#

not the draw

short hazel
#

Put the string in a Debug.Log, I guess

willow scroll
#

Yes, I have mentioned printing it, which means using the print method

marble hemlock
#

that would explain why i dont know what it means 😭

willow scroll
#

Use the MonoBehaviour.print method to print the message I've shown above

fiery badger
#

Hi guys I have this read only error, what should I do?

short hazel
#

print() is roughly a shorthand to Debug.Log()

willow scroll
#

Which can only be used on MonoBehaviours, and calls Debug.Log inside of it

marble hemlock
#

give me a moment my head is struggling with this

willow scroll
#

How is your head struggling with printing a message to the console?

short hazel
marble hemlock
#

up until this point ive only been referred to debug.log, so print is new to me
im not fully understanding its purpose but im trying to read the documentation on it

willow scroll
#

You have to set the string fully

short hazel
#

Yeah you cannot change a single string's character via the indexer str[i]

#

You can get the character at this position, but not set it

willow scroll
fiery badger
#

I see thanks

marble hemlock
#

okay i just started tagging everything i can

#

its hitting... something

#

im not sure what it is yet, but we're getting there

elder condor
#

can i have help pls

short hazel
eternal falconBOT
elder condor
#

do u flicker goon or jelq

short hazel
#

What

languid spire
marble hemlock
#

an alt

#

odd

short hazel
#

Ah, some slang I'm not aware of?

marble hemlock
#

or perhaps a friend of theirs

simple fjord
marble hemlock
#

okay its hitting something related to the player

elder condor
thorny junco
#

"Hello, friends. I have a question that's been on my mind. When I can't remember how to write a certain code (like how to create a timer... etc. ) or when a question pops into my head, should I research it on the internet or use ChatGPT? Which would be more beneficial? ChatGPT really speeds up the process.

elder condor
#

ermm what the sigma

timber wedge
#

mb flickered a little too close to the sun

marble hemlock
#

i think its hitting the player position object

hollow sedge
#

Guys pls keep it proffesional this is a unity server

simple fjord