#Why does this throw errors in-game
1 messages · Page 1 of 1 (latest)
import {world,ItemStack} from '@minecraft/server';
const {afterEvents} = world
afterEvents.entityHit.subscribe((event)=>{
const {hitBlock,entity,hitEntity} =event
const wrench_breakable = [
"minecraft:repeater",
"minecraft:comparator",
"minecraft:redstone_wire",
"minecraft:minecart",
"minecraft:chest_minecart",
"minecraft:furnace_minecart",
"minecraft:hopper_minecart",
"minecraft:tnt_minecart",
"minecraft:powered_rail",
"minecraft:detector_rail",
"minecraft:activator_rail"
]
if (entity.getComponent('inventory').container.getItem(entity.selectedSlot).typeId== 'rc:wrench'&& entity.isSneaking){
if (hitBlock){
if (hitBlock.typeId.startsWith('rc') || wrench_breakable.includes(hitBlock.typeId)) {
const typeid = hitBlock.getItemStack().typeId
entity.getComponent('inventory').container.addItem(new ItemStack(hitBlock.typeId,1))
hitBlock.dimension.runCommand(`setblock ${hitBlock.x} ${hitBlock.y} ${hitBlock.z} air destroy`)
entity.dimension.getEntities({location:entity.location,maxDistance:6}).filter((e)=>e.typeId == 'minecraft:item' && e.getComponent('minecraft:item').itemStack.typeId == typeid || wrench_breakable.includes(hitBlock.typeId)).forEach((e)=>e.kill())
}
}
else if (hitEntity){
if (hitEntity.typeId.startsWith('rc') || wrench_breakable.includes(hitEntity.typeId)){
entity.getComponent('inventory').container.addItem(new ItemStack(hitEntity.typeId,1))
hitEntity.dimension.runCommand(`kill @e[type=${hitEntity.typeId}]`)
const typeids = hitEntity.typeId
entity.dimension.getEntities({location:entity.location,maxDistance:3,type: 'minecraft:item'}).filter((e)=> e.getComponent('minecraft:item').itemStack.typeId == typeids).forEach((e)=>e.kill())
}
}
}
})```
Debug Result
There is an error in this [code](#1125256662593327176 message):
[36m<repl>.js[0m:[33m18[0m:[33m67[0m - [31merror[0m[30m TS2339: [0mProperty 'selectedSlot' does not exist on type 'Entity'.
[7m18[0m if (entity.getComponent('inventory').container.getItem(entity.selectedSlot).typeId== 'rc:wrench'&& entity.isSneaking){
[7m [0m [31m ~~~~~~~~~~~~[0m
it works in game, the only problem is that it throws that error
Use optional chaining operator
That is because when you doesn't have any item in hand it returns undefined
?.typeId
instead of
.typeId
still throws error
I have no idea