#💻┃code-beginner

1 messages · Page 382 of 1

rocky canyon
swift crag
#

use Mathf.Repeat(angle, 360) to get this into the 0..360 range

rocky canyon
#

but my code is jank.. it has 8 different if statements

swift crag
#

here, look at how I'm doing it for my radial menu

zealous hatch
swift crag
#
                float baseAngle = Mathf.Atan2(stickDir.y, stickDir.x) * Mathf.Rad2Deg;

                float angle = baseAngle + 360f / 2 / segments.Count;
                angle = Mathf.Repeat(angle, 360);

                chosenIndex = Mathf.FloorToInt(angle / (360f / segments.Count));
#

The offset on the second line is there because my first radial menu segment is centered at 0

#

so if there are four segments, -45 to 45 should count for segment 0

rocky canyon
swift crag
#

thus I add 45 to get 0..90

#

and then divide by 90 and floor to int to get 0

rocky canyon
rich adder
rocky canyon
zealous hatch
rocky canyon
#

yea his code is better than mine

#

💯

zealous hatch
#

haha

#

its pretty cool what you made tho

rocky canyon
#

for a doom clone

rich adder
rocky canyon
#

amazing how hard it is to make games retro.. u have to fight against the engine alot of the times

#

lol

rich adder
#

always wanted to work on a 2.5 in fps

rocky canyon
rich adder
#

i only know basic billboarding, wouldn't have thought to make the 8 way sprite

rocky canyon
#

heres my 8 sided rotation code.. prepare to laugh, or cry

rich adder
#

ohh SignedAngle. How did I miss this function?

timber tide
#

it boils down to a switch statement anyway

swift crag
#

Mathf.Repeat helps there.

#

Mathf.Repeat(-1, 3) gives you 2

#

it does what the % operator should do (modulo)

#

% is actually the remainder operator

#

Grumble grumble

quick kelp
#

hello quick question

rich adder
#

hi quick question!

quick kelp
#

can different script have the same bool name
but specifically be told which one is true and not true if given serialized reference

rich adder
#

they are separate classes

quick kelp
#

ok thank you thats all i needed to know

river pecan
#

I'm trying to use runtime mesh creation to make a line of sight, I am confused on how the mesh vertex positions are set. I'm currently trying to get the mesh to resemble a cone currently however it doesn't follow the players sight. When the player is facing north, it works normally, when they face east the cone faces south, etc.

    void Start()
    {
        mesh = new Mesh();
        meshFilter.mesh = mesh;
        angleIncrease = fov / rayCount;
    }

    void Update()
    {
        Vector3 origin = transform.position;
        Vector3[] verticies = new Vector3[rayCount + 2];
        Vector2[] uv = new Vector2[verticies.Length];
        int[] triangles = new int[rayCount * 3];
        int vertexIndex = 1;
        int triangleIndex = 0;
        verticies[0] = transform.InverseTransformPoint(origin);
        transform.localEulerAngles = new Vector3(0, fov / -2, 0);
        for (int i = 0; i < rayCount; i++)
        {
            Vector3 vertex;
            transform.position = transform.InverseTransformPoint(origin) + transform.forward * maxRange;
            vertex = transform.position;
            verticies[vertexIndex] = vertex;
            if (i > 0)
            {
                triangles[triangleIndex] = 0;
                triangles[triangleIndex + 1] = vertexIndex - 1;
                triangles[triangleIndex + 2] = vertexIndex;
                triangleIndex += 3;
            }
            vertexIndex++;
            transform.localEulerAngles += new Vector3(0, angleIncrease, 0);
            transform.position = origin;
        }
        transform.localEulerAngles = Vector3.zero;
        mesh.vertices = verticies;
        mesh.uv = uv;
        mesh.triangles = triangles;
    }
#

I know this code must look a bit jarring but I'm still trying to learn how the verticies handle their positions being set

thick nexus
rich adder
rocky canyon
#

exit time or a long transition

rich adder
#

probably the URP one

thick nexus
rich adder
#

Oh was saying the made it URP only but you can still convert materials ig

#

actually idk the one in asset store says v1.1.0

#

so you're using a newer one

rocky canyon
#

you'll be able to get the controller working

rich adder
#

you probably dont have the latest for 6

#

yeah because in asset store is called
Starter Assets: Character Controllers | URP

#

just click this

#

updating should fix deprecated warning

#

wait it wont link to it nvm

zealous hatch
#

haha opkay

#

ive got what i wanted but its the most yucky code ever

#

!code

eternal falconBOT
zealous hatch
#
   //Sprites
   public Sprite Look1;
   public Sprite Look2;
   public Sprite Look3;
   public Sprite Look4;
   public Sprite Look5;
   public Sprite Look6;
   public Sprite Look7;
   public Sprite LookDown1;
   public Sprite LookDown2;
   public Sprite LookDown3;
   public Sprite LookDown4;
  var dir = (mouseWorldPos - (Vector2)transform.position).normalized;
  var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;

  Debug.Log("Direction" + Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg);

  if (angle <= 90 && angle >= 72)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = Look7;
  }
  else if (angle <= 72 && angle >= 56)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = Look6;
  }
  else if (angle <= 56 && angle >= 47)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = Look5;
  }
  else if (angle <= 47 && angle >= 26)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = Look4;
  }
  else if (angle <= 26 && angle >= 12)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = Look3;
  }
  else if (angle <= 12 && angle >= 7)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = Look2;
  }
  else if(angle <= 7 && angle >= 5)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = Look1;
  }
  else if (angle <= 4 && angle >= -6)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = LookDown1;
  }
  else if (angle <= -7 && angle >= -36)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = LookDown2;
  }
  else if (angle <= -37 && angle >= -71)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = LookDown3;
  }
  else if (angle <= -72 && angle >= -90)
  {
      Body.gameObject.GetComponent<SpriteRenderer>().sprite = LookDown4;
  }



#

dont suppose anyone has a better approach to thing 😭

#

i also need it to flip the sprite and do the same thing when mouse is on other side

#

fyi, this is meant to play different sprites of a charcter depending on the angle of the mouse to the player. It does this. But if i were to do the other side it would be like 30 if statements

wintry quarry
zealous hatch
#

how would i use a array for this?

wintry quarry
#

And structs

zealous hatch
#

store the sprites?

wintry quarry
#

Put all the angles and sprites in an array

#

Loop through the array to find the appropriate angle range/sprite

#

You can put the sprite+the angles in a struct in an array

#

Or if it's mathematically based you can just calculate the angles from your for loop too

sick musk
#

What's the simplest way to do a boxcast identical to a box collider?

rich adder
#

pass the size of box collider in the parameter ?

sick musk
#

What

wintry quarry
#

Really this whole thing should be about 6 lines of code

#

Maybe 12

sick musk
#

You can't

rich adder
wintry quarry
wintry quarry
zealous hatch
#

any good resources for learning structs

sick musk
#

Where?

rich adder
eternal needle
#

this is the kind of code people joke about when they say they are on line 500 thousand of their "even or odd calculator"

eternal needle
#

look at the properties it has

sick musk
#

Do you mean to pass in the same values?

#

Well yeah

#

I was asking about an easier way

rich adder
#

so then whats the problem ?

sick musk
#

also it seems to be off

rich adder
#

that is the easy way

sick musk
rich adder
#

also note the size is halfExtents

sick musk
#

So just / 2?

rich adder
#

so you want check.size/2

sick musk
#

oh

#

yeah

zealous hatch
#

so would i make a struct that hold a int(degree) and then a sprite(my image) and then stick them in a array. Then do a for loop to find which genre it fits in

rich adder
#

wouldnt a dictionary be easier nvm

rich adder
#

i wrote that but idk might be too hard for them adding values xD

gaunt ice
#

Many to one mapping (finding a range), dictionary not help

polar acorn
rich adder
#

or implement IEquatable 😮

gaunt ice
#

