#💻┃code-beginner
1 messages · Page 469 of 1
Trying to think of a way to do a "box cast" but one not beholden to physics.
The reason for it is to see what a 1x1x1 cube/box passes through on a grid between two points.
np, it's much nicer to install the NaughtyAttributes package. it's free and they have a ton of useful custom attributes for the inspector . . .
Sorry was busy, but ive implemented this, and am running into an issue with the angle checker, And it mis declaring the angle
Insteresting. I will check this out.. ty
if(CustomIsGrounded && Physics.SphereCast(transform.position, groundCheckRadius, Vector3.down, out RaycastHit slopeHit, 2f))
{
hitPointNormal = slopeHit.normal;
angle = Vector3.Angle(hitPointNormal, Vector3.up);
heres the angle code again
you mean, you just want a box to see what it touches or passes through?
More like what grid positions it passes through. Grid positions do not have colliders and there are no collisions involved in what I want.
Imagine a graph paper, and you got two, cells(?). One's the start, one's the end. I want to project the start square in a straight line to the end square and record what other squares are hit along the way
i believe pathfinding will do that for you . . .
Navmesh pathfinding? This is a turn based game that uses a grid
Navmesh isn't the only pathfinding solution. I opt to A* unless there's freeform movement
more like A* or dijkstra's . . .
and before you even think about it, Imma go ahead and say that I didn't like this asset and ended up writing my own solution within a few days when I needed it
however there are cheaper ready solutions that you could get if you don't wanna code your own for whatever reason: https://assetstore.unity.com/search#q=A* Pathfinding
My goal is XCOM 2 style movement, which is "go exactly to location, unless there's an obstacle in the way. Otherwise, A* pathfind around it until there's no obstacle in the way"
At least, that's what I've got through messing around with it
Here's a variety of examples for what it's like and what I'm aiming for atm.
I'm not sure about the moment the character is moving, but the positioning seems to be grid based, so A* should probably handle that.
Yeah, the in-between is what I'm struggling with. Like that first image? Just go straight to the location
the free version includes something grid based
https://arongranberg.com/astar/docs/gridgraph.html
Class documentation for GridGraph: Generates a grid of nodes.
I'd assume that both grid-based A* and something similar to a navmesh are used.
In what context for each I wonder? Navmesh until there's something in the way?
A* could be used to make sure there's a path to the point. And the navmesh to get the shortest path towards it.
Definitely going to nab this instead of trying to reinvent the wheel
This is just a guess though, they probably have a system that integrates both the grid and direct path finding in one system.
Apparently Xcom2 is built on UE3.5. But Unreal engine is way more lenient with source code access compared to Unity, so I wouldn't be surprised if they have their own system or modified heavily one of the ue systems.
Sadly I think the actual pathfinding stuff is native to unreal, so can't access it just from the modding resources as far as I can tell
I'm not sure how modding is related here at all. Modding depends on how much the developer decides to expose via modding.
True
Where's the free version of this?
Oh wow, that asset seems to do things very closely aligned with what I want
sliced SpritedRender changes in width/height when changing from Empty to containing a Sprite, is this normal behaviour?
i've currently solved this by adding an invisible 1 pixel Sprite, instead of letting it start empty.
on the website there https://arongranberg.com/astar/download
how can i smoothly rotate the camera while it is being moved? i tried a couple of things and it just doesnt work
Just smoothly rotate it the same way you'd do it when it's not moved
Where Vector3.up should be changed according to where it should be rotated
transform.Rotate(rotateSpeed * Time.deltaTime * Vector3.up);
private void LateUpdate()
{
transform.position = Vector3.SmoothDamp(
transform.position,
target.position + offset,
ref currentVelocity,
positionSmoothTime
);
transform.rotation = Quaternion.Lerp(transform.rotation, currentRotation, rotationSmoothTime * Time.deltaTime);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
ToggleGamemode();
}
}
public void ToggleGamemode()
{
if (toggle)
{
offset = new Vector3(0, 12, -30);
currentRotation = Quaternion.Euler(16, 0, 0);
}
else
{
offset = new Vector3(0, 0, -30);
currentRotation = Quaternion.Euler(-8, 0, 0);
}
toggle = !toggle;
}
```That also works?
yeah
i think it does
I have two arrow buttons that I want to cycle forwards and backwards through a list of materials that are applied to an object. Is there a way to check in the method which button has been pressed?
{
}```
It shouldn't work, since rotationSmoothTime seems to be a constant value you don't adjust using Time.deltaTime. You have to add it instead
currTime += Time.deltaTime / rotationTime;
idk it works
And put it inside of a Coroutine
Hi.. Is there a way to give more than 1 tag to an object or other identifiers ? like give a tag and also another identifier I can use to refer to that object?
You can only assign one tag, but you can identify and object by it's components.
what do you mean?
TryGetComponent is a great workaround for that
The components attached to the object. Like check if the Player script is attached
Or the Bomb and Throwable scripts.
Whatever you want
If the object has a certain component, it might be the object you're looking for
Because I have a situation. where I want that the bullet will always be deleted when it hit an enemy so I would use enemy tag in all enemies.. But i need something else to distinguish them for other things. But all my enemies or most of them will have same scripts attached. They will just have dif variable values in general. Maybe is there a way to put script on all my enemies and inside that script I create IDs? and somehow I use it or something like that?
if(enemy.SomeProperty == theValue)
hmmmm ok makes sense
what i do is create factions using an enum. every character has one. The bullet can just check the enum
kinda just like assigning them a team
If you haven't found a solution yet, what you can do is modify the method to add an int parameter, and in the first button pass -1, and 1 for the second.
That way you keep only one, and can add the parameter to a variable representing the current material index in use.
i found a solution already, but thanks for the answer
why exactly am I getting an error here?
{
wheel.GetComponent<MeshRenderer>().material = currentWheelMaterial;
}```
Maybe consider showing the actual error from the console window
Where did you copy this code from? If not, what exactly are you trying to do?
i didn't copy it. I'm trying to change the materials on a prefab so that when the prefab is spawned, all the changes the player made in the customisation screen are saved
Your for each statement looks like it's expecting a collection of mesh renderers
it partly works
mesh.material = currentCarMaterial;```
specifically, this works. The singular mesh renderer on the prefab gets the new material applied when the save button is pressed. It just wont work for the wheels, and I'm not gonna do one for each because thats jarring
there has to be a way to do a foreach, and also find all of the wheels
Yeah, looks like you simply inserted invalid code into a foreach statement tbh
To use the foreach statement, you've got to provide it a collection to iterate.
if i do getcomponentsinchildren then i can't use Find
Well, logically you'll need to find all of your wanted objects first then iterate them using the foreach. You're missing the first step, providing a collection of your wanted objects.
Basically something like... (convoluted solution relative to your specifications - precaching is preferred and avoidance of Find)cs var children = ...GetComponentsInChildren<Transform>(); foreach(var child in children) { var found = child.Find(...); if(found != null) { ... } }
yeah i'll have to see what i can do with that
Sure you can, you'd just iterate each child and use find like your original code
Where you original code called Find on one child whereas you've now got a collection of children
The least possible change would be something like... (Edited to reflect your original design)
#💻┃code-beginner message
i think i got it, but i need to finish my menu script now
cant test until thats finished
How can I add cameras to here within code? URP.
Actually IDK how
Not from there, but you can read it there
yea you should be able to from there
I've got an issue with instantiated text not positioning properly, in some rare cases.
textVnMode = Instantiate(textPrefab);
textVnMode.transform.SetParent(floatingTextContent.transform, false);
It's basically 50% off on y axis, it's inside a vertical layout.
Is it possible that the layout doesn't update in some cases?
Is there a way to force layout to update?
When the issue happens, try disabling and Reena ling the layout group in the inspector. If it doesn't fix it, the cause is probably something else.
It didnt help, but it happens only in certain cases, I think it might be due to a coroutine?
In that 1 case a coroutine is running I think
reenabling it at runtime fixes the issue tho, but thats not a solution
It could be a timing issue indeed. I'd check the layout group API for methods that allow rebuilding the layout.
Alright thanks
That didnt work, I tried few things.
What worked is adding Layout Element to the Verical Layout group and setting Min Height to a higher value, to match the text.
Hey, is this the right place to ask questions? 🙂
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
I was wondering if I could make my sprite look sharp, I think I messed somehting up
So you did not bother to read the bot message I just gave you
Ah, I understood that as ask! lol sorry
where is the hdrp material thing in unity 2022
and i dont see a package for it
nvm found i t
Well that's definitely interesting
Does the angle code work on a normal slope then?
You caught me at a time where I was sleeping 😅
im not exactly sure where to look in documentation exactly but say i have two colliders, and i want it to do a specific thing if the thing its colliding with has a specific tag, how would i go about that, and what's the correct function?
is it OnTriggerEnter?
OnCollisionEnter or OnTriggerEnter
or you can use other things that are part of Physics.
specifically the Overlap and Raycast or similar
i didnt expect this bit to be as complicated as it ended up being
i cant escape raycast 
it is easy
you dont have to do a raycast
doing any type of reliable interactions require some sort of physics functions, raycasts are great because they only need Colliders to work not rigidbodies like OnColl/OnTrigg do
time to begin studying ig
https://youtu.be/EINgIoTG8D4
Watch this video in context on Unity's learning pages here -
http://unity3d.com/learn/tutorials/modules/beginner/physics/raycasting
How to use Rays to detect line of sight and angular calculations.
Help us caption & translate this video!
Sadly even these old videos don't point out that LayerMask is not to be confused with the Layer number on a gameobject, even if they said so
So I just can't see the raycast itself?
no, but unity has built in Physics Debugger that will show you all casts
Does anyone know what I should learn about when it comes to turn based combat systems?
depends what you know so far?
i dont really understand what i should do, im kinda lost
how i loop through jobject storing more jobjects
learn enums
learn arrays
etc.
nested foreach ?
not nested
just it gives me jtokens not jobjects
and i cant seem make use of them
i saved entirety of my json with jobjects
no like literally everything is jobjects
i have jobjects inside jobjects inside jobjects
i vant to make single loop that will get me one step down
I have a bunch of objects moving towards the player and I want to reset them to their starting place when the player dies. In the awake method I assign my Vector3 array of positions to the Vector3 of the GameObject array but I am having trouble setting the Vector3 when the trigger is entered
public GameObject[] tracks;
Vector3[] startPos;
void Awake()
{
startPos = new Vector3[tracks.Length];
}
void OnTriggerEnter(Collider player)
{
tracks = new Vector3[startPos.Length];
}
JObject outerObject = JObject.Parse(json);
foreach (var property in outerObject.Properties())
{
Debug.Log($"Key: {property.Name}");
if (property.Value is JObject innerObject)
{
foreach (var innerProperty in innerObject.Properties())
{
Debug.Log($" {innerProperty.Name}: {innerProperty.Value}");
}
}
}
}```
try it
why is it an array ?
cause there are 6 different objects
should I make 6 variables?
oh this is some type of object manager?
ugh not really I dont think but I could eb wron
im basically making subway surfers and when the player dies I want the tracks to reset to their original position
and there are 6 different tracks
d you actually understand any of that code?
could use a dictionary
I think I do
yeah also, how did you write an array without knowing what you need array for lol
I know you dont
alright
I need the array for the object positions
so then what was the point of asking
have the objects register themselves to a dictionary stored in on 1 script
or have each object track their own original pos
okay, I havent used a dictionary before but Ill look it up
can I have them do that with the dictionary?
you dont need dictionary for that one, just store a Vector3 on each object
startPos = new Vector3[tracks.Length];
initialize the startPos array to an array of Vector3.zeros the same length as the tracks array
tracks = new Vector3[startPos.Length];
try to set the tracks array (which are GameObjects) to a new Vector3 array, which it cannot do
its just a fancy way to store information (key value pair). Think like real life dictionary
how do you store a vector3 on each object? would I need 6 different variables
why do you need 6 ?
cause there are 6 different objects I need to reset their position
each object has their own script ?
oh okay I see
is that effecient? like there isnt an issue with having a different script on each object?
Vector3 originalPosition
Awake() { originalPoisition = transform.position; }
not something to worry about as beginner , especially if you have not a lot going on in Update
okay thanks I'll try it
typically if its doing something like that you can use a single script..
each values assigned per object will correspond w/ that instance of the script
soo u could use 1 variable
public Vector3 positionToResetTo;
and change that per object
same logic... different data
but yea, while ur learning nothing wrong w/ doing it the way ur most comfortable.. and then later on you'll adapt, less is more
Can someone please tell me a better way to do this?
I need a GlobalGameManager script that just exists and loads scenes, stores global variables etc.. I also place a LevelInfo object with a LevelInfo script that is supposed to have a scene selected as nextScene and load it. When I tried to do this I found out that you can't serialize Scenes in unity, so I switched to strings. After that, it turned out these scripts have something massively wrong with them. I don't know how to do this, and google isn't helping.
GlobalGameManager script -> https://gdl.space/iweyatajog.cs
LevelInfo script -> https://gdl.space/voduyacosi.cs
yo any1 can hop on vc for like 2 minutes and help me with a few general stuff please?
Guys, I want to ask a modest question about the save/load system.
The problem is that it's registered as AsSingle, which means I use it in the LoadPlayerProgressState, and as a result, I can't save data from any part of the application anymore. What should I do?
I don't think anyone is going to do that. If you want help, you may consider asking your general staff in the appropriate channel.
ok...
then how do I fix that..
Maybe you could describe what's wmassively wrong about them?
You have to consider learning Unity basics !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
GameObject does not have a definition for getComponent, since methods in C# are written in PascalCase, which means, it's called GetComponent
this appears.
What does the error tell you?
so the problem is cuz I didn't used capital G?
Yes. A bigger problem is that you haven't checked docs
That's it's not been added to something in the build settings. Do I really need to do something like this for every scene?
I'm fine with that, just asking
Surely, every scene has to be added to build settings if it has to be opened in your game
You can add existing scenes by pressing a single button, but you'll have to do that after creating every new scene, since it's not done automatically
aight I deal with a lot of small problems like that cuz my Visual studio doesnt show that redline when there is an error do u know how to fix that by any chance?
Of course. That's from what you should've started. You must configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Like this?
Yes
1sec
finally icons 
!Ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
you're meant to read it not spam it..
I just typed it 1 more time just to see if it will be the same for me
but its just 1 more time its not spaming
Of course it would be the same. And yeah, please don't do that. It is quite large and on mobile pushes a lot out of view.
We do indeed call it spam even if only one time
Unfontunately, I don't have vip commands, so it also works the same for you
Allright sorry
Im new here and to unity in general so im just trying to figure out everything
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class PlayerData
{
public static int coins;
public static int level;
public static List<string> ownedSkins = new List<string>();
public static string equippedSkin;
public static void AddSkin(string SkinID)
{
ownedSkins.Add(SkinID);
}
}
Hello, i have a code like this that i will use to load players skin when they start a level. How can i create an AllSkins to get any skin by just providing name? Since the code is static i cant manually add all of my skin scriptable objects to the list
why is everything static..
because i save this class to a file when the user leaves
and i load it back when they join
and i want it to be usable globally
ig you don't know yourself why its static
i want it to be usable globally
so make a singleton and make the Instance itself static.
then you can put whatever you want in through the inspector
should i make it a prefab and copy it into every single scene
nah you can use DontDestroyOnLoad and persist it through diff scenes, just make sure its on a MB script
thanks
so basically make the containing class static instance then have playerData be serializable
should i keep the coins and levels variables static
no need
they're already public
public class PlayerManager : MonoBehaviour
{
public static PlayerManager Instance { get; private set; }
[SerializeField] private PlayerData playerData;
public PlayerData PlayerDataInstance => playerData;
[Serializable]
public class PlayerData
{
public int Coins;
public int Level;
public List<string> OwnedSkins = new List<string>();
public string EquippedSkin;
public void AddSkin(string SkinID)
{
OwnedSkins.Add(SkinID);
}
}
}```
what does => mean
expression body syntax. that is creating a get-only property
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerDataManager : MonoBehaviour
{
public static PlayerDataManager instance;
[SerializeField] private PlayerData playerData;
public PlayerData PlayerDataInstance => playerData;
public List<string> AllSkins = new List<string>();
private void Awake()
{
DontDestroyOnLoad(gameObject);
instance = this;
}
public void AddSkin(string SkinID)
{
playerData.ownedSkins.Add(SkinID);
}
}
[System.Serializable]
public class PlayerData
{
public int coins;
public int level;
public List<string> ownedSkins = new List<string>();
public string equippedSkin;
}```
How does this look
yea although I would make the singleton how the the link I sent you does it
use a get only property with a instance check for any copies, just incase
thought you said you were gonna use scriptable object to store all skins
i will
i accidentaly wrote string
why do i get this even though they have the same name
did you check for compile errors?
oh it was because of another script
thanks
@rich adder by the way why did you do something like this instead of making it public
my bro jumping twice :(((((((
its good practice to limit where that can be changed from, if it must be accessed from outside ideally for reading only purposes. if it must be changed from another script, a Method or at least a property is better so you can keep track of changes better
whats the difference
How does one add knockback when an enemy attack is 2d
its mainly for self-protecting yourself or whoever writes code with you. Prevents mishaps, if you want to learn more read about "Encapsulation"
i can still edit the values outside the code
no, you would write a method for that ideally
i can still edit it
wdym outside "the code"
its all code lol
are you talking about outside its own class?
rigidbody
Basically when I try to add knockback it doesn't work
doesn't work(
yes
someone help me please with my shitty code :3
im asking whats the difference of using this instead of making it public
oganizing mainly, prevents other scripts accidentally changing it and you forgetting about it later on, then not know which one is changing it..
jumping twice? you mean in the air ?
other scripts can still change it
yes sir 😦
yeah cause its public
I was talking about the PlayerData itself
if you want whats Inside the PlayerData to have the same thing you would also use properties there (but you wont be able to use inspector so no reason to)
I wanted it to only jump one and be blue while in the air but this dude is defying him creator by making him jump twice in the air
doesnt this code edit the player data
you're changing coins yea, you're not replacing PlayerData with another playerData
then your gravity check is wrong if it still jump while in air
same thing as what
thank you very kind and handsome man
i shown a quick example, you could technically do
private int coins;
public int Coins => coins;```
but you dont need to worry about this in beginning
what does this do
it would make it so only PlayerData can change coins
no other script can directly, only read it
like I said don't worry to much about it now, later on it might make more sense
is it the same thing as doing private set public get
yes
well you have a backing field here. edit ops fixed mistake
so it would just be closer to
private int coins;
public int Coins
{
get { return coins; }
}```
thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttachableItems : MonoBehaviour
{
List<Collider> colliders;
float oldTime = 0f;
void Start()
{
oldTime = Time.time;
colliders = new List<Collider>();
}
void OnTriggerEnter(Collider collider)
{
if (!collider.isTrigger)
colliders.Add(collider);
}
void OnTriggerExit(Collider collider)
{
if (!collider.isTrigger)
colliders.Remove(collider);
}
}
how can I get List<Collider> colliders from another script? or should I do it that way? (this script is attached to gameobjects and the other one to the player)
make a public property or a method
public List<Collider>GetColliders(){ return colliders; }. Right now its private
what is attachable items doing exactly?
gets items near that item and gets them into colliders then from other script I would get add forces to 2 items to go near each other and combine them
actually I think I don't need attachableitems
because it's too messy that I don't know what I'm doing
well there are 2 cubes behind each other
there's this script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttachItems : MonoBehaviour
{
public GameObject item1;
public GameObject item2;
public Camera cam;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp("e"))
{
var ray = new Ray (cam.transform.position, cam.transform.forward);
if (Physics.Raycast(ray, out var hit)) {
if (hit.collider.gameObject.tag == "Item" && hit.collider.gameObject.GetComponent<Rigidbody>())
{
if (item1 == null)
item1 = hit.collider.gameObject;
else if (item2 == null)
item2 = hit.collider.gameObject;
if (item1 != null && item2 != null)
{
Debug.Log("combining 2 items");
Debug.Log(item1 + " " + item2);
item1 = null;
item2 = null;
}
}
}
}
}
}
these 2 cubes are item1 and item2
on
if (item1 != null && item2 != null)
{
Debug.Log("combining 2 items");
Debug.Log(item1 + " " + item2);
item1 = null;
item2 = null;
}
I want these cubes be pushed to each other (so they're actualy attached) and attach
so that there's no space field in their center
what does the list of colliders factor into this
are you going to use Fixed Joint to attach them ?
there was some other idea a few days ago but I forgot it and it's bad I think
then why did you ask for a list of colliders
i still have no clue the thought process behind it and why you need it
from another script
after I asked I realized it's a bad idea
I saw the setup but you didnt explain the mechanic you wanted to achieve there lol
if you are planning to use a fixed joint or smth you need the rigidbodies
yea if you want to attach them use fixed joint assign the rigidbodies dynamic, change your code to use the rigidbody
or you could parent one to another 
parenting doesnt work with rigidbodies sadly'
the cube has rigidbody
you could make them both kinematic and parenting should work fine
parent one to another and remove/turn off the child rb
but no collisions
also would change it to cs if (Physics.Raycast(ray, out var hit)) { if (hit.collider.CompareTag("Item") && hit.collider.TryGetComponent(out Rigidbody rb)) // do whatever with rb
eg item1 = rb
Rigidbody item1, item2
kinda sucks you cant parent rigidbodies but i can see why, it might cause a ton of problems
yea the physics are simulated in a different place iirc
unity just adapts what physx already has
moving transform disrupts that flow
fixed joint works like parenting, it just sucks at high velocities
😅
Havok is really nice
imo one of the best physics engines
its just expensive
not by much
So i've been trying to make an enemy and a bullet for way too long now, i've followed a tutorial and adapted it to use velocity instead of rb force, i watched the docs of unity and i thought i was ready, but there's many problems, the firerate doesn't seem to be according to what i want, and the most important part is that the bullet is shot at a direction where the player isn't, sometimes it shoots backwards and other times it shoots to the side. https://hatebin.com/hccfnqykqg (ah yeah and the variables have weird names because, well, why not.)
well if you factor in that you have to pay Havok and some other company to use it
do I just do it like that?
if (hit.collider.CompareTag("Item") && hit.collider.TryGetComponent(out Rigidbody rb))
{
if (item1 == null)
item1 = rb;
else if (item2 == null)
item2 = rb;
can you make short vid?
wdym?
i havent looked at havok for a while so they might have done smth different
the gizmos and stuff
what's a short vid?
well through unity its only as expensive as the pro plan, i think unity takes care of the rest
dont quote me on it, its been a while 😅
i thought you had to pay the other company if you uploaded your game but if unity does it, actual cool beans
very cool
a video showing your bullets going out of whack and gizmos for weapon and whatnot, its easier to see a problem sometimes to know what could b wrong
I would but my computer is staying without ram
what
am barely running discord
if you change item type from GameObject to Rigidbody yeah it suld work
I mean that i have too many things open
close them
that slow down the pc too much
it's unity and visual studio code
can you screenshot maybe
mainly interested in seeing the gizmos and all that
also why did you change it from velocity to translate?
i was trying things i think
yeah translate will just phase the bullets through walls,
the player is the capsule with a camera and the enemy is the more red one
idk if you wanted to see something in particular
am not good with english
are the gizmos in Local Pivot mode ?
Where can i see that?
top left of scene view
well if you been setting everything up with that, it could explain why your directions are not what your code is doing
wdym?
and the most important part is that the bullet is shot at a direction where the player isn't, sometimes it shoots backwards and other times it shoots to the side.
why does an image in my canvas for 2d scale from a weird spot and not the middle of the canvas?
No but i mean why setting up everything like that makes directions not work
well not "not work" (i dont know how would i say this)
this is more of a #📲┃ui-ux question
because blue might always point the direction you think it is when in reality it might be pointing else where
so all your transform.forward can be wrong or any other direction
wdym with blue?
fucking hate raycasts
you're missing out, they're easy and powerful
me neither
hold on
Show the code?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
and what exactly is supposed to happen vs whats happening ?
Do CompareTag for one thing
Also add some debug logs to see where the code actually executes
okay so when i get near the thing, it activates an image that says you can click it
Very important consideration. No object rotation will be relevant to Vector3.forward
Probably want transform.forward
thats what its supposed to do
however, for as long as im holding down any movement key, that prompt will stay up
or sometimes it'll just decide its not going to work
if i move towards the object from the side it just doesnt show the prompt
So what could i do to fix it?
i feel like i need to record this
Tried with velocity before and dont really remember how it works.
just told you why
your ray is always pointing the same direction
well can you select what i asked you to select and screenshot it again with arrows of each item that is going /pointing in wrong direction?
switch from Center / World to Local/Pivot
hold on let me catch up
okay so it only works when im facing a specific way, because its referring to the world's direction, and not mine
Could you explain it easier?
indeed
Simply change Vector3.forward to transform.forward
That is it
Vector3 is never the solution 😔
Well, unless you want the world direction. It is often the solution for grids
But rarely for characters that can rotate around granularly
transform.InverseTransformDirection(Vector3.forward) 😛
the long version
my brain will not process such a thing
not today
Vector3 also useful for having proper direction of the world
if my character flips into a roll I wouldnt want transform.down to check for ground, i would use Vector3.down
this is very much a losing battle on my end
something else broke but im reaching exhaustion
joy
i think its redoing interactPrompt.SetActive(false); or true thing every time i move
be glad those are the easy bugs that can be noticed right away and not hundreds of run where you get that edge case 🥲
if i reach that point i might just have to accept that the project is doomed
its doing it as long as you have ray hitting collider .
Did you mean like the bullets transform?
i kinda wanna use a box collider to do this now it feels way simpler 
its at least something i would have grasped
select it withthe move tool
now what
its simpler at first but less flexible and also you need at least 1 rigidbody
can't tell if im off to a bad start or not
i'll use the box collider and if i ever regain enough sanity to try to understand the raycast function better i will
is this when
Wdym?
since they are screenshots you should describe at least which object this is
and whats going on
show the original bullet not Instantiated
And what do you want to see from it?
the same things we've been talking about the past half hr
i said first step was to make sure all your pivots are correct
including the Shoot point
Well the shoot point is the enemy itself
well you should probably have one , put the look at on that one
I'll try
regardless, show it
So i have to make another script for the shoot point right?
not necessarily, just a Reference to its Transform
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttachItems : MonoBehaviour
{
public Rigidbody item1;
public Rigidbody item2;
public Camera cam;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp("e"))
{
var ray = new Ray (cam.transform.position, cam.transform.forward);
if (Physics.Raycast(ray, out var hit)) {
if (hit.collider.CompareTag("Item") && hit.collider.TryGetComponent(out Rigidbody rb))
{
if (item1 == null)
item1 = rb;
else if (item2 == null)
item2 = rb;
if (item1 != null && item2 != null)
{
Debug.Log("combining 2 items");
Debug.Log(item1 + " " + item2);
Vector3 direction = item2.transform.position - (item2.transform.position - item1.transform.position) * 2f;
item1.velocity = item2.transform.position - direction;
item1 = null;
item2 = null;
}
}
}
}
}
}
(the pain never stops)
how can I disable gravity while that item1.velocity happens and when it stops check if item1 and item2 are colliding and attach them (make them move like 1 thing)?
Tried doing it and it's the exact same
the pain never stops
show which direction the Firepoint is pointing at
use pastesite when sending large code
https://gdl.space
The one selected is the shootpoint, yeah, i reused the AI script, but only for trying, maybe it's that and im dumb
the blue arrow shows where the player is
yes but I already shared it
like it is not there but on that way
so its pointing at player correcty?
yes
but shoots completely on other way
which direction did you pass
for bullet
also now put the script back on the enemy , make a reference to the firepoint only for the lookat
then do this
Rigidbody rb = Instantiate(projectile, firePoint.position, firePoint.rotation;
rb.velocity = rb.transform.forward * bulletSpeed
Ahh, all this mess only to make the bullet slower on slow motion
wdym. This is actually important concepts in unity you should be aware of
especially knowing which arrow is what direction, World Space vs Local Space
your old code you're spawning bullet with Quaternion.identity, which means no Rotation
No one ever told me that
I was following a course
worst 14$ ever spent ngl
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yeah but i mean none of them are in spanish
yeah sadly they dont really have text based tutorials as much, so they can't be translated easily..
Hey guys.. when I create a getter or a setter. Is there any convencional naming for that? Because I always want to know if that is variable that I am getting or setting. Normally I use like "" public int PlayerCurrentHealthGetSet {get{return _playerCurrentHealth;} set{ _playerCurrentHealth = value;} }
"" But i find that naming ugly.
Like that: PlayerCurrentHealthGetSet
just CurrentHealth
or PlayerCurrentHealth
Hmm. I see. ok thank you
btw its backtics ` for code snippets , not '
Yeah I miss typed 😛
goddamn it
it seems like i fixed it but somehow it broke the player
if the character crouches it goes at very high speed suddenly
and cant move
but how the hell would this script affect the player movement
how do you know its happening from this?
It dint happen before
what did you change
literally the 2 lines of code you gave me
but now it's bugged
now i wonder
what did i change without noticing
this wouldnt mess with anything on the player
unelss your bullet is collding with player and causing some other issue there
maybe
yup
that's it
it seems that it fires so fast that it makes the movement bug
on the enemy or player ?
player
even though it is set to trigger
if i deactivate the enemy it works normally
not sure how that would ever mess with player then
how can I apply on a rigidbody a mega super force and make it not ricochet from a wall or whatever it collides with? there should be a setting in rigidbody
I just want that effect temporarily
me neither
turn off Bounce on the material (set it to 0) and maybe turn on Friction more

