#💻┃code-beginner
1 messages · Page 382 of 1
use Mathf.Repeat(angle, 360) to get this into the 0..360 range
but my code is jank.. it has 8 different if statements
here, look at how I'm doing it for my radial menu
this is exactle what im trynna get lol
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
i'll share my code, but it isn't pretty ;D im opening the project atm
huh what am I looking at?
just 1 of the reasons it had to open in safemode
haha okay thanks, @rich adder seems to be decent
Fuck yea!
amazing how hard it is to make games retro.. u have to fight against the engine alot of the times
lol
always wanted to work on a 2.5 in fps
get to it. its fun 🙂
i only know basic billboarding, wouldn't have thought to make the 8 way sprite
heres my 8 sided rotation code.. prepare to laugh, or cry
ohh SignedAngle. How did I miss this function?
it boils down to a switch statement anyway
Angles are slightly annoying to deal with
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
hello quick question
hi quick question!
can different script have the same bool name
but specifically be told which one is true and not true if given serialized reference
of course they can
they are separate classes
ok thank you thats all i needed to know
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
For some reason, when moving the animation activates several seconds later, why could this be happening?
exit time maybe? hard to say from this image alone
exit time or a long transition
probably the URP one
I had set it to 0, I just tried to remove it directly and that seems to have fixed it.
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
you'll be able to get the controller working
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
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
//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
My advice is to learn to use arrays
how would i use a array for this?
And structs
store the sprites?
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
cursed af
What's the simplest way to do a boxcast identical to a box collider?
pass the size of box collider in the parameter ?
What
You can't
in what way you are talking about identical, size ?
Call boxcast using the data from the Collider
holy mother of god
Course you can
any good resources for learning structs
Where?
not that much different than how you make a class
how they function changes a bit.
(values are copied not changed on original ever)
this is the kind of code people joke about when they say they are on line 500 thousand of their "even or odd calculator"
yeah i got
thats cool
so then whats the problem ?
also it seems to be off
that is the easy way
also note the size is halfExtents
So just / 2?
so you want check.size/2
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
wouldnt a dictionary be easier nvm
put those two innit
Dictionary
i wrote that but idk might be too hard for them adding values xD
Many to one mapping (finding a range), dictionary not help
Loop over the dictionary, check if the key is in a range, if it is, get the value
or implement IEquatable 😮
The most easiest way is to use loop to iterate an array or list, ordered set is overkill
Why not just use a list?
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)
public struct Example
{
public int Something;
public Sprite AnotherThing;
}```
though I usually prefer a class when it has reference types
divide the input angle by (360 / 10) -- so, 36 -- to go from the first range to the second range
The easier way is to turn it into a function so you only have to think about it once
uhuh Collider[] overlap = Physics.OverlapBox(transform.TransformPoint(check.center), check.size / 2, check.transform.rotation);
I had this I was just looking for an easier way
how would i use the greater than or less than in this
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
the angles dont go to 360, they start at 90 and then go round to -180
Oh i misread…
looks more like they go from -90 to 90 here
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
the ranges are not the same, 18 35 30 11 ….
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
so this?
this is just an example to your question, re-read what PraetorBlue wrote
okay
also put the [System.Serializable] Attribute above it so you can change it in the inspector
ill give it a go
would this not mean i would have like loads of those struct things
wdym by "loads"
like one for every sprite?
the same amount you got going on with that if statement
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
on the left of what?
i just did this
the character
cant u just compare the x position
if its - then its on the left
yeah but all the degrees on the left are different
ohh i see yeah x would not work
dioes this work on both the left and right
left is negative angle anyway
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
what is it returning?
angle = Vector3.SignedAngle(targetDir, transform.forward, Vector3.up);
wait > 0 is left?
lmao
if (angle > 0) { tempScale.x *= -1f; }
i cant remember which way my sprite faces default
what does returning 7 do for you
Is this channel for troubleshooting?
i pick the sprite that goes with 7
code channel
ahh i see
so i just cut my angles up into 22.5* sections
#🔎┃find-a-channel if you need something other than code
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
i suppose, although this looks alot like mine but with less sprites xD
each sprite has 4 different animations
you should never number your variables
soo each angle has a sprite sheet that goes along with it
always use an array
and i use a blend tree to change em
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
then you have other code setting it
whats the start() and awake() methods have in em?
(yes i have hit save on my code)
editor values would overwrite all those variables
huh ?
whats ur start and awake doing?
hello guys, i am having issues building the project. Can someone help me with this error?
this isn't a code question. Also that warning is pretty self explanatory, seems like some process is still running
oops i just found it
yup, probably where i askd about
how can i rewrite this? Does unity have an elseif statement?
You didn’t close your original if statement
oops, tahnks
also to your second question, there are else if statements:
if (money > 10)
{
}
else if (money > 100)
{
}
else if (money > 1000)
// etc…```
oh, i was trying to make it one word. thank you!
can I have a coroutine in a static class then start it from a separate monobehaviour?
can I run unity from my phone
the editor? no. you can build a game for mobile with unity though
how do I try it and see 😦
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"?
yep
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
Well, you've written it down in the form of asking it here, so you can just refer back to it tomorrow when you're back at the computer
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?
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
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
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
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ok im looking at a tutorial now if i do find it confusing ill go check the learn site out
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;
}```
Why are you changing the render queue, was this AI code?
Nope, I saw it on a forum and had errors in the inspector.
Where are you assigning anything to newColor? This loop looks like it's just assigning to the same value over and over
private float newAlpha = 1.0f;
private Color origColor;
private float origAlpha = 0.0f;
void Start()
{
enemy = GetComponent<Enemy>();
enemyMesh = GetComponentInChildren<SkinnedMeshRenderer>();
// origColor.a = enemyMesh.material.color.a;
newColor.a = newAlpha;
origColor.a = origAlpha;
}```
During my testing I was moving the color change. Without .renderQueue it won't change from visable to hidden in the first instance
Well you probably shouldnt be changing the render queue at all unless you know what it's doing. Maybe clarify what's actually happening because this looks like you just set the alpha to 1 a bunch of times in that coroutine then assign it to 0 at the end.
Also have you tested this without code? You do need specific shader settings if you want something transparent
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;
}
}
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.
I'm changing the material and not color - forums suggest that I should be changing the alpha value via .color so this won't work for me. I don't want to create duplicate materials for all of my gameobjects.
If you want per instance color, you need to use MaterialPropertyBlock.SetColor
That's a terrible example though I just realized lol
https://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html this one's better
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);
}
}
Thanks very much, I'm playing around with it atm
Try the example i posted too
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);
You could try both _Color and _BaseColor, or possibly GetVector() instead of color. But I'd say it's safer and easier to just have the two colors be separate. That way you can tint too if you want to
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);
}```
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
Is carcontroller a component that you added to an object?
its a script yea
If you only want to hide the mesh, you could just disable the mesh renderer component btw. Also look at my latest snippet for a way shorter version of that function - you don't need that hTimer stuff
Then the script should inherit from MonoBehaviour
You know public class MyClass : MonoBehaviour
Do you have that?
What is the file name of this script?
Hmm.. does the file have other monobehaviours in it?
Try removing the component from the object and re adding it
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
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
new knowledge found
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
That doesn't look like a Unity game
it’s in early stages
could anyone help me figure out touch input?
Ask the question and if someone knows the answer they'll help
I need help with everything. I wanna make a mobile joystick but don't understand what i'm doing
and youtube not helping much
thanks
Bot is lagging very badly at the moment
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?
hi guys can someon halp me, i dont know why this error is showing up
here is the code
!code
what do you mean?
obviously something is null at line 113
post your code correctly. Unfortunately the bot is not working
how can i post it?
Use any page as https://hatebin.com/ for long code
i send the link to my code?
yes
I cannot copy paste from that site. But there is so much on line 113 which could be null
like what because in the other lines everyting is ok
only on line 113 i dont understand why
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
man im new at codding this is very complicated to me please explain more simply
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
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;
Is not the best Debug but should work
where can i put that code
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
like create a new script?
put it before the code that throws exception
In your case
btw learn how to use generic
I edit my post so you can change the full case of your switch
now this is the error
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
Yeah but PrintNumbers() or guessingGame()return a bool
Console.WriteLine is from c#
Console.writeline is not java
Read the error, it says is on your Inventory class on line 166
Mb then, sorry
this is the code inventory
https://hatebin.com/qnpkhtdwrt
it doesnt have nothing wrong on line 166
This is line 166
weaponSlots[count].Find("Icon").GetComponent<Image>().sprite = ItemAssets.GetInstance().GetWeaponData(weapon).GetSprite();
Now is your work to find which element is null
```any dot (member access) operator on instance of class may throw NRE if the (reference of) instance is null
wich ones can be nulls?
your job to find it
im just aasking what could be null in that part of the code
as im saying im really new at this please concider that
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
ok
im really dont understanding how to solve this error but I won't bother you anymore thanks btw
dont chain so many methods unless you know they never be null
and https://docs.unity3d.com/ScriptReference/Component.TryGetComponent.html
also consider direct reference in inspector/ cache (save to some variables) the result
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
I left programming for a month and i came back and i dont know what im doing wrong
How do I make a coroutine that yields after a few seconds OR after a mouse click (or any boolean)
You need your own timer since you can’t interrupt wait for seconds
Here is a simple example: https://hatebin.com/alvkiueetm
Ooooohhhh thanks
How can I cehck if two objects are in the same position? ( I tryed .Equals but it is too exact)
exactly what I needed
Use vec3== is enough
Use distance and compare if is less than a margin
thanks, I think it works
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
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?
It won't be shown if the action's type isn't Vector2. Make sure to ask these questions in #🖱️┃input-system next time.
The Action type can be anything but Button. This means, Value or Pass Through. Vector2 has to be chosen as the Control Type
I suppose, you have to make sure the mouse click doesn't happen before the start of the Coroutine
what can i make to solve this?
Go to the last line of the Stack trace
this is no different to the error you fixed 90 minutes ago
Go to the last line of the Stack trace written at the bottom of your Console window
start with, what is the line of code?
this one
now look at that line of code and think what could be null there?
This is not a line
really, as a beginner, you should not be writing such compound statements, you only make your life more difficult
Yes, there are so many things, which can be null
thats the problem i dont know what could be null here and i dont know how to check what is null
like what
bro thats the point im making a project to school i need to make this but i dont want
look at the code you were given to solve the previous null ref exception
I was able to count 7 things in that single line of code, which can throw you a null error
like waht?
can you refere it to me
please
do you even know what I mean by compound statements?
no.
exactly, so post that line of code here
weaponSlots[count].Find("Icon").GetComponent<Image>().sprite = ItemAssets.GetInstance().GetWeaponData(weapon).GetSprite();
-
weaponSlots[count]
-
Find("Icon")
-
GetComponnent<Image>()
-
ItemAssets
-
GetInstance()
-
GetWeaponData(weapon)
It's 6, actually
thanks
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
i solve the rest thanks for the help ❤
That line is a compound statement, because it has a lot of methods calling each other in a single line, without storing the variables
You can break it down by storing every or some of the parts mentioned here in their own variables
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
The code written in methods like Start, OnEnable, Awake etc. will only work once when needed, yes
OnEnable is called when the script is updated, so, surely, there is no need for it to be called more than that
yea, I mean when stopping the project and starting it again. i want it to reset after stopping the scene and starting it again
How do you stop the scene?
clicking the play button again
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
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?
Sounds like you have domain reloading turned off and you are not resetting static variables correctly
the button clicks but nothing happens
Is the scene not changed?
How do you change the scene?
its a bit complicated. I'm using the steam networking. I can send over the script tho
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);
}
what do you suggest?
im trying to add UI but nothing is showing up even when i add an image
You need to create a canvas
i have
check all of your static variables but, tbh, anyone who calls a Method a void should not be doing Networking
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
When Domain Reloading is disabled, the values of static fields in your code do not automatically reset to their original values
Edit > Project Settings > Editor
Oh! I didnt reload the scene or the domain. I'm so stupid.
Thank you so much
You don't even have an EventSystem
yeah i do
this is pretty embrassing considering I've been using unity for 3+ years :/
Well, does it work now?
yup
Also, SteveSmith was the one to suggested it first.
I don't see it in the image you've sent. Is Canvas just above it?
Yea, I kinda skipped over the message haha
ty both of u @willow scroll and @languid spire
I don't see the canvas
what do you man
Double-click on it
Is that all?
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);
}
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
what exactly do you mean diagonally ? your character is stationary and only ever moving in a vertical fashion it looks like ?
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
Yes I shot myself in the foot when making the pipes go right to left instead of the player actually moving left to right. But I'm writing here to learn if there's a way for me to further add to the illusion of horizontal movement by making the ghost follow diagonally upwards/downwards
typically you would rotate the character around the y axis 180 degrees to make him look left. And you would just always shoot the bullet in whatever direction the character is facing via transform.right for example
so no extra code needed
haha i think ive done this is the most stupid way ever
an easy solution would be moving each of the spawned ghost gameobjects to the left and visually it would look the same as if the player was actually moving forward.
Not really, for an infinite scroller that's a good idea. Whats stopping you from moving the after image effect right to left too (basically in the direction of (Vector2.left - CurrentVerticalMotion).normalized)?
I get the behavior you want, but it makes no sense the way you have designed your character movement. Since your character is only every moving vertically, and you want the ghost to follow its previous path, it would never need to follow in a diagonal fashion.
so basically, I change the character sprite depending on the angle he looks at, Then if the angle is in between two certain angles i know he is looking left so i flip him. The gun he is using is just on a pivot that flip when it hits a negative. I tried using the same tactic on the buttlet but its degrees seem really off ranging from -10 to -10
The only thing stopping me is my own incompetence! So yea I don't know how basically
I edited my message a bit, give it a read
I mean from a technical point sure it wouldnt make sense, but the idea is to make it feel like I'm going left to right
Then move the after image in the same way as the pipes/pillars
Will give it a try thank you
You could just make a list of the spawnedGhostObjects and when ever you spawn the ghost object add it to the list and call this at the end of update:
private void MoveGhostsBackward()
{
float moveAmount = Time.deltaTime * playerMovementSpeed;
foreach (GameObject ghost in ghosts)
{
ghost.transform.position += Vector3.left * moveAmount;
}
That will only move them to the left tho, not diagonally
He can just init them with a direction value and update them from there tho in a similar fashion
it will look the same if it spawns the ghost object on the player
the y pos will be different for each
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.
depending where the player is
Maybe, if for a short duration, I'd have to actually try it out and see what looks better
Either way, he asked for a diagonal movement so there's that
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
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
charachter is now not flying towards to sky thanks but now charachter is now cant moving
fixed
thanks
@keen dew ❤️
it literally visually looks the same
as the effect he wanted
looks like its moving forward
@rough orbit is this the effect you're trying to achieve
with the ghost
It is, thank you! I'm so new to all this that I don't even know what making a list of objects entails though. Guess I probably started at the wrong end by trying to learn through "how to make a Unity game" videos without even understanding how C# works?
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?
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);
}
}
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?
this tells the controller to move once
which line
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
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.
That actually looks okay to me. You add gravity to the velocity and then move based on your velocity.
but what im gonna do
yes
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
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.
i just tried to set values quickly and there is no difference
That does not answer my question.
Did you change the value in the code, or did you change the value in the inspector?
code
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
i tried to change value on inspector
nothing happened i dont know why
Screenshot the inspector for your PlayerMoveEvent component.
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)
what value u think ill enter ?
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);
that's odd, because you did jump into the air when you removed deltaTime from characterController.Move(velocity * Time.deltaTime);
If that isn't logging then the condition is never true
your ground check is wrong, then
I'm assuming you'd know if you weren't pressing space so it's probably isGround
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)
Why does this keep appearing?
Because your code is broken
I'm following a tutorial
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
I have already change the name to the scrip I and still shows it
it is not possible to use Unity effectively without your Console window being open
Show us details
Without details all we know is you missed something
Sure, I'm gonna start the pc
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.
Show code, show tutorial
Whats an !ide
An IDE
Also filename and class name don't match. And you haven't saved the code.
It is an integrated development environment
Visual Studio is your IDE, and you haven't set it up properly
The thing you write code in
Follow this @eager bear https://unity.huh.how/ide-configuration/visual-studio
Line 11 in LimbCollision has the capitalization error btw
How can I change this?
Yes
Rename the file
Ctrl+r
like any other file on your computer
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.
How are they making these Collapsible Headers on the inspector? I am wanting my custom script to have these for organization
With a custom inspector
You can also use NaughtyAttributes:
https://dbrizov.github.io/na-docs/attributes/meta_attributes/foldout.html
hi guys im having a error on my code can someone help me?
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
NA doesn't have that problem
gotcha! I'll try it out
Yes, I am a big child, but I always giggle to myself when someone mentions these.
Seems pretty clear - your code is trying to access a Dictionary with a key that doesn't exist in the Dictionary
how can i solve that?
Figure out what it's looking for and then figure out why it isn't finding it?
Either:
- Make sure your populated the Dictionary properly before accessing it
- Use TryGetValue if it's expected for the key to not exist sometimes
TryGetValue is great for the latter situation
I've replaced all of my "if has key, then..." with it
nvm I can read
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!
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
So, you press E, you destroy GunInst and set GunInst to a clone of Gun2, at the position and rotation of Gun, with GunWrapper as its parent. Is that not what you want to be happening?
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
The gun should just have a script on it that either handles the shooting entirely, or has a function that returns the spawn point for the bullets
Just use that
how can i know where to find that variables?
i dont understand nothing
how can i access a variable from a script from a prefab?
bro i need to make this project to school and i dont want to understand just make the fucking game
i can just do something like GunInst.GetComponenent right
Instantiate returns the object you created. Access it from there
The point of school is to just fucking make you understand, not to make the game
and im trynna solving this error all day
yes
would i get the script
you've already been shown how to solve this and given the code to do it
component
why is it always students who assert "i don't want to learn anything"
why are you learning game dev if you don't want to learn
bro im done with this shit i just want to finish it to have a good grade
then reap what you have sown and fail.
you think you deserve a good grade when you make no effort?
i can't stand this sort of attitude
wait how do i get a certain gameobject componenet? GetComponenet<GameObject>
GameObject is not a kind of component.
No... the actual name of the component you want
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 ?
don't take the class if you have no interest in following it... Schools are accomedating if you put your leg forward
where would i put that
So then you can click on all of em and read all of the things
if you can't understand the concept of dictionaries, then fallback onto stuff you already know like arrays
in the <> of GetComponent
MyScript myVariable = myObject.GetComponent<MyScript>();
i chosse to make a game at the beggining but no one told me it was gonna be that hard
Game dev is very hard
im gonna try to understand it
game dev is like any other coding profession, but you actually have to put all those optimization techniques to use
not for me
so how would i go about getting a gameobject from a prefab
i see the beuty in it but not for me
I told you , Instantiate does that
sorry im tweaking
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
what is MyScript?
ive got this to spawn in my prefab
` cs GunInst = Instantiate(Gun2, GunWrapper.position, GunWrapper.rotation, GunWrapper);
MyScript is your script
whatever component you have on the prefab
Like a Gun script or something
Whatever YourScript is
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
what component are you trying to use
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
ah its not a componenet, its a child
then just link the prefab using a public variable
drag it in the box
or serializefield
cant use getcomponent for the whole object
i need the spawn point which is inside the prefab
What do you intend to actually do with this object once it exists. Do you need to call any sort of functions on any components of it?
"[SerializeField] GameObject SpawnPoint;"
then save the code and drag the object into the box
it is like a reference
to the object
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
As i said ages ago PUT a component on the root parent object of the prefab that has a reference to the thing
So your prefab should have a script on it that holds a reference to the spawn point. Then, you use that script as the MyScript that Praetor suggested
Way back here #💻┃code-beginner message
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?
my prefab doesnt hold any scripts
are you saying i should make one
Thats why I said to make one
make a list. Shuffle it. Pull the first or last element out to pick a random one.
and why praetor said to make one
Yes we said that many times
and the script just holds a reference?
Oh I see, so remove it from the list then shuffle/randomize it in order to get the selected value
There are many good reasons to have one for a gun
you only need to shuffle once
If you shuffle the list once, you can just keep taking whatever's next in the list
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
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
im sorry but this is still confusing me
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
So, the variable you're intantiating your prefab from should be of that type. Then that changes the return type of Instantiate. You can then get that reference from your script
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
Floating point precision. It's not exactly -200, it's probably like, -200.000000001
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
What are you doing where you expect an object to have these exact magic number positions?
I think this may be the issue yeah, I tested to see if (-200 == the local transform position) and it didn't, even though it shows up as precisely -200 in the inspector? I'll just use a different solution at this point as you say. it's just frustrating as when I make the slots "move" I do specify exactly -200, but I guess it's just a tiny bit off
if you want to do that convert your Vector3 to a Vector3Int, then you can test for equality
1 img in the Scene 2nd in the game how can i fix this ?
One of the flaws of trying to fit an infinite set (all real numbers) into a finite space on disk. Some numbers just literally cannot exist precisely.
what does "vaeriable your intantiating your prefab fdrom" mean
What variable are you passing to the first parameter of Instantiate
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;
why are they static
oh i was trying something else
i was trying
bulletSpawnPoint = ReferenceTaker.SpawnPoint;
[SerializeField] public GameObject SpawnPoint; [SerializeField] public GameObject LeftHandWrapper;
Yes, now assign those on your prefab
do you have any compile errors
nah
did you save the script after changing it
yes
Show a screenshot of your console
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
sorry to be such a pain but what does instantaiate returns mean
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
oh i seee
the type of variable it returns is the same as the type of variable you are instantiating
public void MyMethod() returns nothing
public int MyOtherMethod() returns an int
so with GunInst = Instantiate(Gun2, GunWrapper.position, GunWrapper.rotation, GunWrapper); its returning and i can then get my script from some sort of GunInst.
Some sort of GunInst? You would access it from GunInst
Or as Digi said, just make Gun2 the script itself
So, you'd make your Gun2 variable of type ReferenceTaker, and then you'd be able to store that in a variable of type ReferenceTaker. You can change GunInst to ReferenceTaker as well to run this line
if i made gun2 the script wouldnt it then not make the gun
yes
it clones the object
and it clones gun2
If the script is on a gameobject, then it will spawn the gameobject
It will simply give you a REFERENCE to the script
oh okay
would i need to reference the script some how
i cant just put ReferenceTaker instead of Gun2 right
No, you do not need to change the name of the variable
Names have nothing to do with how the code works at all
Change the TYPE of the variable though
Yes, do not write ReferenceTaker
Write Gun2
ok
tio what type
What type do you need it to be
Hint, the script
cause its already a gameobject right
Yes, you do not want it to be GameObject
😭 what type does a script come under
is it the variables im trying to grab?
im looking at the different types atm
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
You cannot call instantiate on a type, you have to call it on a variable
Is there a built in method for shuffling in Unity? I've searched high and low but the closest I could find is this:
https://learn.microsoft.com/en-us/dotnet/api/system.random.shuffle?view=net-8.0
You were supposed to change the type of the variable, not change Instantiate
No built in way, you'll need to either grab a library or code up the algorithm yourself
Darn, I was hoping to avoid that haha
won't work with my current system so I'll just go about it a differen way, thank you for your help anyway!
Extensions I use in a lot of Unity projects. Contribute to jschiff/unity-extensions development by creating an account on GitHub.
understood, appreciate your help!
im kind of getting it, but i dont understand how this comes together. I
Oh sweet, so I just copy over this file into my project and bingo bango I have all this additional functionality?
in the instantiate
Instantiate gun2
No
Do you know what a "Type" is
You do not touch the instantiate from how it was earlier
You change the VARIABLE that you named Gun2
is this going in my main script im supposing
what the heck is a "main script"?
I literally have no idea. It is wherever you made the variable
You are changing the variable you already have to a different Type
You should know
kidnof
is it in my referencetaer script where im storing the references or the minanscript with the instaitation
https://www.w3schools.com/cs/cs_data_types.php
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
i know what a variable is
I don't know. How could I possibly know that?
Then change it. You know where Gun2 is. Change THAT variable
So, change the type of that variable
to the type you just made
omg im trippiong
Then you know that every variable has a type. Use the correct type for your variable . . .
yes okay that makes sense
i think the gameobjects being a type was tripping me
public [Something] Gun2
class
Everything is a type
Btw, GameObject is the name of a class.
Now change it's type
There it is
okay the tyoe us gameobject so im going to change that
Yes
to referenecetaker
yes
Now you also have to either change the type of GunInst or store it in a different variable of type ReferenceTaker
Now you can do GunInst.SpawnPoint or whatever variable you need from it
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]];
}
just like this, assuming you shuffled hiraganaArray beforehand
If hiraganaArray is shuffled, then that is randomized
Okay it says the object in the instantiation is null
Did you drag in your prefab back into the Gun2 slot since you changed the prefab
you have to assign the prefab to the field in the inspector
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
I don't understand what that sentence means
yes
thats what it is when im getting the error
you have another copy of the script in the scene
Should probably be a prefab with the script
Is this from the scene?
Nm, certainly what praetor said
So let's say the shuffled array is [あ い う え お], and when I go to fill in the buttons, the first button is going to always be the array[0], in this case the answer is あ
what does this mean
Why is the first button going to be the answer
How is the first button always the answer if you've shuffled it?
It means what I said. You have another Gun script in the scene, and it's not referencing the prefab properly
It means you have another copy of this script in the scene
Because of the way I'm for looping through the array
for (int i = 0; i < 4; ++i)
{
answerButton[i].text = answerKey[hiraganaArray[i]];
}
like attached to another game object
Yes
Or even the same game object
I don't see anything here that will do that. Can you explain what you're talking about? Are you saying that's what you want or that's what's happening
That is what's happening
If you shuffled it, it has an equal chance of being in any of the slots
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
wdym by "pull the first shuffled value"
what did you actually shuffle?
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
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
maybe shuffle the answerButton array instead
If you don't want the answer to be the first value then don't pull the first value. Pull a random value instead.
public static void HideMe (Enemy enemy, MaterialPropertyBlock materialProperty)
{
enemy.GetComponentInChildren<SkinnedMeshRenderer>().SetPropertyBlock(materialProperty);
}```
Aren't you only setting the block on ONE renderer here?
No that won't work because one value has to be the answer, and just randomly selecting values will just give random answers
And why can't you make a random value the answer?
And the values are already shuffledt o begin with
I don't think so - the object starts off as seen and all of the child objects are then hidden.. so it's only when I set it back that it seems to break
Pull the answer, then three random values from the shuffled list
Put those 4 in a list or array.
Shuffle THAT list or array.
use those as the possible answers
okay how would i reference the gameobject(prefab) that the script is attached to(referencetaker)
I don't understand this function. Why is it doing GetComponentInChildren<SkinnedMeshRenderer>()? You already have an array of the renderers, why don'y you just pass in the renderer as the parameter instead of the Enemy?
public static void HideMe (Renderer rend, MaterialPropertyBlock materialProperty)
{
rend.SetPropertyBlock(materialProperty);
}```
HideMe(enemyMesh, origPropertyBlock);```
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);
}
}```
Hi I finished to create my game, how can I build it (it's for Android)
you probably have the value of maxHealth set to 0 in the inspector
Also, for future reference !code
You beauty!! I've been staring at this for so long and kept assuming it was something else 🙈 . Thank you thank you!
Well I can simply adjust it to 100 in the Player Inspector but from the reference I took the code it automaticly took the maxValue of the slider which is that 100. And thanks tho! I will keep that in mind!
Here I could easily adjust it to 100 myself.
But normally that should be automaticly set to that 100 depending on the slider maxValue.
Unity ignores the values in your code once it has been serialized. So the inspector value is always leading
So just for me to understand it right. Thats not nessecary at all 😄
Cause it will be ignored anyways cause I can assign the value in the Inspector.
not what I am saying this
public int maxHealth = 100;
does not need to set the value to `100
because the value in the inspector will overwrite the 100
Okey, so then im doing it by myself with the Inspector. But thanks for enlightening me! 🙂
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
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'
😏 I only know because I did forget and curious behind the why
Got the shuffle working! Thank you so much for the help
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.
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
google on collision exit
OnCollisionExit2D is needed to detect existing the collision
Hey all. I cannot get out of this situation where I do not know how to handle these scripts and break them down for saving. Should I store the Items in a Database so I can get them after deserialize and somehow populate the inventory with the items on load?
Item https://hatebin.com/eulonbdgiw
InventoryItem https://hatebin.com/svmkwpjpbe
InventorySlot https://hatebin.com/zvonmqkcqq
I can provide the InventoryManager script as well.
ok I’m going to try that thank you
think about what your code is doing, it doesn't make sense
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
Ya it makes sense I don’t know what I’m doing I left Unity for a month and came back an idiot 😅
how do i check if the mouse is clicked anywhere but the object
Depends
Is it a 2d, 3d or an ui object?
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
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?
My preference is to use the event system for click detection, i.e. IPointerDownHandler. Then I put a big transparent invisible UI image covering the whole screen that's behind everything in a screen space camera canvas and handle it with the printer down handler for that thing
The easiest way is to use MoveTowards in Update, not Lerp.
Or use DOTween
How can I access the alpha value, of a video player, in a script?
if I do Cutscene.alpha, nothing relevant shows
What is the event system? What does that mean?
The Color's alpha?
I don't think so
VideoPlayer has a float targetCameraAlpha
Which is a properly and can be set
For more help check this too: https://docs.unity3d.com/Manual/class-VideoPlayer.html
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
but it's not working
Does this mean the variable is not shown in the Inspector?
The variable is shown in the inspector, but I can't drag and drop the script into it
This means the types are not the same
What are the types? The type is the script?
Here. The type is the script name?
The type of your script is the name of the class. CutsceneTransition
That's right
You should now show what you're dragging into it
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?
!code
Yes
Yup 👍🏻
This is because the types aren't the same
What should I put as the type?
The object you're dragging should have your script, assuming it's derived from Component
!code
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?
This happens because MoveTowards only moves the value by the 3rd parameter, 0.05f in your case.
To make it work, the 1st parameter should not be constant. This means, you have to use its current alpha in your calculations
The bot is dead today you'll need to look at #854851968446365696 for how to post code
Thanks mate 🙂
Is CutsceneTriggered true for multiple frames?
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
Yeah, right now CutsceneTriggered stays on forever but the alpha stays at 0.05. Doesn't increase
Yeah, because moving from 0 to 1 with a value of 0.05 per frame is going to always be 0.05. Your endpoints are unchanging
The 1st parameter is constant
The first value is the current, not the start
This is the difference between it and Lerp
Lerp does expect constant inputs with a changing time, while MoveTowards expects changing inputs with constant distance
Yeah, it's like a goldfish
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? (:
Is this correct?
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
This is what I have but it instantly changes the alpha. It's not a gradual increase
i would expect this to move it very very very very slowly
Yeah, same
given that you're moving it by 0.0005f per second
- Does it start at 0?
- Are you sure you want it to change by 0.0005 per second? That's over half an hour
It was just for testing
Try adding this log:
Debug.Log($"Changing alpha from {VideoAlpha} -> {CutsceneVideo.targetCameraAlpha}");
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.
didn't we already have that discussion, just without specifying a "door"
I believe so, if you're referring to the player position not being in the right spot when entering and exiting the door
#💻┃code-beginner message
that conversation was about how to set that up in a sane and expandable way
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