The most easiest way is to use loop to iterate an array or list, ordered set is overkill
Why not just use a list?

swift crag
#

You need to turn an angle into an index

#

your input is in the 0..360 range, and let's say you want to produce a value in the 0..10 range

#

(both are exclusive ranges)

rich adder
swift crag
#

divide the input angle by (360 / 10) -- so, 36 -- to go from the first range to the second range

wintry quarry
sick musk
#

I had this I was just looking for an easier way

zealous hatch
gaunt ice
#

The problem is i have a point and i want to find out the range/interval that contains the point
Then difference between two end points seem to be 18, Fen solution work btw, just angle/18 (note that it can be negative so you hvae to offset it) then use it as an index to access the array

zealous hatch
gaunt ice
#

Oh i misread…

swift crag
#

If you don't use the full 0..360 range, then you can just do something like this

#
float t = Mathf.InverseLerp(lowEnd, highEnd, angle);
int index = Mathf.FloorToInt(t * numberOfChoices);
#

InverseLerp tells you how far along you are between two values

#

in the 0..1 range

#

then you multiply by the number of choices and floor that

gaunt ice
#

the ranges are not the same, 18 35 30 11 ….

swift crag
#

ah, you're right

#

i look very silly right now

#

then just loop over it yeah

#

since there's no straightforward function to map from an angle to an index

rich adder
zealous hatch
#

okay

rich adder
#

also put the [System.Serializable] Attribute above it so you can change it in the inspector

zealous hatch
#

ill give it a go

#

would this not mean i would have like loads of those struct things

zealous hatch
#

like one for every sprite?

rich adder
#

the same amount you got going on with that if statement

zealous hatch
#

how would i go about flipping the sprite when the mouse is on the left? i know i can use math.sign to see if it is on the left side but would i have to write a bunch of if statements or structs like i did for the right side

rocky canyon
rocky canyon
#

i just did this

zealous hatch
rich adder
#

if its - then its on the left

zealous hatch
#

yeah but all the degrees on the left are different

rich adder
#

ohh i see yeah x would not work

zealous hatch
rich adder
#

left is negative angle anyway

rocky canyon
#

my signed angle gives me a value i can compare against 0

#

if the angle is > 0 i know its left.. if its less i know its right

zealous hatch
#

what is it returning?

rocky canyon
#

angle = Vector3.SignedAngle(targetDir, transform.forward, Vector3.up);

rocky canyon
#

maybe right.. idk

#

its 1 or the other lol

rich adder
#

lmao

rocky canyon
#

if (angle > 0) { tempScale.x *= -1f; }

#

i cant remember which way my sprite faces default

zealous hatch
modern olive
#

Is this channel for troubleshooting?

rocky canyon
#

i pick the sprite that goes with 7

rich adder
zealous hatch
#

ahh i see

rocky canyon
#

so i just cut my angles up into 22.5* sections

rich adder
rocky canyon
#

and i have a total of 8

#
  private int GetIndex(float angle)
    {
        //front
        if (angle > -22.5f && angle < 22.6f)
            return 0;
        if (angle >= 22.5f && angle < 67.5f)
            return 7;
        if (angle >= 67.5f && angle < 112.5f)
            return 6;
        if (angle >= 112.5f && angle < 157.5f)
            return 5;
        
        
        //back
        if (angle <= -157.5 || angle >= 157.5f)
            return 4;
        if (angle >= -157.4f && angle < -112.5f)
            return 3;
        if (angle >= -112.5f && angle < -67.5f)
            return 2;
        if (angle >= -67.5f && angle <= -22.5f)
            return 1;
        
        return lastIndex;
    }
#

dirty.. but it works

zealous hatch
#

i suppose, although this looks alot like mine but with less sprites xD

rocky canyon
#

each sprite has 4 different animations

rich adder
rocky canyon
#

soo each angle has a sprite sheet that goes along with it

rich adder
#

always use an array

rocky canyon
#

and i use a blend tree to change em

modern olive
#

I have an issue where I'm working with public float variables for a 3D movement system, walk speed and run speed. Whenever I change them in the unity editor, they revert to 6 and 12 respectively when i start the game. I've rewritten the script to make the variables not 6 and 12, but they automatically revert when i start the game. Other variables like jump height dont change, can anyone help

rich adder
rocky canyon
#

whats the start() and awake() methods have in em?

modern olive
rocky canyon
#

editor values would overwrite all those variables

rich adder
rocky canyon
#

whats ur start and awake doing?

vale olive
#

hello guys, i am having issues building the project. Can someone help me with this error?

rich adder
modern olive
rocky canyon
#

yup, probably where i askd about

modern olive
#

how can i rewrite this? Does unity have an elseif statement?

tacit estuary
modern olive
#

oops, tahnks

tacit estuary
modern olive
stark hedge
#

can I have a coroutine in a static class then start it from a separate monobehaviour?

#

can I run unity from my phone

slender nymph
#

the editor? no. you can build a game for mobile with unity though

stark hedge
#

how do I try it and see 😦

slender nymph
#

is this some shitty way of saying "i'm not at my computer to test it myself so i'd rather be lazy and just ask discord and assume someone will spoon feed me the information instead"?

stark hedge
#

yep

#

do u know?

slender nymph
#

yep

stark hedge
#

man I'm all cozy in my bed about to sleep and thinking about stuff. tried to look it up and I think I understand how it works just trying to confirm here. why are u so bitter for no reason?!?!? its the beginner chat man

#

so annoying

#

I'm assuming it works otherwise u would've said no

polar acorn
stark hedge
#

impressive

#

astounding

#

good night

tepid horizon
#

hello all. im making a survival game and i would like to make a simple grid inventory system but its very hard finding a tutorial as its my first time with this. any reccomendations?

slender nymph
#

you're unlikely to find a tutorial that covers exactly what you want to do, but you can check out a few tutorials to see how they do things and use that knowledge to write your own. or break down exactly how you want yours to act into smaller parts that you can search up tutorials and documentation for

rich adder
#

good start would be learning 2D arrays maybe

#

tilemap is also usable

tepid horizon
#

ok thank you, im finding the majority on youtube are either to hard to understand for me or outdated, i dont know where else too look other then youtube so ill search the internet

slender nymph
#

if the stuff is too hard to understand you are either looking at poor tutorials, or you are trying to do something that you don't quite have the foundational skills for yet. if it's the latter, i recommend brushing up on the basics by going through the beginner courses pinned in this channel and/or the pathways on the unity !learn site

eternal falconBOT
#

:teacher: Unity Learn ↗

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

tepid horizon
karmic kindle
#

I'm trying to change the Alpha value from 0 > 1, it works to set the material opaque but it doesn't work to set it back to visable again ``` public IEnumerator BuffHide(float hTimer)
{
while(hTimer > 0)
{
if(hTimer > 0)
{
hTimer--;
}
enemy.gameObject.tag = "Fallen";
Debug.Log("Enemy is hidden - Alpha = " + enemyMesh.material.color.a);

        enemyMesh.material.color = newColor;
        enemyMesh.material.renderQueue = -1;
        yield return new WaitForSeconds(1f); 
    }
    Debug.Log("Unhiding");
    enemy.gameObject.tag = "Enemy";
    enemyMesh.material.color = origColor;
    enemyMesh.material.renderQueue = -1;
}```
eternal needle
karmic kindle
#

Nope, I saw it on a forum and had errors in the inspector.

eternal needle
karmic kindle
#

During my testing I was moving the color change. Without .renderQueue it won't change from visable to hidden in the first instance

eternal needle
rustic timber
#
public class Test : MonoBehaviour
{
    [SerializeField] MeshRenderer meshRenderer;
    [SerializeField] Color defaultColor;
    [SerializeField] Color buffColor;

    void Start()
    {
        meshRenderer.material.color = defaultColor;
        StartCoroutine(ShowBuff(2.5f));
    }