also what the hell
i realized i disabled the attack from the enemy when it started bugging
and it stills attacks (shoots) even with it off
or smth
why the hell is enemy ai so hard
even when it is only shooting
not possible
Update does not run with Disabled GameObject
this ?
Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>(); ?
or whatever
yes
did you actually save..and compile again..
wdym?
when you added // did you save the script and did it compile ? without errors
where is this?
uh what?
looks like some type of custom editor thing, never seen that b4
only the enemy folder has it
I have never seen that before
I dont have a custom editor
or what you mean idk
can I do
IEnumerator something() {}
without initializing the function and then calling it?
wdym without initilizing ?
it's fast script reload or something
wdym by "without initializing the function"
it's the only one i installed
man those things usually more damage than good
but i need it
if not it takes like 1 minute to add a ;
you're relying on a third party to keep things always updated, and that wont break at some point
for an example there's
IEnumerator SpawnItem(float posRange = 0, float posRangeDivide = 0, float pushPower = 0, int quantity = 1, float cooldown = 0)
{
Debug.Log("Trying to spawn an item");
Debug.Log(posRange + " " + posRangeDivide + " " + pushPower + " " + quantity + " " + cooldown);
GameObject sigma;
for (int i = 0; i < quantity; i += 1)
{
sigma = Instantiate(itemToSpawn, Items.transform);
sigma.transform.position = spawner.transform.position;
float randomX = Random.Range(-posRange, posRange) / posRangeDivide;
float randomZ = Random.Range(-posRange, posRange) / posRangeDivide;
sigma.GetComponent<Rigidbody>().AddForce(new Vector3(randomX, pushPower, randomZ), ForceMode.Impulse);
if (cooldown != 0)
yield return new WaitForSeconds(cooldown);
}
}
IEnumerator SpawnItem(something)
can I do it cleaner?
I dont think it is the cause of the problem anyways
it has happened before i even installed it
idk how i fixed it tho last time
ignore the parameters / arguments thing
do what "cleaner"
first of all id at least use String interpolation
this is wild
Debug.Log(posRange + " " + posRangeDivide + " " + pushPower + " " + quantity + " " + cooldown);
vs
Debug.Log($"{posRange}. {posRangeDivide}. {pushPower}. {quantity}. {cooldown}.);
Optional parameters allow you to omit some of them, so you'll be able to do SpawnItem(cooldown: 10) for example
Another option is to create overloads - methods with the same name but different parameter counts or types
well for an example in lua you can
task.spawn(function()
print("amogus")
end)
instead of
function amogus_printer()
print("amogus")
end
task.spawn(amogus_printer)
that's what I want to do here
that's not "cleaner" that's just creating a delegate instead of using a method. i don't see how that would make your code any cleaner either
in fact that would do the opposite of making the code cleaner because you would be declaring the logic inline when creating the delegate instead of just using a method
I'm doing a similar function in a different script, not editing the SpawnItem one
and yet that changes nothing at all about what i've said
how can I do it like with
task.spawn(function()
print("amogus")
end)
tho?
why the hell it is attackin g ahhh
literally deactivated everything that made it shoot
again, that is the less clean way, but if for some reason you want to insist on doing it that way you could use a lambda expression. but again, that is the worse way.
it is in no way cleaner and will likely result in more allocations so in every sense of the word it is worse
ok
Right-click AttackPlayer (not the commented one, the method definition), and choose "Find All References", that will list all the call sites, make sure there are none
Also check strings, maybe you have a Invoke("AttackPlayer", ...) somewhere?
I see no Debug.Logs. How do you know THIS code is running?
the trick is to start shrinking that time into nanoseconds 😛
Put a log in this function. That log will have a stack trace that shows what calls it
Okay, sorry for making yall waste your time
but somehow it is not updating
idk how
like i added a variable in public to realize
oh so it was like I said, it never compiled..
and i even restarted visual studio
are you certain your hot reloading plugin hasn't actually somehow prevented it from compiling your changes?
Make sure you saved and that there's no errors across the entire project.
idk
let me try saving another variable
yeah that asset is probably messing with autocompile
Then, try moving the file to another folder and back (from Unity) to force a compiler pass
^ this , can also right click project view / file hit Reimport
doesn't seem to be caused by the error
like the script
so i think it may be needed to reimport as you said
Soo, Navarone, the code that you gave me is weird
what should firePoint be?
A transform or a gameobject
both give errors
Well, idk if transform gives error
It says cannot convert unitygameobject to rigidbody
[SerializeField] Transform firePoint
drag n drop in the inspector
firePoint.LookAt(target)
etc.
Doesn't seem to fix the problem
39 is the code you gave
huh ? idk what line 39 is
this one
but the one you made
change projectile's type to Rigidbody
you have to drag bullet inside inspector again when you change it
you will get Mismatch or Missing
https://gdl.space/okezinoxol.cs
IEnumerator BringAndAttach()
{
Debug.Log("itgwerogerjoererjgoierjgeroig");
Vector3 direction = item2.transform.position - (item2.transform.position - item1.transform.position) * 2f;
item1.velocity = item2.transform.position - direction;
Debug.Log(direction);
item1 = null;
item2 = null;
yield return new WaitForSeconds(0.5f);
}
how can I predict time that will take item1 to reach item2 and put it into WaitForSeconds? (the time item1 takes to reach item2 is always the same)
that waitforseconds is 100% pointless because it waits to do literally nothing at all
it will have a use later...
okay well why not just use a loop and a yield return null instead
then for your loop you just check if the object has reached its desired destination or whatever condition you want
because it's not always going to reach the target, sometimes it can just get stuck or go into a wrong direction
then the statement "the time item1 takes to reach item2 is always the same" is categorically false
it works like that
and the ones that dont dont move
if it goes through a straight direction then the amount of time should be the same (hopefully?), if it has some obstacles on it's way it's gonna be slower or will actually stop at some moment without reaching item2
okay well the magnitude of the velocity is the number of units per second it will move
did you remove collision between enemy layer and enemy bullet layer ?
Hello I'm made this script that create a new player when someone join the game we are in , but I don't know why, the script can find the bone "Bone.002" of my player and I don't know why
if(!Players.ContainsKey(newID))
{
var playerInfo = new PlayerInfo { Health = 100, Kills = 0, Coordinates = "0", PreviousLivingState = "1", PreviousTeamState = "0", ArmRotation = 0f};
Players[newID] = playerInfo;
player = Instantiate(PlayerPrefab, new Vector3(10, 10, 10), Quaternion.identity);
player.name = newID;
Players[newID].Player = player;
Players[newID].BackBone = player.transform.Find("Bone.002").gameObject; //--> this is the line that don't work
Players[newID].PlayerAnimator = player.transform.GetChild(0).GetComponent<Animator>();
Players[newID].PlayerAnimator.enabled = true;;
}
I use a RenderTexture, that has a custom shader on a 3D plane, how would I flip it horizontally after the custom shader but before displaying it? (not sure where to ask this question)
ideally you wouldn't need to search for that object specifically like that. if you put a component on the root of your prefab that has a reference to the desired object you can grab immediately upon instantiation
I'm not sure I understand what I should do 😅
https://unity.huh.how/references/references-to-prefab-children
pretty much this
Thanks! I'll have a look
If you just want it horizontally, you could just invert the uv axis you need since those are normalized (1.0 - uv.x for example), or if you have an exposed texture in the shader, and you utilize its tiling properties, you can invert the scale on that itself. Or invert the scale of the plane, etc different ways to do it. Do whatever works for your stuff 
https://gdl.space/ijazecesil.cs how can I repeat wait until cubes are touching each other / should be touching each other if they were going through a straight direction?
after I detect it I want them to attach to each other
hey guys how can i fix this
for some context, I got a custom shader from a youtube tutorial for my portals that makes sure that it only fits in the portal the part of the image that my character can see through the portal, and I either need to mirror the camera that takes the picture, or somehow include a function in the shader or in code that allows me to flip it after it does all of the fitting stuff
this is the shader, and ideas?
Shader "Unlit/ScreenCutoutShader"
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
}
SubShader
{
Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
Lighting Off
Cull Back
ZWrite On
ZTest Less
Fog{ Mode Off }
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
//float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float4 screenPos : TEXCOORD1;
};
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.screenPos = ComputeScreenPos(o.vertex);
return o;
}
sampler2D _MainTex;
fixed4 frag(v2f i) : SV_Target
{
i.screenPos /= i.screenPos.w;
fixed4 col = tex2D(_MainTex, float2(i.screenPos.x, i.screenPos.y));
return col;
}
ENDCG
}
}
}
I honestly don't really get how shaders work
so any help would be, well... helpful
do not crosspost. You were already linked explanation to what null reference is and how to fix it
Well like I said, either flip the uv o.screenPos.x = 1.0 - o.screenPos.x;, or figure out how to allow for tiling from the exposed texture in the inspector for that variable (no clue what macro that needs).
Is there some way to get a navmeshagent to calculate a path to a destination, but without actually moving to it? iirc as soon as you do SetDestination, it immediately starts going to the location
the pain never stops
Nice! ty
Hey, I'm not really sure of what you're trying to do here but you could:
void OnCollisionEnter(Collision collision)
{
if(this.gameObject.GetInstanceID() > collision.gameObject.GetInstanceID()){ //Makes sure the code only triggers for one of the two cubes, there might be better alternatives
collision.gameObject.transform.SetParent(this.transform); //set the parent to be the first cube
collision.gameObject.GetComponent<RigidBody>.isKinematic = true; //set the rigid body as kinematic
this.enabled = false; //disable this code for this cube
}
}
I'm not sure this is the exact syntax tho
hey, anyone know how to change the speed that my sprite animation is at in code? i want to do the code in my movement script but i dont exactly know how to change the speed of it from there.
Hey, if you're sprite animation uses unity animator components, you could ise that https://docs.unity3d.com/ScriptReference/Animations.AnimatorState-speed
i was able to figure it out lol, thank you so much!
No problem
Reword: how can I tell if a NavMeshAgent has reached its destination? As well as if it's still in the process of getting to the destination
But it no longer has the build option when I open it
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-pathStatus.html
You can also just check the distance with v3 Distance, or remaininig distance + stopping distance https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-remainingDistance.html
Gotcha, ty!
it's not the solution of what I'm currently making, I'm trying to find a moment when to check the collision and if it collides then attach these bodies. that way a loop wouldn't happen forever if the body never collides
plus with that script I would also have to make another script and attach it to the body which will make things messier and harder...
That's exactly what OnCollisionEnter does, it's only called when a collision happens
You can add that method to an existing script you already have on your cubes if you want to
Hello, is there a way to make a defined component run at a specific time in my code? I'd like a parent component to run at the very end of each frame, after the late update.
There is a script execution order but not sure that's what you want
what is it? we never know maybe it could help me 😄
With this you can specify the order scripts will execute (the order in which unity will call Update())
also my problem is that the gun don't stay in the player hand because the parent constraint is run before the bone rotate
maybe there's a function that returns all colliders the collider is colliding with?
not through a loop way (oncolliderenter is a loop way)
OnCollisionEnter will be called for each collider the cube is colliding with (but only at the start of the colision)
So script execution order won't help, sorry
There is no way to know when to check if a collision happens without checking if a collision happens.
How are you supposed to "know" when to check otherwise?
is there a way to do a one time check?
no problem 👍 😁
You can do an overlap cast and check, yes
if ... then
should I use overlapsphere or overlapbox?
Whatever shape fits your situation
hmm, overlapsphere might be better
Came up with an interesting way to use a navmesh for grid movement, bypassing a lot of coding in the process (A* and others).
Ran into a problem with the pathfinding though. In the image, the wire cubes are what is recorded as the corners for the NavMeshPath. Start position is where the capsule is and end position is on the furthest left wire cube. For some reason, the agent wants to go around through the bottom, with what seems to be a very unecessary "corner" in between the two ones that matter. ON TOP OF THAT, for some reason, it does not want to take a path on the northern part of the wall, which should be shorter. Any thoughts?
For additional context, the center of these corners are where the agent gets its destinations individually set to, essentially creating grid movement, but via the Unity navigation system
Oh, hm. Looks like messing with voxel size helped out. Set the ratio from 2.00 per agent radius to 4.00
How to GetComponent the X-Position?
IDE is Visual Studio btw and I did try and troubleshoot with the API
are there Physics.OverlapBox gizmos?
Elaborate?
thats not how that is done, you get the object first then get the transform of said object.
I did
If you manually add it then no
Is it something like Get(NameOfObject)<Transform.position??>;
https://docs.unity3d.com/ScriptReference/Gizmos.html
you can use the cube with whatever size you want
someobject = GetComponent<Gameobject>();
i suggest you use docs next time for GetComponent
xPos = transform.position.x
Transform and GameObject have properties on component to get them so no need for GetComponent
https://docs.unity3d.com/ScriptReference/Component.html
(Monobehaviour inherits Compoent)
Thank you so much for actually being so much clearer
Honestly I did look at the documentation for GetComponent tho
ended up copying the RenderTexture in a temporary one, using that one with a custom material that has a shader which flips it and then copies it to the original, all in RenderPipelineManager.endCameraRendering to make sure the first shader does not get overwritten so the order is kept, but it works
if you did you would see that what you were doing was wrong
Hey guys. I'm having a wierd problem where the bullets coming out of my gun are following the rotation of the player when it moves AFTER being instantiated. I've looked through all my code multiple times and I can't find the issue.
I have three scripts (relatively small):
- PlayerMovement (attached to the player) https://gdl.space/iliratoyin
- Gun (attached to the player) https://gdl.space/iropupadec.cs
- Bullet (attached to the bullet prefab) https://gdl.space/neqezunugo.cs
if you need more info see the video:
its a child of your player
and bullet spawn point
since the player is moving, so is the bullet
yeah just remove the last value on that instantiate which sets the parent
I think it's better to just make the bullet spawn point a seperate object
it needs to follow your player though 🤔
so its fine and should leave it a child
I can set its position to the position of the player when ShootBullet() is called
seems kinda pointless
just make it a child
you know actually I think Faywilds is right
I dont even need the bullet spawn point to begin with
I deleted that and made the spawn point position the player, and removed the parent
thats not even what he said lol, but alright you do you
removed the parent in code
as of right now they are just in the hierarchy
which is what he said
Im having a issue with my camera and my movement
Hey, so I finally got a chance to work on my game. I removed the camera that was a child of the player and I now have a script that searches for the player and makes it follow them. However, this only works for the first player, for the 2nd the camera is stuck.
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using Unity.Netcode;
using Cinemachine;
public class CameraScript : NetworkBehaviour
{
public GameObject cameraTarget;
private CinemachineVirtualCamera vcam;
public override void OnNetworkSpawn()
{
if (!IsOwner)
{
gameObject.SetActive(false);
}
}
private void Start()
{
vcam = GetComponent<CinemachineVirtualCamera>();
}
private void Update()
{
cameraTarget = GameObject.Find("Player(Clone)");
if (cameraTarget != null)
{
vcam.Follow = cameraTarget.transform;
}
}
Another dumb question.
How do I make variables accessible through all scripts?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Make them public
It says that it doesn't exist when I use it
let me pull it up hold on
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Perhaps you wrote Public instead of public?
You have the method collapsed, uncollapse MovePlayer
Show line 23
Irrelevant tho
Oh, this is a completelh differe script.
you are not accessing movement
The error is in EnemyScript
Everything you showed is completely irrelevant
you should learn how references work
What does that mean
Show the correct script
also you have nested MB classes..
you have xPos and yPos on the Movement script
so of course it wont work
Oh damn. Awful screenshots on mobile. I see the script now
This is why screenshots suck
its an entirely different script you need to access
Honestly I’m just gonna learn this and try to stop being confused so much about Unity
But the issue is that you never referenced the Movement script as dec said. You need to do something like
public Movement movement;
movement.xPos
ObjectReference Dot Variable
The link? I have it pinned in my phones clipboard haha
you have the website loaded lmao
its also pinned in this channel
where?
I've been trying forever to get this to work but I just can't figure it out. No matter what I do I try to make it so when my player hits an obstacle by entering its collider box with an OnTriggerEnter method and then calling a method from another script that resets the position of certain objects in my scene.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design.Serialization;
using UnityEngine;
using static Track;
public class Obstacle : MonoBehaviour
{
Track trackScript;
void Awake()
{
trackScript = GetComponent<Track>();
}
void OnTriggerEnter(Collider other)
{
trackScript.ResetPosition();
}
}
public void ResetPosition()
{
left.transform.position = startPosL;
middle.transform.position = startPosM;
right.transform.position = startPosR;
}
Then I get an error that says "Object reference not set to an instance of an object" on the line "trackScript = GetComponent<Track>();"
I've tried so many things and just can't figure out how to avoid the null reference
Double check the line number for your error. That line is not capable of throwing that error
Anyway it seems very strange that TrackScript and Obstacle would be on the same GameObject so that code is almost certainly not correct
So my character moves in the direction of the camera but eh camera is stuck where the player is facing instead of the player looking where the camera is
its cause I grabbed a method from my trackscript so thats how I called the method in the obstacle script
also I swear it says the same line number im 100% sure
That doesn't make any sense because your code is trying to get the script from the same GameObject
Prove it to me
Show the actual full error message
Track script was null
Show the inspector for that game object
GetComponent would return null and would assign that null to the track script if there isn't a track script component in that game object.
Hello, so im trying to make player look in a certain direction on start. When I press start, my camera is reset to 0 and looking in the direction the mouse was last left at on the screen(ex. If mouse was top left of screen on start, the fps cam will be looking top left).
i tried getting rid of cursor lock but it didnt help
this script is attached to the camholder and Transform cameraPosition is on the player
That's not the same line you mentioned at all
So your "100% sure" was wrong
Anyway it's as I mentioned, your code doesn't make sense. I would expect you to get the script from the object you collided with, not this same object
hey i need some help, i was making a game about combat with colours and i got stuck in a really weird technicality. so basically, what i was trying to create, was a combat system, where the longer i hold space, the bigger and slower the attack "blob" is, and the shorter i hold space, the small and faster the blob is. but what the error is, is that sometimes, the blob first comes out big and fast, and right after that, no matter how long or short i hold space, the blob comes out small and slow. here's the code -
@tranquil zealot !code on how to share code here. Don't just dump it.
📃 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.
📃 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.
You're meant to read the message, not parrot what I wrote.
public class PlayerAttack : MonoBehaviour
{
public Animator animator;
public Transform attackPoint;
public LayerMask enemyLayer;
public GameObject prefabBlob;
public BlobScript blobScript;
bool isBlack;
bool isWhite;
bool isRed;
bool isYellow;
bool isBlue;
GameObject instantiatedBlob;
Renderer blobRenderer;
float startTime;
float endTime;
public float totalTime;
void Update()
{
ChangeBrushColor();
if (Input.GetKeyDown(KeyCode.Space) && instantiatedBlob==null)
{
animator.SetBool("isAttack", true);
startTime = Time.time;
}
if (Input.GetKeyUp(KeyCode.Space) && instantiatedBlob==null)
{
endTime = Time.time;
totalTime = endTime - startTime;
if(totalTime > 0.7f)
{
totalTime = 0.7f;
}
if(totalTime < 0.1f)
{
totalTime = 0.1f;
}
Debug.Log(totalTime);
Attack();
startTime = 0f;
endTime = 0f;
totalTime = 0f;
}
}
void Attack()
{
animator.SetBool("isAttack", false);
instantiatedBlob = Instantiate(prefabBlob, attackPoint.position, attackPoint.rotation);
blobRenderer = instantiatedBlob.GetComponent<Renderer>();
blobScript.speed = (1f - totalTime) * 15;
instantiatedBlob.transform.localScale = new Vector3(0.3f + totalTime, 0.3f + totalTime, 1f);
InstantiateBlob is not null after the first time
Unless you set it to null somewhere else?
Why even check whether it is null in update?
Hello, so im trying to make player look in a certain direction on start. When I press start, my camera is reset to 0 and looking in the direction the mouse was last left at on the screen(ex. If mouse was top left of screen on start, the fps cam will be looking top left).
https://gdl.space/etapuxitoy.cs
i tried getting rid of cursor lock but it didnt help
https://gdl.space/uxaziwezay.cs
this script is attached to the camholder and Transform cameraPosition is on the player
well my intention was to not be able to spam the attack, is that not necessary?
You are using GetKeyDown and Up so it will not spam faster than keypresses. If you want a cooldown, I would just go with a timer.
But if the null check works, that is fine, you just have to actually set it back to null
super condescending for no reason
and not constructive
It wasn't constructive to give misleading information about the situation which made it take longer to solve the problem
this is the beginner chat, you think I'm intentionally giving you the wong information. I thought I was sure, and I wasnt simple as that. you felt the need to be condescending and point out that I was wrong
Be more humble, less confident, since it's the beginner chat.
is it a bad habit to not feel like learning and using some of unities tools like with IDragHandlers, and instead just making my own item to mouse drag
i just made my own for my game cause i was too lazy to look into unities and i prefer it i suppose
being not confident and humble are two different things. if anyone needs to be humble its the one in the beginner chat dicking on people for making small mistakes
you'll make them again if he doesn't, and it's less of being humble and not confident and more of being willing to learn
besides it's a chat for programming why argue? just get to the facts
False. It was an important fact
thats exactly my point. why did he need to point how that I was wrong explicitly
not really, i would get that I was wrong out of any correction
so you'd know for next time
my point is there is a better way to get that point across
What he said was a pretty polite correction imo
No need to be rude to him when he was just helping
one way or another it gets said as long as it conveys the idea oh well
my teachers in school could use that lesson tho 💀
I appreciate the help, minus the condescending tone. thats my point. anything extra to actual constructive criticism which "your statement was wrong" is not constructive. instead he shoulda just pointed out my mistake and left it at that. I also still don't know the fix because he was super vague
and didnt point out what I was missing and just said where I should get the script which I dont know how to do
I tried fixing this problemon my own and came to this server as a last resort. im not js coming here as my first resource
reacting to a message with an x is literally the definition of non constructive criticism
Well, he is unlikely to continue helping after the insults, I will not either. He was not condescending. You could have just asked for clarification, instead of attacking people for no reason. Literally no one was anything but polite and helpful to you before whatever this was
Just gonna block.
Please watch your behaviour before mods take action
I dont want anyone helping me that is condescending so that works idrgaf if i get blocked
okay and i disagree bruh just block. youre going in circles
i hope the mods take action against me for pointing out condescension
you can @ them if you want
i think the point is to just be respectful to those trying to help out even if you feel an indifference
and I'm saying I deserve the same respect, i didnt want to call it out with soft speak so I called it for what it was, condescending.
last thing i say cause i don't want mods fishy with me for sum reason. personally i could see how you think it sounds condescending when he's more deeply telling you to look outside the box even if you feel "100% sure". but morley you should have focused on the help he gave you right after you practically ignored
im not ignoring, i knew exactly what the line said. because he didnt point out what i missed. i still dont know how i was supposed to read the error message. not everyone has the same level of knowledge as you. that guy didnt know how to explain it to me. and thats okay. but it didnt need to be disrespectful
it's because GetComponent is trying to get track script from you obstacle object
you need to make track script variable on obstacle public then reference your track script's object from the inspector
I ended up figuring it out. i think using a different solution. but I appreciate it, thank you for the explanation
no problem, and yeah MonoBehavior scripts are in unity considered "components" so using GetComponent will look on the object with the script that ran it or you can do GameObject.GetComponent() to get one from a different object but replace GameObject with a referenced Game Object
ohhhh thats good to know thank you
!code
📃 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.
so what do I need to do
use a paste site as the bot says
so is this alg
no, you post your code to the pastesite then you post the link to that here
Ok, so you are going to need to add some Debug.Logs in there to see exactly what is going on
could you tell where
Well I dont know your data or setup so no, but basically start with everywhere
ok so it took a while and i figured out how ray works and i got it drawing the ray
we making progress i think 👍
only took me
6ish hours of sifting through tutorials, feeling like im getting nowhere, going through documentation, getting frustrated again, etc.
well this quite the predicament cause idk where
also get @timber wedge banned for this inappropriate message
that black line coming from the camera
every method needs a Debug.Log so you know if it's being run or not. Every if statment needs a debug.log to see which path is being taken. This is Debugging 101
thats the only ray coming out of it right?
that just needs to hit something for it to detect?
you can report it if you think it's necessary
Hello everyone. I tried to subscribe SessionManagers method GameOver to a unityEvent in the EnemyManager OnRechingfinishLine.
public UnityEvent OnReachingFinishLine;
Do you know why this is wrong?
FindAnyObjectByType<EnemiesManager>().OnReachingFinishLine += GameOver;
CS0019 Operator '+=' cannot be applied to operands of type 'UnityEvent' and 'method group'
But this is just fine?
FindAnyObjectByType<EnemiesManager>().OnReachingFinishLine.AddListener(GameOver);
aren't those the same statements?
+= is how you do it for c# delegates
https://docs.unity3d.com/ScriptReference/Events.UnityEvent.html
unity event doesnt use that as an operator
To subscribe to a UnityEvent, you have to use the AddListener method
these 2 works
ah, I see, Thanks!
OK, Debugging 102. Dont just output literals, show some useful data, in this case waypoint index and target
How does "skibidi toilet" printed in both methods tell you which one was called?
Seems like to will have to check the stack trace for each
something is severely wrong im gonna
idk how to do this
Did you actually learn C# basics or just copy/paste this code?
oh
hey this not very nice
i actaully tried
just asking because string interpolation is a pretty basic thing
@devs can sm1 else help this guy is rachet
i was just curious on what variables i could displaye
they have great resources and honestly its better than just trying at random tutorials with rough explanations because they either A) expct you to be pretty far in understanding or B) don't really explain wha they're doing and simply just tell you to follow
hey, could you try be a bit nicer, he is trying his best to help as many people as he can.
ok
in my attempt to record the problem
i have found the problem
i was noticing that whenever i looked down, the raycast was triggering "hey something is in the way", and i couldnt figure out why, and i thought it was the floor
but no the raycast was hitting the player, which i tagged an interactable for some reason
wait ive just reverted back to another problem fuck
hey no swearing
):
im not even sure whats going on here
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
void Update()
{
RaycastHit hit;
Ray ray = new Ray(cam.transform.position, cam.transform.forward);
Debug.DrawRay(ray.origin, ray.direction * interactRange, Color.black);
if(Physics.Raycast(ray, out hit, interactRange))
{
if(hit.collider.tag == "interactBlock")
{
Debug.Log("Something is in the way");
interactPrompt.SetActive(true);
}
else
{
interactPrompt.SetActive(false);
}
}else {
interactPrompt.SetActive(false);
}
}```
i might be doomed
it fixes the problem, thank you, but now its freaking out whenever i move
i mean it was doing it before but now its doing it all the time
raycasts are hard
i m more doomeed I cant even doing nuthing the bro isnt helping me
@timber wedge apologize
now
im sorry ):
good boy
good luck, you need it
@timber wedge @simple fjord Both of you can stop this sort of stuff. This really isn't the server for this.
this is rough
apologies
I apologise for my past actions. sincerely, D1 flickerer
the raycast is still colliding with the interactBlock but whenever i move the player's position, it just bleh
well
What does it mean?
Could you, perhaps, describe the issue?
well its doing this
i have a debug log that whenever the ray cast is hitting the thing tagged interactBlock, which is the white rectangle thing over there, it'll say that something is in the way
and if something is in the way, it will show an image prompt
the problem is that whenever i start moving, even if the raycast is colliding, it starts to just spaz out
im not even sure what exactly is the problem
moving the camera seems to have no issue
How can I help you if you are not sure what is your problem
the problem seems inconsistent
the problem seems most notably whenever i get close to the object hold on
From the video, it only seems to detect the white object when you're not moving
Which could mean the raycast hits the player first
I would debug the raycast position and direction using the physics debugger
Yeah, your player also has the tag "interactBlock"
that was causing a problem earlier but i did fix that
whenever i looked down it would cause it to immediately trigger
Oh, that's your white block selected
Ray ray = new Ray(cam.transform.position, cam.transform.forward);
Well the raycast positionand direction is based on the camera, which i named cam, and whichever way "forward" is for the camera
this is rough
Show the code that executes the raycast
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Here, under this condition
if(Physics.Raycast(ray, out hit, interactRange))
$"name: {hit.collider.name}; tag: {hit.collider.tag}"
something had to be changed because earlier whenever the player looked away it kept it on screen until they looked around
And you already have a Debug.DrawRay, good
Put the string in a Debug.Log, I guess
Yes, I have mentioned printing it, which means using the print method
that would explain why i dont know what it means 😭
Use the MonoBehaviour.print method to print the message I've shown above
Hi guys I have this read only error, what should I do?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
print() is roughly a shorthand to Debug.Log()
Which can only be used on MonoBehaviours, and calls Debug.Log inside of it
give me a moment my head is struggling with this
How is your head struggling with printing a message to the console?
This is the Unity server, this doesn't look like Unity C# code
up until this point ive only been referred to debug.log, so print is new to me
im not fully understanding its purpose but im trying to read the documentation on it
You cannot assign a string's char, if it's inside of an Enumable
You have to set the string fully
Yeah you cannot change a single string's character via the indexer str[i]
You can get the character at this position, but not set it
Yes, here the last part is redundant, since it's not only in Enumerables, but overall
I see thanks
okay i just started tagging everything i can
its hitting... something
im not sure what it is yet, but we're getting there
can i have help pls
!ask a question!
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
do u flicker goon or jelq
What
<@&502884371011731486>
Ah, some slang I'm not aware of?
or perhaps a friend of theirs
bro is this toast
okay its hitting something related to the player
chur
"Hello, friends. I have a question that's been on my mind. When I can't remember how to write a certain code (like how to create a timer... etc. ) or when a question pops into my head, should I research it on the internet or use ChatGPT? Which would be more beneficial? ChatGPT really speeds up the process.
ermm what the sigma
mb flickered a little too close to the sun
i think its hitting the player position object
Guys pls keep it proffesional this is a unity server
@strong wren
just turn off and on
chase