    public IEnumerator ShowBuff(float duration)
    {
        meshRenderer.material.color = buffColor;
        yield return new WaitForSeconds(duration);
        meshRenderer.material.color = defaultColor;
    }
}
karmic kindle
# eternal needle Well you probably shouldnt be changing the render queue at all unless you know w...

I cast a spell, it applies to gameobjects within range, this spell "hides" the gameobjects so I'm trying to change the material via code. I was moving stuff around while testing and found the renderQueue line on a forum, when I applied it, it now makes the material opaque, but it just won't turn it back - outside of that, I've never tried to change materials on the fly. Even in the scene, I can pause, manually move the alpha slider and it becomes visable again.

karmic kindle
rustic timber
#

If you want per instance color, you need to use MaterialPropertyBlock.SetColor

#

That's a terrible example though I just realized lol

#
public class Test : MonoBehaviour
{
    [SerializeField] MeshRenderer meshRenderer;
    [SerializeField] Color defaultColor;
    [SerializeField] Color buffColor;
    MaterialPropertyBlock propertyBlock;

    void Start()
    {
        propertyBlock = new();
        SetMeshColor(defaultColor);
        StartCoroutine(ShowBuff(2.5f));
    }

    public IEnumerator ShowBuff(float duration)
    {
        SetMeshColor(buffColor);
        yield return new WaitForSeconds(duration);
        SetMeshColor(defaultColor);
    }

    void SetMeshColor(Color color)
    {
        propertyBlock.SetColor("_BaseColor", color); // Or "_Color" depending on your material
        meshRenderer.SetPropertyBlock(propertyBlock);
    }
}
karmic kindle
rustic timber
#

Try the example i posted too

karmic kindle
#

These lines work, but I can't get "GetColor" to work so it set's back to the original correctly enemyMesh.SetPropertyBlock(propertyBlock); enemy.GetComponentInChildren<SkinnedMeshRenderer>().SetPropertyBlock(propertyBlock);

rustic timber
karmic kindle
# rustic timber You could try both `_Color` and `_BaseColor`, or possibly `GetVector()` instead ...

The problem with that is when it reverts back to the original color, it's setting the whole object that color and not using the original materials. I think the whole mix up is because "alpha" is attached to the color property. I've got it working now with this, thanks for your help!

    void Start()
    {
        enemy = GetComponent<Enemy>();
        enemyMesh = GetComponentInChildren<SkinnedMeshRenderer>();
        origPropertyBlock = new MaterialPropertyBlock();
        enemyMesh.GetPropertyBlock(origPropertyBlock);
        propertyBlock = new MaterialPropertyBlock();
        propertyBlock.SetColor("_Color", newColor);
    }
    public IEnumerator BuffHide(float hTimer)
    {
        enemyMesh.SetPropertyBlock(propertyBlock);
        HideMe(propertyBlock);
        while(hTimer > 0)
        {
            if(hTimer > 0)
            {
                hTimer--;
            }
            enemy.gameObject.tag = "Fallen";
            Debug.Log("Enemy is hidden - Alpha = " + enemyMesh.material.color.a);

            yield return new WaitForSeconds(1f); 
        }
        Debug.Log("Unhiding");
        enemy.gameObject.tag = "Enemy";
        HideMe(origPropertyBlock);
    }```
exotic hazel
#

hello
so i was making a racing game
it wasa working fine and now im getting this error on the car.I understand the error but dont know what the problem is

verbal dome
exotic hazel
rustic timber
verbal dome
#

You know public class MyClass : MonoBehaviour

#

Do you have that?

exotic hazel
#

yea its just like that

rustic timber
#

Also make sure the file name matches the name of the class

#

In case you renamed it

verbal dome
exotic hazel
verbal dome
#

Hmm.. does the file have other monobehaviours in it?

#

Try removing the component from the object and re adding it

exotic hazel
#

ok lemme try that

#

whats an editor script?

verbal dome
#

A script that is intended only to work in the editor, not in built game

#

Why?

exotic hazel
#

oh

#

it was in a Editor folder

#

cus when i tried to build the game it said cant build while editor is compiling scripts

#

so i saw online and added to a editor folder

verbal dome
#

Ah okay yeah, the docs say:

Note: Unity doesn’t allow components derived from MonoBehaviour to be assigned to GameObjects
if the scripts are in the Editor folder

verbal dome
#

I didnt know that either

#

Although it does make sense

exotic hazel
#

but then how i build the game

#

it doesnt let me build the game

#

error comes cannot build while the editor is importing assets or compiling scripts

#

are their bugs in unity 6000 my unity keeps crashing whenever i open and scroll the heirarchy of a certain object

keen dew
#

That doesn't look like a Unity game

viral plover
#

it’s in early stages

fickle plume
#

Did you just shove a zipped game into git repository?

#

Removing this

dusty shell
#

could anyone help me figure out touch input?

keen dew
#

Ask the question and if someone knows the answer they'll help

dusty shell
#

I need help with everything. I wanna make a mobile joystick but don't understand what i'm doing

#

and youtube not helping much

keen dew
#

Requests for personal tutors go to the forums. !collab

dusty shell
#

thanks

fickle plume
#

Bot is lagging very badly at the moment

latent magnet
#
function getUserData() {
  return userData;
}


if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
  // Mobile device style: fill the whole browser client area with the game canvas:
  var meta = document.createElement('meta');
  meta.name = 'viewport';
  meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
  document.getElementsByTagName('head')[0].appendChild(meta);

  var canvas = document.querySelector("#unity-canvas");
  canvas.style.width = "100%";
  canvas.style.height = "100%";
  canvas.style.position = "fixed";

  document.body.style.textAlign = "left";
}

I am creating a webgl app
I have the getUserData() function in my main.js, how can I call it from unity?

timid hinge
#

hi guys can someon halp me, i dont know why this error is showing up

languid spire
timid hinge
languid spire
#

obviously something is null at line 113

languid spire
timid hinge
#

how can i post it?

storm pine
timid hinge
#

i send the link to my code?

languid spire
#

yes

timid hinge
languid spire
#

I cannot copy paste from that site. But there is so much on line 113 which could be null

timid hinge
#

like what because in the other lines everyting is ok

#

only on line 113 i dont understand why

storm pine
# timid hinge https://hatebin.com/uisoaktyvn

It looks that there is any problem on line :

if(ItemAssets.GetInstance().GetWeaponData(WeaponData.WeaponType.sword).GetParent().Equals(WeaponData.Parent.Player))

Maybe when you call it your ItemAsssets haven't load all the data and gives the error there. You have to Debug and found where the problem really comes. Or if is in this line maybe the GetParent() is failing

timid hinge
#

man im new at codding this is very complicated to me please explain more simply

languid spire
#
ItemAssets.GetInstance()
.GetWeaponData(WeaponData.WeaponType.sword)
.GetParent().
Equals(WeaponData.Parent.Player

So ...
ItemAssets
ItemAssets.GetInstance()
WeaponData
WeaponData.WeaponType
GetWeaponData(WeaponData.WeaponType.sword)
GetParent()
WeaponData.Parent
WeaponData.Parent.Player
Any one of the above could be null

timid hinge
#

ohh

#

i think is this

#

right?

#

thank you so much for the explanation ❤️‍🔥

storm pine
#

Try this:

case WeaponData.WeaponType.sword:
    var weaponData = ItemAssets.GetInstance().GetWeaponData(WeaponData.WeaponType.sword);
    if (weaponData == null)
    {
        Debug.Log("weaponData is null");
    }
    else
    {
        var weaponParent = weaponData.GetParent();
        if (weaponParent == null)
        {
            Debug.Log("weaponParent is null");
        }
        else
        {
            if (WeaponData.Parent.Player == null)
            {
                Debug.Log("WeaponParentPlayer is null");
            }
            else
            {
                var isEqual = weaponParent.Equals(WeaponData.Parent.Player);
                if (isEqual)
                {
                    isParentPlayer = true;
                }
            }
        }
    }
    break;

storm pine
timid hinge
#

where can i put that code

gaunt ice
#
var isEqual = weaponParent.Equals(WeaponData.Parent.Player);
if (WeaponData.Parent.Player == null){
  Debug.Log("WeaponParentPlayer is null");
}
```you use the WeaponData.Parent.Player before checking
timid hinge
#

like create a new script?

gaunt ice
#

put it before the code that throws exception

storm pine
gaunt ice
#

btw learn how to use generic

storm pine
topaz fractal
#

why am i getting this error it dont make sense

#

i have a else return true

timid hinge
#

now this is the error

gaunt ice
#

i would do that btw

get A
if(A==null){
  Debug.log("a is null");
  goto Error;
}
get B from A
if(B==null){
  Debug.log("b is null");
  goto Error;
}
....
goto Success;
Error:;
EditorApplication.isPlaying=false;//fatal error
Success:break;
```c style debugging
storm pine
gaunt ice
#

Console.WriteLine is from c#

eternal needle
gaunt ice
#

java one is System.out.printX

#

btw not code question related to unity

storm pine
topaz fractal
#

@storm pine console.writeline is c#...

#

what r u saying

storm pine
topaz fractal
#

sorry bra i diddnt see the 2 other ppl who said it

#

i diddnt mean 2 be a dick

timid hinge
#

it doesnt have nothing wrong on line 166

storm pine
gaunt ice
#
```any dot  (member access) operator on instance of class may throw NRE if the (reference of) instance is null
gaunt ice
#

your job to find it

timid hinge
#

im just aasking what could be null in that part of the code

#

as im saying im really new at this please concider that

gaunt ice
#

weaponSlots[count]?.Find("Icon")?.GetComponent<Image>()?.sprite = ItemAssets.GetInstance()?.GetWeaponData(weapon)?.GetSprite();
the stuffs that followed by ?

#

weaponSlots[count] may return null
weaponSlots[count].Find() may return null
etc

timid hinge
#

ok

#

im really dont understanding how to solve this error but I won't bother you anymore thanks btw

gaunt ice
#

dont chain so many methods unless you know they never be null

rough orbit
#

Making this dumb little game to learn Unity better and while this effect prob isnt suitable for the game format I've attempted to make an after image/ghost effect (a la Metroid/SOTN etc) by using an animator and scripting. But instead of exactly following the player's frames I'd like it to follow diagonally upwards/downwards as the illusion is that the player is flying left to right (it's actually the pipes moving right to left).
Making the effect less cluttery is another issue but that's prob more suited for the animation channel.

This is all very new to me so not even sure what I'm asking for here, so feel free to ask for additional info.

#

Unless the diagonal change can be more easily done somewhere in Unity, my best guess is that the answer lies somewhere in the Ghost's script? Again I'm still pretty clueless with everything Unity/game dev

long jacinth
#

I left programming for a month and i came back and i dont know what im doing wrong

dim wharf
#

How do I make a coroutine that yields after a few seconds OR after a mouse click (or any boolean)

gaunt ice
#

You need your own timer since you can’t interrupt wait for seconds

dim wharf
#

Ooooohhhh thanks

ionic zephyr
#

How can I cehck if two objects are in the same position? ( I tryed .Equals but it is too exact)

dim wharf
#

exactly what I needed

gaunt ice
#

Use vec3== is enough

storm pine
ionic zephyr
willow scroll
# ionic zephyr How can I cehck if two objects are in the same position? ( I tryed .Equals but i...

It's override bool Equals calls the internal public Equals method to check for all 3 coordinates, in case of Vector3, to be exactly the same.

x == other.x && y == other.y && z == other.z;

The operator == checks for the sum of the axes' differences being less than a really small value, and returns true if the Vectors are approximately equal

float num4 = num * num + num2 * num2 + num3 * num3;
return num4 < 9.99999944E-11f;

Equals is the thing which is exact. The thing is that it doesn't work if Unity's calculations are wrong at some point, which results in possible 10 != 10.0000001

errant lava
#

in the input manager when i right click to create a new binding it doesnt show the 2d vector composite. how would i get that to work?

willow scroll
#

The Action type can be anything but Button. This means, Value or Pass Through. Vector2 has to be chosen as the Control Type

willow scroll
timid hinge
#

what can i make to solve this?

willow scroll
timid hinge
#

stack trace?

#

what is that

languid spire
timid hinge
#

i need help men

#

i dont know how to coslve that

willow scroll
languid spire
timid hinge
#

this one

languid spire
#

now look at that line of code and think what could be null there?

willow scroll
timid hinge
languid spire
#

really, as a beginner, you should not be writing such compound statements, you only make your life more difficult

willow scroll
timid hinge
#

thats the problem i dont know what could be null here and i dont know how to check what is null

timid hinge
timid hinge
languid spire
willow scroll
timid hinge
#

please

languid spire
languid spire
timid hinge
#

weaponSlots[count].Find("Icon").GetComponent<Image>().sprite = ItemAssets.GetInstance().GetWeaponData(weapon).GetSprite();

willow scroll
#

It's 6, actually

timid hinge
#

thanks

harsh vigil
#

anyone know why sometimes a unity script only works once? and i have to fricking change something in the script for it to work again? it's really annoying

timid hinge
#

i solve the rest thanks for the help ❤

willow scroll
willow scroll
languid spire
#
var a = weaponSlots[count].Find("Icon");
var b = a.GetComponent<Image>();
var c = ItemAssets.GetInstance();
var d = c.GetWeaponData(weapon);
var e = d.GetSprite();
b.sprite = e;

@timid hinge

#

break the compound statement down into it's constituent parts

willow scroll
#

OnEnable is called when the script is updated, so, surely, there is no need for it to be called more than that

harsh vigil
harsh vigil
#

clicking the play button again

willow scroll
#

It does start the scripts again

#

You should explain your objective properly

harsh vigil
# willow scroll You should explain your objective properly

i got a script that switches the player over to the next scene via a button.

when i run it the first time it works perfectly with no issues at all. but when i stop the scene and start it again. I click on the button that switches me over to the next scene it doesnt work at all.

I need to go over to the script and change anything. (Like for example setting a object from private to public, etc) and after testing it again it starts working. But stopping it and starting again it breaks. So it only works once every time i update the script

willow scroll
#

I click on the button that switches me over to the next scene it doesnt work at all.
What exactly doesn't work? Is there button not clicked or the scene not changed?

languid spire
harsh vigil
willow scroll
harsh vigil
#

only changes after updating the script

willow scroll
#

How do you change the scene?

harsh vigil
#

but this is the void that I used for the button:

public void StartGameServer()
{
    if(NetworkManager.Singleton.IsHost)
    NetworkManager.Singleton.SceneManager.LoadScene("SampleScene", LoadSceneMode.Single);
}
bleak condor
#

im trying to add UI but nothing is showing up even when i add an image

harsh vigil
bleak condor
#

i have

languid spire
cobalt atlas
#

So I’m making a mobile game. Not to publish or make money off of just to send to a few friends to play. Well I’m on windows and came across the issue of needing a Mac/Apple device in order to make it an application due to needing XCode. I switched to trying to make it possibly a WebGL but now I’m having the issues of not having a way for iPhone users to full screen the game in something like itch.io. Is there any solution to my issue. I just want iPhone users to be able to run my game full screen without issues

willow scroll
#

Edit > Project Settings > Editor

harsh vigil
willow scroll
bleak condor
harsh vigil
#

this is pretty embrassing considering I've been using unity for 3+ years :/

willow scroll
harsh vigil
willow scroll
willow scroll
harsh vigil
#

ty both of u @willow scroll and @languid spire

willow scroll
#

And the image you've added

bleak condor
willow scroll
bleak condor
#

what do you man

willow scroll
#

Where is the Canvas' border?

#

You can also edit the messages

bleak condor
#

what do you mena where is it

#

i cant see it either

willow scroll
#

Double-click on it

bleak condor
#

oh nice

#

thanks i figured it out

willow scroll
bleak condor
#

yeah

#

lmao

rough orbit
#

The after image effect in the clip below was made through animation and some scripting. Anyone have suggestions on what to read up on if I want the "ghost" to follow diagonally upwards/downwards instead of exact player frames? The ghost is generated from space key inputs in the player script:

   {
       if (Input.GetKeyDown(KeyCode.Space) == true && birdIsAlive == true)
       { myRigidbody.velocity = Vector2.up * flapStrength; }
       { ghost.makeGhost = true; }
   }
#

Ghost script:

public class Ghost : MonoBehaviour
{
    public float ghostDelay;
    private float ghostDelaySeconds;
    public GameObject ghost;
    public bool makeGhost = false;

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

    {
        ghostDelaySeconds = ghostDelay;
    }

    // Update is called once per frame
    void Update()
    {
        if (makeGhost)
        {
            if (ghostDelaySeconds > 0)
            {
                ghostDelaySeconds -= Time.deltaTime;

            }
            else
            {
                //Generate a ghost
                GameObject currentGhost = Instantiate(ghost, transform.position, transform.rotation);
                ghostDelaySeconds = ghostDelay;
                Destroy(currentGhost, 1f);
            }
rough orbit
#

Posted it here since I'm a beginner myself trying to figure out how Unity works, but feel free to point me somewhere else if the issue is more advanced

slender bridge
zealous hatch
#

I have a gun shoot script that initialises a bullet prefab. Problem is when my character is looking left the bullet gets shot the other way, this is likely because i need to flip the bullet but i dont know how i would tell the bullet that it needs to be flipped

rough orbit
wintry quarry
#

so no extra code needed

zealous hatch
#

haha i think ive done this is the most stupid way ever

primal aurora
modest dust
slender bridge
zealous hatch
rough orbit
modest dust
rough orbit
modest dust
#

Then move the after image in the same way as the pipes/pillars

rough orbit
primal aurora
modest dust
#

He can just init them with a direction value and update them from there tho in a similar fashion

primal aurora
#

the y pos will be different for each

slender bridge
#

My thing is, if your character never moves on the X axis, how do you expect to make the ghost follow in some diagonal way? unless you create some arbitrary diagonal movement that wasn't natural to the character movements.

primal aurora
#

depending where the player is

modest dust
#

Either way, he asked for a diagonal movement so there's that

fair temple
#

im trying to make fps camera

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

public class PlayerMoveEvent : MonoBehaviour
{

    private bool isGround;
    private Vector3 velocity;
    private LayerMask layer;
    private CharacterController characterController;
    [SerializeField] private float walkSpeed = 7F;
    [SerializeField] private float gravity = 9.81F;
    [SerializeField] private float jumpHeight = 1F;
    [SerializeField] private float distance = 0.3F;
    [SerializeField] private GameObject groundedObject;

    private void Awake()
    {
        characterController = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
    }

    private void Update()
    {
        isGround = Physics.CheckSphere(groundedObject.transform.position, distance, layer);
        if (isGround && velocity.y < 0)
        {
            velocity.y = -1.2F;
        }

        float x = Input.GetAxisRaw("Horizontal");
        float y = Input.GetAxisRaw("Vertical");

        Vector3 moveToDirection = transform.right * x + transform.forward * y;
        characterController.Move(moveToDirection *  walkSpeed * Time.deltaTime);

        if (Input.GetButtonDown("Jump") && isGround)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2F * gravity);
        }

        velocity.y += gravity * Time.deltaTime;
        characterController.Move(velocity * Time.deltaTime);

    }

}

i guess everything is correct but character is flying towards sky

keen dew
#

If it doesn't work the way you want then I guess everything is not correct

#

Gravity is usually set to -9.81, yours is positive

#

so gravity is pulling the player upwards

fair temple
#

charachter is now not flying towards to sky thanks but now charachter is now cant moving

#

fixed

#

thanks

#

@keen dew ❤️

primal aurora
#

as the effect he wanted

#

looks like its moving forward

primal aurora
#

with the ghost

rough orbit
fair temple
#

When I remove time.deltatime, it jumps, but it jumps a lot. When I add time.deltatime, it doesn't jump at all. Any advice?

swift crag
#

please share your code properly

#

!code

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

public class PlayerMoveEvent : MonoBehaviour
{

    private bool isGround;
    private Vector3 velocity;
    private LayerMask layer;
    private CharacterController characterController;
    [SerializeField] private float walkSpeed = 7F;
    [SerializeField] private float gravity = 9.81F;
    [SerializeField] private float jumpHeight = 1F;
    [SerializeField] private float distance = 0.2F;
    [SerializeField] private GameObject groundedObject;

    private void Awake()
    {
        characterController = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
    }

    private void Update()
    {
        isGround = Physics.CheckSphere(groundedObject.transform.position, distance, layer);
        if (isGround && velocity.y < 0)
        {
            velocity.y = -2F;
        }

        float x = Input.GetAxisRaw("Horizontal");
        float y = Input.GetAxisRaw("Vertical");

        Vector3 moveToDirection = transform.right * x + transform.forward * y;
        characterController.Move(moveToDirection *  walkSpeed * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.Space) && isGround)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2F * gravity);
        }

        velocity.y += gravity * Time.deltaTime;
        characterController.Move(velocity * Time.deltaTime);

    }

}
deft glen
#

super simple question, im trying to get all the children of a specific transform and put it into a list. whats the simplest wayto do this?

swift crag
fair temple
#

which line

swift crag
#

oh, I misread a bit -- you're not moving in the if statement

#

characterController.Move(velocity * Time.deltaTime);

This runs every frame. If you don't include deltaTime here, you'll move a distance of velocity every single frame

#

So you definitely want to keep the deltaTime factor in there

lime pewter
#
Debug.Log(liquidType.maxFill / liquidType.viscosity + " this is min fill");

"maxFill" = 1f", and "viscosity = 9" why does Unity somehow output 0.133333?
I understand there is a float point error but where does Unity pull the 0.133333 when the true answer should be 0.1111111, even if it's not fully accurate an entire 0.02+ off seems excessive.

swift crag
fair temple
swift crag
#

I would log the value of velocity

#

also, one thing that seems a bit weird..

fair temple
#

yes

swift crag
#

velocity.y = Mathf.Sqrt(jumpHeight * -2F * gravity);

Did you set gravity to be a negative number?

#

the field initializer is 9.81F, but I'm guessing you changed that in the inspector

fair temple
#

when i change to negative

#

its still same

#

no difference

swift crag
#

you mean when you change the field initializer?

#

the value in the code?

#

That won't change the value that you've set in the inspector.

fair temple
swift crag
#

That does not answer my question.

#

Did you change the value in the code, or did you change the value in the inspector?

swift crag
#

okay, that won't do anything

#

unity is going to keep whatever value you've assigned in the inspector

#

and I'm guessing you entered -9.81 in the inspector

fair temple
#

nothing happened i dont know why

swift crag
#

Screenshot the inspector for your PlayerMoveEvent component.

fair temple
#

oky wait

swift crag
#

okay, so gravity is current -9.81, which is fine

#

9.81 would have made you fall into the sky

#

(and jumping wouldn't work, because you'd be taking the square root of a negative number)

fair temple
#

what value u think ill enter ?

swift crag
#

i didn't say you need to change gravity

#

it's fine as is

#

You should log the value of velocity right after performing a jump

#

so just Debug.Log("Jumped: " + velocity);

fair temple
#

oky

#

its not logging

#

omg

swift crag
#

that's odd, because you did jump into the air when you removed deltaTime from characterController.Move(velocity * Time.deltaTime);

fair temple
#

im struggling with this for 3 days

#

i cant fix

#

i tried every way

polar acorn
# fair temple

If that isn't logging then the condition is never true

swift crag
#

your ground check is wrong, then

polar acorn
#

I'm assuming you'd know if you weren't pressing space so it's probably isGround

swift crag
#

but they were jumping into space earlier

#

which is odd

#

One possibility is that the extreme downwards movement got them closer to the ground..maybe

#

(they removed deltaTime from the part that moves them vertically)

eager bear
#

Why does this keep appearing?

wintry quarry
eager bear
#

I'm following a tutorial

wintry quarry
#

You missed something

#

On line 7 of "IsFloor.cs" you are mentioning some ccript that doesn't exist

#

PlayerController < you don't have anything by this name so you can't use it

#

Also you need to open your Console window

eager bear
#

I have already change the name to the scrip I and still shows it

wintry quarry
#

it is not possible to use Unity effectively without your Console window being open

wintry quarry
#

Without details all we know is you missed something

eager bear
#

Sure, I'm gonna start the pc

karmic kindle
# rustic timber If you only want to hide the mesh, you could just disable the mesh renderer comp...

Hey, thank you. I didn't even think about just disabling the object, however the way this code works I really like the slight visual that's given to the player and it leaves the shadows too.

I just want to ask for my understanding, but with your code, it seems like you're configuring the Color in the inspector? As far as I understand, I have to use 'enemyMesh.GetPropertyBlock(origPropertyBlock);' in order to use the mesh on the specific gameObject when I set it back to visable again. I'm also keeping the timer there just to flow with the rest of my code and make it easier to remember things, I appreciate the mention though, some things are configured with 'tics' but others I need to keep a bit manual for my mechanics.

polar acorn
eager bear
#

I think I have found te problem

#

I'm gonna try

#

It doesn't work

eager bear
summer stump
#

Your !ide is not configured and there is a capitalization error

#

Harumph. Slow bot

eager bear
#

Whats an !ide

summer stump
#

An IDE

wintry quarry
# eager bear

Also filename and class name don't match. And you haven't saved the code.

summer stump
#

It is an integrated development environment

wintry quarry
summer stump
#

The thing you write code in

wintry quarry
summer stump
#

Line 11 in LimbCollision has the capitalization error btw

wintry quarry
#

Change what

#

the filename?

eager bear
#

Yes

wintry quarry
#

Rename the file

summer stump
#

Ctrl+r

wintry quarry
#

like any other file on your computer

swift crag
#

well, there is one small caveat

#

if you rename the file in Explorer, and don't rename its .meta file, Unity will think you deleted player.cs and created PlayerController.cs

#

So do it in Unity.

worthy merlin
#

How are they making these Collapsible Headers on the inspector? I am wanting my custom script to have these for organization

timid hinge
#

hi guys im having a error on my code can someone help me?

worthy merlin
#

ah, I've always been hesitent to use those because from how it looks, it will delete pretty much everything from your inspector and you have to manually add all of the variables back

wintry quarry
#

NA doesn't have that problem

worthy merlin
#

gotcha! I'll try it out

ruby python
wintry quarry
timid hinge
#

how can i solve that?

ruby python
#

Figure out what it's looking for and then figure out why it isn't finding it?

wintry quarry
# timid hinge how can i solve that?

Either:

  • Make sure your populated the Dictionary properly before accessing it
  • Use TryGetValue if it's expected for the key to not exist sometimes
swift crag
#

TryGetValue is great for the latter situation

#

I've replaced all of my "if has key, then..." with it

worthy merlin
#

nvm I can read

swift crag
#
if (!auralAlerts.TryGetValue(heard, out var list))
{
    auralAlerts[heard] = new();
    list = auralAlerts[heard];
}

this either gets the list from the dictionary or creates a new one and puts it in the dictionary!

zealous hatch
#

how can i replact this gun with a prefab i have. Need it to be the same position, parent and other things. Plus i need a variable from another script to have the prefab assaign its value.

atm i have this

if (Input.GetKeyDown(KeyCode.E))
{
    Destroy(GunInst);
    GunInst = Instantiate(Gun2, Gun.transform.position, Gun.transform.rotation, GunWrapper);
    
}``` although it doesnt remove the original sprite nor does it replace in the same loaction
polar acorn
wintry quarry
timid hinge
#

please what can i do to solve this

zealous hatch
# wintry quarry shouldn't you be using `GunWrapper.positoin/rotation` not Gun?

i figured that out but thank you. and yeah you were correct. How would i go about replacing all the links that where connected through a different script?

For example i have a sceript that is accesses the guns spawn point(for the bullet) but when i delete it i want to replace that spawn point with the new prefabs

wintry quarry
#

Just use that

timid hinge
wintry quarry
#

first one

timid hinge
#

i dont understand nothing

wintry quarry
#

read

#

click the link and read

#

give it an effort

zealous hatch
#

how can i access a variable from a script from a prefab?

timid hinge
#

bro i need to make this project to school and i dont want to understand just make the fucking game

zealous hatch
#

i can just do something like GunInst.GetComponenent right

wintry quarry
wintry quarry
timid hinge
#

and im trynna solving this error all day

zealous hatch
#

would i get the script

languid spire
zealous hatch
#

component

swift crag
timber tide
#

why are you learning game dev if you don't want to learn

timid hinge
swift crag
#

then reap what you have sown and fail.

languid spire
swift crag
#

i can't stand this sort of attitude

zealous hatch
#

wait how do i get a certain gameobject componenet? GetComponenet<GameObject>

swift crag
wintry quarry
timid hinge
#

bro trust me im trynna to understand but im so fucking done

#

i cant no more man

raw ledge
#

Hello im getting a Collider from a child with a serializedfield and I want to rotate it of 90 degrees on the z axis im doing this : colliderTransform *= Quarter.Euler(0,0,90) any idea why it's not working ?

worthy merlin
zealous hatch
polar acorn
timber tide
#

if you can't understand the concept of dictionaries, then fallback onto stuff you already know like arrays

wintry quarry
#

MyScript myVariable = myObject.GetComponent<MyScript>();

timid hinge
#

i chosse to make a game at the beggining but no one told me it was gonna be that hard

wintry quarry
#

Game dev is very hard

timid hinge
timber tide
#

game dev is like any other coding profession, but you actually have to put all those optimization techniques to use

timid hinge
#

not for me

zealous hatch
#

so how would i go about getting a gameobject from a prefab

timid hinge
#

i see the beuty in it but not for me

wintry quarry
zealous hatch
wintry quarry
#
GameObject instance = Instantiate(prefab);``` assuming `prefab` is a GameObject
#

Even better though would simple be to directly reference the prefab as the component tpye.

Like:


public MyScript prefab;

void Spawn() {
  MyScript instance = Instantiate(prefab);
}```
#

no need for GetComponent then

zealous hatch
#

what is MyScript?

#

ive got this to spawn in my prefab

` cs GunInst = Instantiate(Gun2, GunWrapper.position, GunWrapper.rotation, GunWrapper);

wintry quarry
#

whatever component you have on the prefab

#

Like a Gun script or something

polar acorn
zealous hatch
#

why would i need to put my script

#

if im just trying to grab a gameobject from a prefab

#

sorry im actually fried right now

carmine sierra
polar acorn
#

Because it is almost always the wrong move to store a prefab in a variable of type GameObject. You should use the component you actually want. All components have .gameObject, whereas getting a specific component requires calling GetComponent which is slow

zealous hatch
#

ah its not a componenet, its a child

carmine sierra
#

drag it in the box

#

or serializefield

zealous hatch
carmine sierra
#

cant use getcomponent for the whole object

zealous hatch
#

i need the spawn point which is inside the prefab

polar acorn
carmine sierra
#

then save the code and drag the object into the box

#

it is like a reference

#

to the object

zealous hatch
#

so i havew a defualt gun that shoots and follows the players mouse. When i click e i want to swap it out for another gun. Ive got that but in my player script is where i hand the aiming and spawning of bullets so i need to replace all the public variables link with the previous gun to the new one like with spawnpoint

wintry quarry
polar acorn
wintry quarry
dense root
#

I'm trying to exclude a *selected value * from being selected from the values i.e. 2 is selected but I want to exclude it from the random values.

One suggestion was to create an array of values with 2 being excluded {1, 3, 4 ,5} and then randomizing that result, but it doesn't seem quite elegant especially if I am doing hiragana/katakana which contains 92 characters.

Any suggestions on a better solution?

zealous hatch
#

are you saying i should make one

polar acorn
wintry quarry
polar acorn
#

and why praetor said to make one

wintry quarry
zealous hatch
#

and the script just holds a reference?

wintry quarry
#

yes

#

for now

#

I mean it can do lots of other things.

dense root
wintry quarry
#

There are many good reasons to have one for a gun

wintry quarry
polar acorn
wintry quarry
#

think of it like shuffling a deck then drawing down the cards. You get a random one each time since you shuffled at the start

dense root
#

ohhhh

#

Let me do some tinkering and see if I can get it to work on my own.

#

Just to double check, the pseudocode would look something like this:

Pick out the first value to get the enemy hiragana/alphabet character あ
Iterate on the list for the other values
i + 1 => い
Repeat as necessary
zealous hatch
#

ive made a script that references it

#

now do i just add in my main script some variable to the script and then gain the variable

polar acorn
coral crater
#

hi all :) got some switch weirdness here? I have 3 outcomes for if you click something on -200, 0, or 200. I have no issues at all with 0 and 200 working, but with -200 it always goes to default? but the error message tells me that the clicked object is on -200. any ideas if I'm formatting something wrong? I already tried writing (int) infront of -200 on the case

polar acorn
#

The log truncates to two decimal places, but the case statement is looking for exact equality.

#

Instead of using a switch, use if statements with Mathf.Approximately

wintry quarry
coral crater
languid spire
formal hatch
#

1 img in the Scene 2nd in the game how can i fix this ?

polar acorn
zealous hatch
polar acorn
zealous hatch
#

oh the prefab

#

i have the script in my prefab but it wont let me assaign the varaibles

#

public static GameObject SpawnPoint; public static GameObject LeftHandWrapper;

zealous hatch
#

oh i was trying something else

#

i was trying
bulletSpawnPoint = ReferenceTaker.SpawnPoint;

zealous hatch
# polar acorn no

[SerializeField] public GameObject SpawnPoint; [SerializeField] public GameObject LeftHandWrapper;

polar acorn
zealous hatch
polar acorn
zealous hatch
#

nah

polar acorn
#

did you save the script after changing it

zealous hatch
#

yes

polar acorn
#

Show a screenshot of your console

zealous hatch
#

i just reset unity

#

it now allows me to

polar acorn
#

Okay, so it just needed to compile

#

Now, you can assign those variables in your prefab, and change the variable you're instantiating from to the type ReferenceTaker

#

and that will be the type that Instantiate returns, so you can access its SpawnPoint and LeftHandWrapper variables

zealous hatch
#

sorry to be such a pain but what does instantaiate returns mean

polar acorn
#

Functions can return a value. That means that if you were to do someVariable = aFunction() it would assign someVariable to the return value of the function aFunction

#

Instantiate returns a reference to the object it just made

zealous hatch
#

oh i seee

polar acorn
#

the type of variable it returns is the same as the type of variable you are instantiating

summer stump
zealous hatch
summer stump
#

Some sort of GunInst? You would access it from GunInst
Or as Digi said, just make Gun2 the script itself

polar acorn
zealous hatch
#

if i made gun2 the script wouldnt it then not make the gun

polar acorn
#

Instantiate clones an object

#

no matter what type you pass in

zealous hatch
#

yes

polar acorn
#

it clones the object

zealous hatch
#

and it clones gun2

summer stump
zealous hatch
#

oh okay

#

would i need to reference the script some how

#

i cant just put ReferenceTaker instead of Gun2 right

summer stump
#

Names have nothing to do with how the code works at all

zealous hatch
summer stump
#

Change the TYPE of the variable though

#

Yes, do not write ReferenceTaker

#

Write Gun2

zealous hatch
#

ok

summer stump
#

public [SomeType] Gun2

#

Change the type

zealous hatch
#

tio what type

summer stump
#

What type do you need it to be
Hint, the script

zealous hatch
#

cause its already a gameobject right

summer stump
#

Yes, you do not want it to be GameObject

zealous hatch
#

😭 what type does a script come under

#

is it the variables im trying to grab?

#

im looking at the different types atm

summer stump
#

public class [nameOfScript]

#

nameOfScript is the type

#

You have defined the type yourself

#

It sounds like it is ReferenceTaker? I don't think that is a great name, but that would be the type here

polar acorn
# zealous hatch

You cannot call instantiate on a type, you have to call it on a variable

dense root
polar acorn
#

You were supposed to change the type of the variable, not change Instantiate

polar acorn
dense root
#

Darn, I was hoping to avoid that haha

coral crater
coral crater
zealous hatch
dense root
summer stump
#

public ReferenceTaker Gun2

#

Drag in the object

zealous hatch
#

in the instantiate

summer stump
#

Instantiate gun2

summer stump
polar acorn
summer stump
#

You do not touch the instantiate from how it was earlier

#

You change the VARIABLE that you named Gun2

zealous hatch
wintry quarry
#

what the heck is a "main script"?

summer stump
polar acorn
summer stump
#

You should know

zealous hatch
zealous hatch
polar acorn
# zealous hatch kidnof
zealous hatch
#

i know what a variable is

summer stump
summer stump
polar acorn
#

to the type you just made

zealous hatch
#

omg im trippiong

cosmic dagger
summer stump
#

[Accessor] [Type] [name]

#

Change the type

zealous hatch
#

i think the gameobjects being a type was tripping me

summer stump
#

public [Something] Gun2

zealous hatch
#

class

summer stump
#

No

#

class is a keyword
A SPECIFIC class's NAME is a type though

polar acorn
summer stump
zealous hatch
polar acorn
summer stump
#

There it is

polar acorn
#

like we said

#

to the script you just made

zealous hatch
#

okay the tyoe us gameobject so im going to change that

summer stump
#

Yes

zealous hatch
#

to referenecetaker

polar acorn
#

yes

zealous hatch
polar acorn
# zealous hatch

Now you also have to either change the type of GunInst or store it in a different variable of type ReferenceTaker

zealous hatch
#

okay

#

so ive changed the gunInst to the tpye referencetaker

polar acorn
#

Now you can do GunInst.SpawnPoint or whatever variable you need from it

dense root
#

Okay so I'm creating a flash card system and I was able to successfully shuffle the key using the provided shuffle method. How do I go about randomzing which character goes in which button? Currently it just displays in order

        for (int i = 0; i < 4; ++i)
        {
            answerButton[i].text = answerKey[hiraganaArray[i]];
        }
wintry quarry
polar acorn
zealous hatch
polar acorn
wintry quarry
dense root
#

no no, I'm pulling from the first increment in the array. So the first button is always the correct answer

#

I need a way to re-shuffle the buttons

wintry quarry
#

I don't understand what that sentence means

zealous hatch
#

should it be the script

polar acorn
#

yes

zealous hatch
#

thats what it is when im getting the error

wintry quarry
#

you have another copy of the script in the scene

summer stump
# zealous hatch

Should probably be a prefab with the script
Is this from the scene?

Nm, certainly what praetor said

dense root
zealous hatch
wintry quarry
polar acorn
wintry quarry
polar acorn
dense root
#

Because of the way I'm for looping through the array

        for (int i = 0; i < 4; ++i)
        {
            answerButton[i].text = answerKey[hiraganaArray[i]];
        }
zealous hatch
summer stump
#

Yes

polar acorn
wintry quarry
dense root
#

That is what's happening

wintry quarry
#

If you shuffled it, it has an equal chance of being in any of the slots

dense root
#

The first button is always the ansewr

#

Right right

#

But the problem when I go to make answer buttons, the way I'm currently doing it is I pull the first shuffled value. Then when I want to randomly select values (including the answer) I run into the problem as described

wintry quarry
#

wdym by "pull the first shuffled value"

languid spire
#

what did you actually shuffle?

karmic kindle
#

I've set up a script to turn objects transparent, however it isn't applying the settings to all of the mesh objects when it's being "shown" again - https://pastebin.com/hR93zLv8

dense root
#

Well I'm using the first shuffled value to declare the enemy, then I'm key-value pairing with the answer (あ = A); then using the shuffled array to pull the answers and the enemy from it

#

Maybe I should make a video

languid spire
#

maybe shuffle the answerButton array instead

keen dew
#

If you don't want the answer to be the first value then don't pull the first value. Pull a random value instead.

wintry quarry
dense root
keen dew
#

And why can't you make a random value the answer?

dense root
#

And the values are already shuffledt o begin with

karmic kindle
wintry quarry
dense root
#

Ahhh

#

yeah that's what I should do

zealous hatch
#

okay how would i reference the gameobject(prefab) that the script is attached to(referencetaker)

wintry quarry
#
    public static void HideMe (Renderer rend, MaterialPropertyBlock materialProperty)
    {
        rend.SetPropertyBlock(materialProperty);
    }```
#
HideMe(enemyMesh, origPropertyBlock);```
lost wasp
#

Hello there! Im totally new to C# and especially in combination with Unity.

Im working on a healthbar which ive already created as UI in Unity and Set the min. and max. Value of the Slider from 0 to 100.
For whatever reason the code doesnt takes the 100 maxValue as maxHealth, instead its starting with 0.
Acctually I cant figure out what might be the problem so if anyone has an idea, hit me up. Thanks! 🙂

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

public class HealthBar : MonoBehaviour
{
    public UnityEngine.UI.Slider slider;

    public void SetMaxHealth(int health)
    {
        Debug.Log("Setting max slider value: " + health);
        slider.maxValue = health;
        slider.value = health;
    }

    public void SetHealth(int health)
    {
        Debug.Log("Setting current slider value: " + health);
        slider.value = health;
    }
}```

using System.Collections;
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.WebApi;
using UnityEngine.UI;
using UnityEngine;

public class Player : MonoBehaviour
{
public int maxHealth = 100;
public int currentHealth;

public HealthBar healthBar;

// Start is called before the first frame update
void Start()
{
    currentHealth = maxHealth;
    Debug.Log("Setting max health: " + maxHealth);
    healthBar.SetMaxHealth(maxHealth);
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        TakeDamage(20);
    }
}

void TakeDamage(int damage)
{
    currentHealth -= damage;
    Debug.Log("Taking damage: " + damage + ", current health: " + currentHealth);
    healthBar.SetHealth(currentHealth);
}

}```

ionic plank
#

Hi I finished to create my game, how can I build it (it's for Android)

languid spire
karmic kindle
lost wasp
#

Here I could easily adjust it to 100 myself.

#

But normally that should be automaticly set to that 100 depending on the slider maxValue.

languid spire
lost wasp
#

Cause it will be ignored anyways cause I can assign the value in the Inspector.

languid spire
#

because the value in the inspector will overwrite the 100

lost wasp
#

Okey, so then im doing it by myself with the Inspector. But thanks for enlightening me! 🙂

karmic kindle
#

The only caveat I've found is when you first attach a script to an object; if the script has # = 100;, the inspector will show that until you set otherwise

languid spire
#

true, but dangerous. you change the code and nothing happens so best to keep all serialized values in the inspector only then you don't make mistakes or 'forget'

karmic kindle
#

😏 I only know because I did forget and curious behind the why

dense root
#

Got the shuffle working! Thank you so much for the help

woven crater
#

i have a gameobject that have a material respond for screen transition but idk how to put it on screen space like a canvas image.

long jacinth
#

Guys I don’t know I’m doing wrong here when I collide with the object it shows the interacticon butt when I leave it doesn’t

gaunt ice
#

google on collision exit

wintry quarry
final kestrel
long jacinth
wintry quarry
#

it's saying if I am colliding with an object that has the wrong tag, hide the thing

#

it's not saying "when I stop colliding with the correct object, hide the thing"

#

That latter one is what you want

long jacinth
#

Ya it makes sense I don’t know what I’m doing I left Unity for a month and came back an idiot 😅

misty pecan
#

how do i check if the mouse is clicked anywhere but the object

ashen ridge
#

Is it a 2d, 3d or an ui object?

misty pecan
#

2D object, i have a tower and i want to show its targeting radius, which is a child object, whenever it is selected, which happens OnMouseDown(), but i want it to de-select whenever i click anywhere that isnt on the object

west sonnet
#

What's the easiest way to use lerp to change a value? I want to slow change the alpha value of a video

#

I think lerp can be used for that, right?

wintry quarry
wintry quarry
west sonnet
#

How can I access the alpha value, of a video player, in a script?

#

if I do Cutscene.alpha, nothing relevant shows

misty pecan
willow scroll
west sonnet
willow scroll
#

Which is a properly and can be set

ashen ridge
west sonnet
#

I'm so confused. I have this reference to another script, but I'm trying to drag and drop it in the inspector but it's not working?

#

It's also not detecting it if I click the little box to the right

#

The name is defo correct

willow scroll
west sonnet
#

The variable is shown in the inspector, but I can't drag and drop the script into it

willow scroll
west sonnet
#

What are the types? The type is the script?

west sonnet
willow scroll
willow scroll
#

You should now show what you're dragging into it

west sonnet
#

I'm dragging the same script into it

#

It's worked for me before

#

Is it because the script isn't attached to an object?

lost wasp
#

!code

west sonnet
#

Yup 👍🏻

willow scroll
west sonnet
#

What should I put as the type?

willow scroll
#

The object you're dragging should have your script, assuming it's derived from Component

willow scroll
west sonnet
#

MoveTowards doesn't keep repeating. Value jumps from 0 to 0.05 and stays there. Doesn't go any higher. What am I doing wrong?

willow scroll
polar acorn
polar acorn
#

It'll move 0.05 units closer to 1 every time it runs

#

Also, you probably want your "current value" to actually be the current value instead of 0 every time

west sonnet
willow scroll
polar acorn
willow scroll
polar acorn
#

The first value is the current, not the start

#

This is the difference between it and Lerp

swift crag
#

MoveTowards is not magical. It has no memory.

#

It moves from A to B by at most C

polar acorn
#

Lerp does expect constant inputs with a changing time, while MoveTowards expects changing inputs with constant distance

ashen ridge
swift crag
#

If you ask it to move from 0 to 1 by at most 0.05, you're going to get 0.05 out

#

Lerp is also not magical. It has no memory. It gives you a value that C% between A and B.

#

you wouldn't expect 1 + 1's value to change depending on how many times you did it, would you? (:

west sonnet
#

Is this correct?

swift crag
#

It'll function now, but it's also framerate-dependent

#

You are asking it to move from VideoAlpha to 1 by at most 0.05f every frame

west sonnet
#

This is what I have but it instantly changes the alpha. It's not a gradual increase

swift crag
#

i would expect this to move it very very very very slowly

west sonnet
#

Yeah, same

swift crag
#

given that you're moving it by 0.0005f per second

polar acorn
polar acorn
#

Try adding this log:

Debug.Log($"Changing alpha from {VideoAlpha} -> {CutsceneVideo.targetCameraAlpha}");
dense root
#

What's the simplest way to make a door? I'm making a Pokemon style clone

And was thinking it would go something like this

Collider on the door.
Player changes scene to the house.
Transform.Position of player is set.
slender nymph
#

didn't we already have that discussion, just without specifying a "door"

dense root
#

I believe so, if you're referring to the player position not being in the right spot when entering and exiting the door

slender nymph
#

doing that would mean you won't have to keep changing it every time you decide you want new features, like bigger or more buildings/doors